Reputation:
I need help with the error handling in discord.py. I want to send the server owner a private message if my bot doesn't have enough rights for a command or if my bots fail something (reason not enough rights) with the right, that he needs.
Now I searched a lot and can't find a good example that shows this. I know how to send the Owner a private message, but the "isinstance" thing confuses me very hard, I never used it before. But this is an important feature, that I would love to integrate.
Upvotes: 2
Views: 16114
Reputation: 4700
Preface: Since you are talking about error handling, I am assuming that the member is trying to use a command, but the bot does not have enough permissions to properly execute the function body of the command.
@commands.command(name="kick")
@commands.has_permissions(kick_members=True)
async def kick(ctx, members, *, reason=None):
await member.kick(reason=reason)
@kick.error
async def kick_error(error, ctx):
if isinstance(error, commands.MissingPermissions):
owner = ctx.guild.owner
direct_message = await owner.create_dm()
await direct_message.send("Missing Permissions")
The isinstance()
function is a Python built-in function which takes two arguments, object
and classinfo
. The function returns whether or not the object
argument is an instance of classinfo
. In this case, the error caused by the bot not having enough permissions raises a discord.ext.commands.MissingPermissions
error.
The isinstance()
function in this case checks if the exception raised is an instance of commands.MissingPermissions
. If the exception is the discord.ext.commands.MissingPermissions
error, then isinstance()
will return True
.
The code of the if
clause is easier to understand. The owner of the guild (as a discord.Member
object) is stored as an attribute of discord.Guild
objects; in this case, ctx.guild.owner
. Since the object is a discord.Member
object, the create_dm()
classmethod can be called to create a private direct message channel. In that channel, the message is sent.
Upvotes: 4