Python Bot错误消息

时间:2018-06-01 14:52:07

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

这是我的代码,我添加了错误处理,但它无法正常工作。当命令由非管理员执行时,我在bash中收到错误。如果我输入带有管理员角色的?hello,则命令如下,但是当命令为非管理员类型时,他们会收到You don't have permission to use this command.

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)

1 个答案:

答案 0 :(得分:1)

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"))