如何为Python机器人命令设置多个别名?解决命令不可调用报错
解决Discord.py命令别名的"Command is not callable"错误
嘿,这个问题我太熟悉了!你踩的坑是因为被@bot.command装饰过的函数已经不再是普通的可调用函数——它被Discord.py包装成了一个Command实例对象,直接像调用普通函数那样hellothere(ctx)自然会报错。
给你两种靠谱的解决方式:
方法1:用官方推荐的aliases参数(最简单)
这是最规范也最省事的做法,直接在原命令的装饰器里添加aliases参数,把你想要的别名放进去就行:
@bot.command(pass_context=True, aliases=['hello']) async def hellothere(ctx): await Bot.say("Hello {}".format(ctx.message.author))
这样用户输入!hellothere或者!hello(假设你的命令前缀是!)都会触发同一个逻辑,完全不需要额外写新函数。
方法2:单独写别名命令并调用原命令的invoke方法
如果你确实需要单独定义hello命令(比如后续要给这个别名加专属逻辑),那就得调用原命令对象的invoke异步方法,让Discord.py的命令系统来处理上下文:
@bot.command(pass_context=True) async def hellothere(ctx): await Bot.say("Hello {}".format(ctx.message.author)) @bot.command(pass_context=True) async def hello(ctx): # 调用原命令的invoke方法,注意要加await await hellothere.invoke(ctx)
这里的关键是用await hellothere.invoke(ctx)替代直接调用函数,因为invoke才是触发命令执行的正确方式。
内容的提问来源于stack exchange,提问作者crousap
相关产品推荐
相关产品推荐

