How to make a bot delete its own message after 5 seconds - discord.py

I can't get the bot to delete its own message.
I have tried await ctx.message.delete() and ctx.message.delete(embed)
#bot.command()
async def help(ctx):
embed=discord.Embed(title="List of commands.", description="", colour=discord.Color.orange(), url="")
await ctx.send(embed=embed)
await ctx.message.delete()
await asyncio.sleep(5)
await message.delete()
I'm wanting the bot to delete the command then send an embed: "A list of commands has been sent to your DM's" then wait 5 secs and delete the embed

ctx.message.delete() deletes the message from the user.
But to delete the bot's message you need the bot's message object
from the return of ctx.send() :
bot.remove_command('help') # Removes default help command
#bot.command()
async def help(ctx):
embed=discord.Embed(title="List of commands.", description="", colour=discord.Color.orange())
msg = await ctx.send(embed=embed) # Get bot's message
await ctx.message.delete() # Delete user's message
await asyncio.sleep(5)
await msg.delete() # Delete bot's message
EDIT:
You can use parameter delete_after=(float)
await ctx.send(embed=embed, delete_after=5.0)

Related

How do i remove a command message in discord.py

I am trying to delete the command message (the one sent by the user not by bot)
Ive tried it like this.
#bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith("-"):
wait(5)
await message.delete()
and this
#bot.command()
async def creator(ctx, message):
await ctx.send(f"Example text")
wait(5)
await message.delete()
but none of them work. If you know why please post a solution. Thanks!
In the first code :
import time
#bot.event
async def on_message(message):
if message.author.bot : return
if message.content.startswith("-"):
time.sleep(5)
await message.delete()
Second Code
import time
#bot.command()
async def creator(ctx):
await ctx.send("Example text")
time.sleep(5)
await ctx.message.delete()
If you are using the both of on_message and commands in your bot,
You may want to add this in the end of on_message Event So your bot will handle the on_message event, Then it goes to process commands.
Without it the bot commands wont work .
await bot.process_commands(message)
Eg :
#bot.event
async def on_message(message) :
await message.channel.send("Example")
await bot.process_commands(message)

I want to improve my kick command in discord.py

I have made a bot in discord.py which has a kick command. But I want the bot to say "please tell me whom to kick" when someone uses the command without saying whom to kick. I mean if someone uses the kick command without mentioning whom to kick, the bot will say "please tell me whom to kick".
I am trying to make a good bot so please help me.
async def kick(ctx, member : discord.Member, *, reason=None):
if (ctx.message.author.permissions_in(ctx.message.channel).kick_members):
await member.kick(reason=reason)
await ctx.send(f"{member.mention} has successfully been kickded for {reason}")
if not (ctx.message.author.permissions_in(ctx.message.channel).kick_members):
await ctx.send("You don't perms to play football with Araforce and kick them. Sed")
if not user:
await ctx.message.delete()
msg = await ctx.send("You are a bit idiot, don't you know I can't kick anyone if you don't tell whom to kick? Tell me whom to kick and the go away.")
await sleep(4.7)
await msg.delete()
return
if not reason:
await ctx.message.delete()
msg2 = await ctx.send("Hmm.. Why I will kick him? Specify a reason please.")
await sleep(4.7)
await msg2.delete()
return```
async def kick(ctx, user: discord.User = None, *, reason=None):
if not user:
await ctx.message.delete()
msg = await ctx.send("You must specify a user.")
await sleep(4.7)
await msg.delete()
return
if not reason:
await ctx.message.delete()
msg2 = await ctx.send("You must specify a reason.")
await sleep(4.7)
await msg2.delete()
return
I changed ifs to the error handler, which is necessary because if you won't pass one of the arguments (user or reason) you would get an error.
Full code:
#client.command()
async def kick(ctx, member: discord.Member, *, reason): #if you will change "member" and "reason" to something else remember to also change it in error handler
await member.kick(reason=reason)
await ctx.send(f"{member.mention} has successfully been kicked for {reason}")
#kick.error #cool mini error handler
async def kick_error(ctx, error):
if isinstance(error, discord.ext.commands.errors.MissingRequiredArgument):
if str(error) == "member is a required argument that is missing.": #change this if you changed "member"
await ctx.message.delete()
await ctx.send("You are a bit idiot, don't you know I can't kick anyone if you don't tell whom to kick? Tell me whom to kick and then go away.", delete_after=4.7) #you don't have to use "await sleep" you can use "delete_after" parameter
elif str(error) == "reason is a required argument that is missing.": #change this if you changed "reason"
await ctx.message.delete()
await ctx.send("Hmm.. Why I will kick him? Specify a reason please.", delete_after=4.7)
elif isinstance(error, discord.ext.commands.errors.MissingPermissions):
await ctx.send("You don't have perms to play football with Araforce and kick them. Sed")
Discord error handling example

Deleting the command after embed has been executed

I'm trying to make it to where when the embed for example below is executed, the ?ra1 message from the user is deleted. Thanks for any help.
#client.command()
async def ra1(ctx):
embed = discord.Embed(
colour=discord.Colour.blue(),
title="RIDEALONG 1 REQUEST",
description=str(ctx.author.mention) + " IS REQUESTING THEIR FIRST RIDEALONG IN SERVER !"
)
embed.add_field(name="For CDTOs", value="Please message the user to accept their RA request. Please delete their message once the ridealong has been completed.", inline=False)
embed.timestamp = datetime.utcnow()
await ctx.send(embed=embed, delete_after=7200)
You can use await ctx.message.delete() in order to delete the message that triggered the command.
#client.command()
async def ra1(ctx):
embed = discord.Embed(
colour=discord.Colour.blue(),
title="RIDEALONG 1 REQUEST",
description=str(ctx.author.mention) + " IS REQUESTING THEIR FIRST RIDEALONG IN SERVER !"
)
embed.add_field(name="For CDTOs", value="Please message the user to accept their RA request. Please delete their message once the ridealong has been completed.", inline=False)
embed.timestamp = datetime.utcnow()
await ctx.send(embed=embed, delete_after=7200)
await ctx.message.delete()
References
discord.Message.delete
Context.message
Context has the attribute message which you can delete
await ctx.message.delete()
This is quite simple infact its just using await ctx.message.delete()
Implemented inside of your code:
#client.command()
async def ra1(ctx):
await ctx.message.delete()
embed = discord.Embed(
colour=discord.Colour.blue(),
title="RIDEALONG 1 REQUEST",
description=str(ctx.author.mention) + " IS REQUESTING THEIR FIRST RIDEALONG IN SERVER !"
)
embed.add_field(name="For CDTOs", value="Please message the user to accept their RA request. Please delete their message once the ridealong has been completed.", inline=False)
embed.timestamp = datetime.utcnow()
await ctx.send(embed=embed, delete_after=7200)

How to make lockdown and unlock commands discord.py

Im trying to make a lockdown and unlock command using discord.py rewrite. I have the code but it doesn't work at all. Can someone help me?
#client.command()
#commands.has_permissions(manage_channels = True)
async def lockdown(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False)
await ctx.send( ctx.channel.mention + " ***is now in lockdown.***")
#client.command()
#commands.has_permissions(manage_channels=True)
async def unlock(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=True)
await ctx.send(ctx.channel.mention + " ***has been unlocked.***")
I found out the issue. The commands work on every other server except for the one I'm testing it on. It turns out that That server makes everyone admin as soon as they join.
Try this, to enable the necessary bot permissions:
#client.command()
#has_permissions(manage_channels=True)
async def lockdown(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role,send_messages=False)
await ctx.send( ctx.channel.mention + " ***is now in lockdown.***")
#client.command()
#has_permissions(manage_channels=True)
async def unlock(ctx):
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=True)
await ctx.send(ctx.channel.mention + " ***has been unlocked.***")
this is my unlock command hope it helps you
you have to use overwrites TextChannel.set_permissions
#client.command()
async def unlock(ctx, role:Optional[Role], channel:Optional[TextChannel]):
role = role or ctx.guild.default_role
channel = channel or ctx.channel
async with ctx.typing():
if ctx.author.permissions_in(channel).manage_permissions:
await ctx.channel.purge(limit=1)
overwrite = channel.overwrites_for(role)
overwrite.send_messages = True
await channel.set_permissions(role, overwrite=overwrite)
unlock_embed = discord.Embed(
title= ("UNLOCKED"),
description= (f"**{channel.mention}** HAS BEEN UNLOCKED FOR **{role}**"),
colour=0x00FFF5,
)
unlock_embed.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar_url)
unlock_embed.set_author(name=client.user.name, icon_url=client.user.avatar_url)
unlock_embed.set_thumbnail(url=ctx.guild.icon_url)
await ctx.channel.send(embed=unlock_embed, delete_after=10)
print("unlock")
else:
error3_embed=discord.Embed(title="ERROR", description="YOU DONT HAVE PERMISSION", colour=0xff0000)
error3_embed.set_thumbnail(url='https://images.emojiterra.com/google/android-11/512px/274c.png')
error3_embed.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar_url)
error3_embed.set_author(name=client.user.name, icon_url=client.user.avatar_url)
await ctx.channel.send(embed=error3_embed, delete_after=10)

How do I check if a message is sent by a bot or not in discord.py?

I made a Hello Bot using discord.py and Python v3.9.0 and I don't want my bot to read any messages from bots. How do I do that?
I tried to see other questions on Stack Overflow but they were all at least 5 years ago.
I already have it so that it doesn't read messages sent from itself. By the way, my command prefix is '
Here is my code:
import os
import discord
# * Clear the screen
def clear():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
# * Code
clear()
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("'hello"):
await message.channel.send("Hello!")
if message.content.startswith("'Hello"):
await message.channel.send("Hello!")
if message.content.startswith("'HELLO"):
await message.channel.send("Hello!")
if message.content.startswith("'Hi"):
await message.channel.send("Hello!")
if message.content.startswith("'hi"):
await message.channel.send("Hello!")
if message.content.startswith("'HI"):
await message.channel.send("Hello!")
if message.content.startswith("'hey"):
await message.channel.send("Hello!")
if message.content.startswith("'Hey"):
await message.channel.send("Hello!")
if message.content.startswith("'Greetings"):
await message.channel.send("Hello!")
if message.content.startswith("'greetings"):
await message.channel.send("Hello!")
if message.content.startswith("'howdy"):
await message.channel.send("We're not cowboys!")
if message.content.startswith("'Howdy"):
await message.channel.send("We're not cowboys!")
if message.content.startswith("'Bye"):
await message.channel.send("Bye!")
if message.content.startswith("'bye"):
await message.channel.send("Bye!")
if message.content.startswith("'BYE"):
await message.channel.send("Bye!")
# * Runs the code
client.run("my_token")
You can simply use discord.Member.bot. It returns True or False depends on whether the user is a bot or not. Also, you can use str.lower() instead of checking all uppercase and lowercase letter possibilities.
#client.event
async def on_message(message):
if message.author.bot:
return
if message.content.lower().startswith("'hello"):
await message.channel.send("Hello!")
if message.content.lower().startswith("'hi"):
await message.channel.send("Hello!")
if message.content.lower().startswith("'hey"):
await message.channel.send("Hello!")

Resources