Discord Bot在线但不响应消息的问题排查与解决
Discord Bot在线但无消息响应的问题解决
问题场景
我为Discord服务器制作了一个用于内部玩笑的Bot,核心功能是读取消息最后一个单词的末尾两个字母,若以er结尾,则回复{last_word}, I hardly know her!。Bot启动无报错,在Repl.it及测试Discord服务器中均显示在线状态,但完全不响应任何消息。
初始代码如下:
import discord client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print('TARA_BOT ONLINE') async def on_message(message): if message.author == client.user: return words = message.content.split() last_word = words[-1].lower() if words else "" if last_word.endswith("er"): response = f"{last_word} I hard know her" await message.channel.send(response) # Continue processing other commands await client.process_commands(message) client.run('Token')
初步排查
首先怀疑是消息权限问题,于是修改代码开启message_content意图,同时在Discord开发者平台勾选了对应的权限选项:
import discord intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) @client.event async def on_ready(): print('TARA_BOT ONLINE') async def on_message(message): if message.author == client.user: return words = message.content.split() last_word = words[-1].lower() if words else "" if last_word.endswith("er"): response = f"{last_word} I hard know her" await message.channel.send(response) # Continue processing other commands await client.process_commands(message) client.run('Token')
但修改后问题依旧存在。
最终解决
经过检查,发现问题根源是on_message函数没有添加@client.event装饰器——Discord.py需要通过这个装饰器来识别消息事件的处理函数。添加装饰器后,Bot正常响应消息,同时我还扩展了检测逻辑,新增对or/ar结尾单词的支持,最终正确代码如下:
import discord intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) @client.event async def on_ready(): print('TARA_BOT ONLINE') @client.event # 添加此装饰器将函数注册为消息事件处理器 async def on_message(message): if message.author == client.user: return words = message.content.split() last_word = words[-1].lower() if words else "" if last_word.endswith("er") or last_word.endswith("or") or last_word.endswith("ar"): response = f"{last_word}, I hardly know her!" await message.channel.send(response) # 继续处理其他命令 await client.process_commands(message) client.run('Token')
内容的提问来源于stack exchange,提问作者Phighlow
相关产品推荐
相关产品推荐

