Python开发Discord机器人无报错但不响应指令的解决方法
首次使用Python开发Discord机器人时,实现代码如下:
import discord from http import client from discord.ext import commands client = discord.Client() client = commands.Bot(command_prefix='`') @client.event async def on_ready(): print("Bot is online") @client.event async def on_message(message): if message.author == client.user: return if message.content == 'hello': await message.channel.send('Welcome to the server, human') @client.command async def info(ctx): await ctx.send(ctx.guild) client.run(#mytokenishereicantshareit)
程序运行后控制台正常输出Bot is online,机器人可正常在目标Discord服务器上线,运行全程无任何报错,但既不响应内容为hello的普通消息,也无法触发命令前缀为`的info自定义命令。
discord.ext.commands.Bot内置了默认的on_message事件处理逻辑,会自动完成消息校验、前缀命令解析、命令分发的全流程。当使用@client.event装饰器自定义on_message方法时,会完全覆盖内置的默认实现,导致内置命令处理逻辑不会执行,所有前缀命令都无法被触发;如果自定义逻辑没有正确覆盖消息流转分支,也会导致普通消息响应逻辑失效。
以下两种方案均可解决该问题:
方案1:替换事件装饰器
将on_message事件的装饰器@client.event替换为@client.listen。该装饰器会将自定义的消息处理逻辑作为监听器追加到默认on_message流程之后,不会覆盖内置的命令处理逻辑,无需额外修改其他代码,即可同时支持普通消息响应和前缀命令触发。方案2:手动调用命令处理方法
保留@client.event装饰器的前提下,在on_message事件的消息处理逻辑末尾(需放在所有提前return的分支之后,确保非机器人自身发送的消息都能执行到该行),添加process_commands方法调用,手动触发内置的命令解析流程。
原代码段:if message.content == 'hello': await message.channel.send('Welcome to the server, human')修改后代码段:
if message.content == 'hello': await message.channel.send('Welcome to the server, human') await client.process_commands(message)注意:调用
process_commands时的实例名需要和代码中初始化Bot的变量名保持一致,本示例中初始化的实例名为client,不要直接照搬bot.process_commands,否则会触发变量未定义错误。
完成上述任意一种修改后,机器人即可正常响应各类消息与指令。
内容的提问来源于stack exchange,提问作者Blue

