Python 3.6 Discord Bot事件冲突:如何让两个on_message事件共存?
解决Discord Bot两个
on_message事件冲突的问题 Hey there! I totally get why you're running into this issue—let me break it down and fix it for you.
问题根源
In Discord.py, when you define multiple functions with the same event name (like two on_message functions decorated with @client.event), the last one you define will completely overwrite the earlier ones. That's why only your guess-the-number game works, and the "reply 'k' to 'k'" feature is dead in the water.
解决方案:合并事件逻辑
The fix is simple: combine both features into a single on_message event handler. Here's how to do it properly:
修改后的完整代码
import random # 别忘了导入这个模块,猜数字功能需要它! @client.event async def on_message(message): # 先过滤掉机器人自己和其他机器人的消息,避免无限循环 if message.author == client.user or message.author.bot: return # 功能1:收到消息"k"就回复"k" if message.content == 'k': # 新版Discord.py用message.channel.send(),旧版可以用client.send_message(message.channel, 'k') await message.channel.send('k') # 功能2:1-10猜数字小游戏 if message.content.startswith('!guess'): await message.channel.send('Guess a number between 1 to 10') def guess_check(m): return m.content.isdigit() # 新版用client.wait_for('message', ...),旧版用wait_for_message() guess = await client.wait_for('message', timeout=10.0, author=message.author, check=guess_check) answer = random.randint(1, 10) if guess is None: fmt = 'Sorry, you took too long. It was {}.' await message.channel.send(fmt.format(answer)) return if int(guess.content) == answer: await message.channel.send('You are right!') else: await message.channel.send('Sorry. It is actually {}.'.format(answer)) # 必须保留这一行,让Bot能处理其他命令(如果有的话) await client.process_commands(message)
额外注意事项
- 版本兼容性:If you're using a newer version of Discord.py (v1.0+),
client.send_message()andclient.wait_for_message()are deprecated. I've updated the code to use the modernmessage.channel.send()andclient.wait_for('message', ...)syntax. If you're on an older version, just swap those lines back to your original code. - 导入模块:Your original code was missing
import random—I added that because the guess game usesrandom.randint(). Without it, you'll get an error. - 逻辑顺序:The order of these checks doesn't matter here, but if you had overlapping conditions (like a message that triggers both), you'd want to prioritize the more specific check first.
内容的提问来源于stack exchange,提问作者Lukim




