python - 如何在 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
解决方案
在其他一些情况下,您会收到此消息(您已被阻止,该用户已完全禁用 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
推荐阅读
- pine-script - 如何在前一根蜡烛的“收盘价”设置“止损”?
- python - 计算常用词
- python - Django - ModuleNotFoundError:没有名为“alluth”的模块
- python - 如何使用redis高效存储分层数据?
- codeigniter-2 - 在 2021 年使用 CodeIgniter 2 是安全的,以及如何在 cPanel 上使用 CodeIgniter 4 更新 CodeIgniter 2
- wait - 如何在kotlin中同步函数中的所有代码
- android - com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:应为 BEGIN_ARRAY,但在第 1 行第 148 列路径 $.main 处为 BEGIN_OBJECT
- algorithm - 在无向图中打破关节点后得到的每个组件的总和(优化方法)?
- iis - Web API 和 AD 的应用程序池标识
- python - 想了解 sklearn 分类器的评分方法