python - discord.py 针对不同的检查失败引发不同的错误
问题描述
我有一个带有命令的 discord.py 机器人test
。我想运行两次检查,首先检查运行它的人是否是机器人所有者,然后检查命令是否在 dm 中运行。如果机器人在 dm 中运行,我希望它发送一条消息,但如果它不是所有者,我希望它运行一条不同的消息。我该怎么做?
@bot.command()
@commands.guild_only()
@commands.check(is_owner)
async def test(ctx):
await ctx.send("Good job you passed the checks!")
@test.error
async def test_error(ctx, error):
if failed guild_only():
await ctx.send("Hey only use this in a guild")
if failed is_owner():
await ctx.send("You're not the owner!!")
解决方案
使用isinstance()
.
isinstance
检查对象是否具有指定的类型。例如,isinstance(3, int)
检查 3 是否为整数(它是整数,因此返回True
)。在您的情况下,您可以检查错误是否commands.NoPrivateMessage
是由 引发的guild_only
,或者错误是否commands.NotOwner
是由引发的is_owner
。正确的代码是:
@test.error
async def test_error(ctx, error):
if isinstance(error, commands.NoPrivateChannel):
await ctx.send("Hey only use this in a guild")
if isinstance(error, commands.NotOwner):
await ctx.send("You're not the owner!!")
推荐阅读
- sql - 如何将带有属性的 XML 数据转换为 SQL Row
- python - 神经网络验证准确性有时不会改变
- jquery - 使用自定义 ajax 调用的数据表过滤器中的问题
- javascript - 如何获取数组中的键和值并将其推送到表中
- laravel - 无法删除包 phpoffice/phpword。(laravel 5.2)
- elasticsearch - 如何汇总和分页结果
- java - 没有 XML 文件的 DOM 树数据结构
- flutter - 使用 Navigator 时,如何解决在 null 上调用了“ancestorStateOfType”方法?
- java - 如何让java程序读取它的内部路径以使其在每台PC上工作
- python - 通过 cron 或类似方法在 Python Flask 中触发操作