Discord.py 如果成员没有角色,则发送错误消息

Discord.py send error msg if member don't have role

嘿,我是 discord.py 的初学者,需要一些帮助。

我正在制作一个不和谐的机器人,我有一个命令,只有具有“职员”角色的成员才能使用,但如果你没有这个角色,我想要一个发送嵌入的命令,上面写着“职员角色是使用此命令的要求!”。但是我不知道怎么做,我什么都试了一点点,但没有任何效果=/

这是我目前所拥有的

# Moderator Commands List
@commands.has_role('Staff')
@bot.command(name='help_mod')
async def help_mod(context):
    my_embed = discord.Embed(title="Moderator Plugin", color=0xFFC71C)
    my_embed.add_field(name="Ban a member from the server", value="``?ban [member] (optional reason)``", inline=False)
    my_embed.add_field(name="Temporarily ban a member from the server", value="``?tempban [member] [duration] (optional reason)``", inline=False)
    my_embed.add_field(name="Mute a member in the whole server", value="``?mute [member] (optional reason)``", inline=True)
    my_embed.add_field(name="Temporarily mute a member in the server", value="``?tempmute [member] [duration] (optional reason)``", inline=False)
    my_embed.add_field(name="Kick a member from the server", value="``?kick [member] (optional reason)``", inline=False)
    my_embed.add_field(name="Unban a member", value="``?unban [member]``", inline=False)
    my_embed.add_field(name="Unmute a member", value="``?unmute [member]``", inline=False)
    my_embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/765665083082407976/767502481922981928/ModHammer.png')
    my_embed.set_footer(text="Work in progress, these commands are not in function yet.")

感谢大家的帮助!

您可以在错误处理程序中执行此操作:

@bot.command(name='help_mod')
@commands.has_role('Staff')
async def help_mod(ctx):
   # ...


@help_mod.error # <- name of the command + .error
async def help_mod_error(ctx, error):
    if isinstance(error, commands.MissingRole):
        await ctx.send("Staff role is a requirement to use this command!")

Here's错误处理简介

除了上面的答案,您还可以执行以下操作: 删除 has_role 检查,而是检查您的代码是否用户具有所需的角色。

@client.command(name='help_mod')
async def help_mod(context):
    staff_role = discord.utils.get(context.guild.roles, id = role_id) # Insert the role id here
    if staff_role in context.author.roles:
        # Your Code
    else:
        # Send error message

按 ID 过滤角色还可以确保即使角色名称发生更改,您的代码仍然有效。

后来找到了这个解决方案,效果很好。

from discord.ext.commands import MissingPermissions
   
 

@helpm.error  # <- name of the command + .error
        async def helpm_error(ctx, error):
            if isinstance(error, commands.MissingRole):
                error_role = discord.Embed(description="Staff role is a requirement to use this command!", color=0xf30000)
                await ctx.message.channel.send(embed=error_role)