【问题标题】:Python Bot error messagePython 机器人错误消息
【发布时间】:2018-11-11 18:05:23
【问题描述】:

这是我的代码,我添加了错误处理,但它不起作用。当命令由非管理员执行时,我在 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)

【问题讨论】:

  • “我收到错误无法运行脚本”。所以当你运行这个程序时,它会准确地打印“无法运行脚本”,而不是别的?
  • “尝试了所有来自互联网的代码”?那是很多代码;)
  • 是的,但不知道我做错了什么。我知道我做错了什么。
  • 看起来它不喜欢你的 await 关键字,那里。 AFAICT await 只能出现在异步函数中,而 on_command_error 还没有被标记为异步。 (将其作为评论而不是答案发布,因为我对异步和/或不和谐知之甚少,不知道这是否完全解决了问题)
  • 我添加了异步现在更新的主脚本,它运行但无法接收自定义错误消息。

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


【解决方案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"))

【讨论】:

  • 真的很棒,你的所有回复都很棒,一切正常。
猜你喜欢
  • 1970-01-01
  • 2020-12-03
  • 2021-10-19
  • 2021-07-13
  • 1970-01-01
  • 2019-01-12
  • 2021-08-24
  • 2018-05-02
  • 2019-02-20
相关资源
最近更新 更多