Discord.py error handling not outputting a message? - discord.py

I have tried making an error message when a user does not have the permissions to use the command, this is because I kept getting an error in the console the code is supposed to send a message in chat when the user doesn't have permissions to use it, the error has disappeared from the console but it does not output a message
#client.command()
#has_permissions(manage_messages=True)
async def clear(ctx, limit: int):
await ctx.channel.purge(limit = limit)
await ctx.send('Cleared by {}'.format(ctx.author.mention))
#clear.error
async def clear_error(error, ctx):
if isinstance(error, MissingPermissions):
await ctx.send('Sorry, you do not have permissions to do that!')

When you're using an error handling function, you have to do async def clear_error(ctx, error):. Basically you just have to swap the parameters' places.
#clear.error
async def clear_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send('Sorry, you do not have permissions to do that!')

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

How do you connect a bot to a voice channel?

How do I make a bot join a voice channel in rewrite?
Anything I try doesn't work, and it doesn't give an error either.
Below are my attempts:
#client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
#client.command()
async def join(ctx):
channel = client.get_channel(ctx.author.voice.channel.id)
await channel.connect()
Edit: I turned off the error handler and now I get this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'
Edit 2: I am in a voice channel that the bot can connect to. ctx.author.voice_channel doesn't work, I get this this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'voice_channel'
Edit 3: The command works. I installed PyNaCl and it works just fine.
Try these code.
#client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
#client.command()
async def leave(ctx):
await ctx.voice_client.disconnect()

Ban coroutine not executing [no errors] | Discord.py

I'm creating a new bot (my third time now, but it's been a while) and I am creating a simple ban command. It is line-for-line the same as my other commands, with the addition of the #commands.has_permissions() decorator and an embed to display the ban. However, after adding some prints to show where it gets to, it doesn't make it past await user.ban().
# ---BAN---
#client.command(name="ban", pass_ctx=True)
#commands.has_permissions(ban_members=True)
async def ban(ctx, user: discord.User=None, *, reason: str=None):
if not user:
await ctx.send("Specify a user")
return
embed = discord.Embed (
color = discord.Color.magenta()
)
embed.add_field(name=f"{user} was banned!", value=f"For reason: {reason}", inline=False)
await user.ban()
await ctx.send(embed=embed)
#ban.error
async def ban_error(ctx, error):
if isinstance(error, BadArgument):
await ctx.send("Please specify a **valid** user!")
No error is thrown, but it only gets to await user.ban() before just stopping. Is my user wrong somehow, or did I make an obvious mistake?
'User' object has no attribute 'ban' , instead you need to pass a member object:
async def ban(ctx, user: discord.Member=None, *, reason: str=None):
And you're not getting any errors because #ban.error is catching them but is only handling the BadArgument exception while the rest are ignored.

Ban and Unban commands to work in all servers

I've been programming a discord bot letely, and for its ban command here is the code i use:
#client.command(aliases=['Ban'])
async def ban(ctx, member: discord.Member, days: int = 1):
if get(ctx.author.roles, id=548841535223889923):
await member.ban(delete_message_days=days)
await ctx.send("Banned {}".format(ctx.author))
else:
await ctx.send(ctx.author.mention + " you don't have permission to use this command.".format(ctx.author))
However, if i try to use this on other servers, it just tells me i dont have the required role..
So how do I get the role ID for a new server the bot joins automatically or is there some other way to make this work?
You can use a check for permissions instead of looking for a specific role ID
import discord
from discord.ext import commands
#client.command(aliases=["Ban"])
#commands.has_permission(ban_members=True)
async def...
you can use a has_permission, like this:
#client.command(aliases=["Ban"])
#commands.has_permission(administrator=True)
async def ban(ctx, member: discord.Member, days: int = 1):
await member.ban(delete_message_days=days)
await ctx.send("Banned {}".format(ctx.author))
You can then add a missing permissions error handler:
#client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You do not have the permissions required for this command.")
return
raise error

Resources