首页 > 解决方案 > 如何在 discord.py 中排除角色

问题描述

所以我有一个紧急命令,以防有什么事情,我必须给每个人发消息,但是机器人有问题,因为给他们发消息会导致错误(机器人角色是“机器人”)

@bot.command(pass_context=True)
async def emergency(ctx, *, message: str):
    if admin in [role.id for role in ctx.message.author.roles]:
        for server_member in ctx.message.server.members:
            await bot.send_message(server_member, message)
    else:
        await bot.say("DENIED, You do not have permission to use this command")

和错误

Traceback (most recent call last):
  File "C:\Users\adamk\PycharmProjects\bot\venv\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "C:\Users\adamk\PycharmProjects\bot\venv\lib\site-packages\discord\ext\commands\core.py", line 374, in invoke
    yield from injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\adamk\PycharmProjects\bot\venv\lib\site-packages\discord\ext\commands\core.py", line 54, in wrapped
    raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: FORBIDDEN (status code: 403): Cannot send messages to this user

标签: pythondiscord.pydm

解决方案


在其他一些情况下,您会收到此消息(您已被阻止,该用户已完全禁用 DM,等等),因此在每次发生错误时捕获错误并继续处理更有意义。

@bot.command(pass_context=True)
async def emergency(ctx, *, message: str):
    if admin in [role.id for role in ctx.message.author.roles]:
        for server_member in ctx.message.server.members:
            try:
                await bot.send_message(server_member, message)
            except discord.Forbidden:
                pass
    else:
        await bot.say("DENIED, You do not have permission to use this command")

如果您还想检查角色,可以使用discord.utils.get

if get(server_member.roles, name="BOTS"):
    # has role
else:
    # does not have role

推荐阅读