Discord.py中@bot.event命令无响应,Ping指令无法触发回复
问题分析与解决方案
核心问题
你注册了多个on_message事件处理函数,discord.py框架只会执行最后一个注册的on_message事件,之前的事件逻辑会被完全覆盖,这就是ping指令无响应的直接原因。
修复方案
提供两种可行的修复方式,推荐使用第二种更符合discord.py规范的写法:
方案1:合并所有on_message逻辑
将忽略自身消息、ping指令的逻辑整合到同一个on_message事件中,同时如果后续要使用commands装饰器定义指令,必须调用bot.process_commands(message)确保指令被处理:
import os import discord from dotenv import load_dotenv from discord.ext import commands load_dotenv() PREFIX = os.getenv("PREFIX") TOKEN = os.getenv("TOKEN") intents = discord.Intents().all() bot = commands.Bot(command_prefix=PREFIX, intents=intents) @bot.event async def on_message(message): # 忽略机器人自身发送的消息 if message.author == bot.user: return # 处理ping指令 if message.content.startswith(PREFIX + 'ping'): # 将latency从秒转为毫秒,保留两位小数更直观 await message.channel.send(f'pong! {bot.latency * 1000:.2f}ms') # 必须调用此方法,否则@bot.command定义的指令会失效 await bot.process_commands(message) @bot.event async def on_ready(): print("Bot is ready and logged in as {0.user}!".format(bot)) bot.run(TOKEN)
方案2:使用@bot.command()装饰器(推荐)
discord.py的commands模块专门用于管理指令,这种写法更清晰易维护:
import os import discord from dotenv import load_dotenv from discord.ext import commands load_dotenv() PREFIX = os.getenv("PREFIX") TOKEN = os.getenv("TOKEN") intents = discord.Intents().all() bot = commands.Bot(command_prefix=PREFIX, intents=intents) # 定义ping指令 @bot.command(name='ping') async def ping_command(ctx): await ctx.send(f'pong! {bot.latency * 1000:.2f}ms') @bot.event async def on_ready(): print("Bot is ready and logged in as {0.user}!".format(bot)) # 如果需要自定义on_message逻辑,必须调用process_commands确保指令被处理 @bot.event async def on_message(message): if message.author == bot.user: return await bot.process_commands(message) bot.run(TOKEN)
补充说明
- 同一个事件(如
on_message)只能注册一个有效处理函数,后续注册的会覆盖之前的 bot.latency返回的是秒级延迟,乘以1000转换为毫秒更符合使用习惯- 使用
commands装饰器能更方便地扩展其他指令,还支持参数、权限控制等功能
内容的提问来源于stack exchange,提问作者LordYersinia
相关产品推荐
相关产品推荐

