Python 机器人错误消息

标签 python python-3.x discord discord.py

这是我的代码,我添加了错误处理,但它不起作用。当非管理员执行该命令时,我在 bash 中收到错误。下面的命令如果我使用管理员角色键入 ?hello ,它可以工作,但是当非管理员键入该命令时,他们会收到 您没有使用此命令的权限。

token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
prefix = "?"

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.command(pass_context=True)
async def on_command_error(self, exception, ctx):
    if isinstance(exception, CheckFailure):
        print("{0} does not have permission to run `{1}`".format(ctx.message.author, ctx.command.name))
    elif isinstance(exception, CommandNotFound):
        # This is handled in CustomCommands
        pass
    else:
        print(exception)
        await self.on_error("on_command_error", exception, ctx) 

@bot.command(pass_context=True)
@commands.has_any_role("Admin", "Moderator")
async def hello(ctx):
    msg = 'Hello... {0.author.mention}'.format(ctx.message)
    await bot.say(msg)

bot.run(token)

最佳答案

on_command_error 必须是协程,并且您必须将其注册为 bot 的事件

@bot.event
async def on_command_error(error, ctx):
    if isinstance(error, commands.NoPrivateMessage):
        await bot.send_message(ctx.message.author, 'This command cannot be used in private messages.')
    elif isinstance(error, commands.DisabledCommand):
        await bot.send_message(ctx.message.author, 'Sorry. This command is disabled and cannot be used.')
    elif isinstance(error, commands.CheckFailure):
        await bot.send_message(ctx.message.author, 'Sorry. You dont have permission to use this command.')
    elif isinstance(error, commands.MissingRequiredArgument):
        command = ctx.message.content.split()[1]
        await bot.send_message(ctx.message.channel, "Missing an argument: " + command)
    elif isinstance(error, commands.CommandNotFound):
        await bot.send_message(ctx.message.channel, codify("I don't know that command"))

关于Python 机器人错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50646101/

相关文章:

python - 转换 Pandas DataFrame,添加行值作为列标题

c++ - 在 C++ 中使用 cURL 和多线程

javascript - Discord.js 重启命令不起作用(返回未定义的错误)

node.js - Discordjs 检查用户是否具有角色

python - 我如何从 django 中的 mysql 检索数据并以模式显示,其中我也可以更新它?

python - 在日志格式化程序中提取日志记录调用中的额外字段

python - 为什么没有作为输出?

python - 从 Python 的数组生成 pandas 数据框

python - pandas 和 numpy 的问题在哪里条件/多个值?

Python: "TypeError: ' 组的对象不可调用”