Discord.py启用Intent后on_message事件不响应问题求助
Discord机器人on_message事件无响应的修复方案
核心问题:Client与Bot实例混用
你同时实例化了discord.Client和commands.Bot两个对象,却把on_message事件绑定在Client实例上,最后启动的却是Bot实例——这直接导致事件无法触发。因为Bot本身是Client的子类,完全不需要同时创建两个实例。
错误代码示例:
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) bot = commands.Bot(command_prefix='!', intents=intents) @client.event async def on_message(message): # 你的统计逻辑 pass bot.run('你的TOKEN')
修正后代码:
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True # 只保留Bot实例 bot = commands.Bot(command_prefix='!', intents=intents) @bot.event async def on_message(message): # 必须调用此方法,否则会拦截命令功能 await bot.process_commands(message) # 你的流行词统计逻辑 if "流行词" in message.content: # 处理统计逻辑 pass bot.run('你的TOKEN')
其他需要修复的代码问题
- 多次定义on_message事件:如果用
@bot.event重复定义on_message函数,后定义的会完全覆盖前一个,只有最后一个生效。把所有统计逻辑合并到同一个on_message函数里即可。 - 拼写错误
message.auther:把auther修正为正确的author,否则会触发AttributeError,中断事件执行。 - 整数与字符串拼接错误:直接拼接整数和字符串会报错,改用类型转换或f-string:
# 错误写法 await message.channel.send("使用次数:" + count) # 正确写法1:类型转换 await message.channel.send("使用次数:" + str(count)) # 正确写法2:f-string await message.channel.send(f"使用次数:{count}")
内容的提问来源于stack exchange,提问作者The_SemiPro
相关产品推荐
相关产品推荐

