Discord.py Cog内!ping命令无响应且无报错问题求助
问题分析与解决
核心问题1:重复定义on_ready事件
你的bot.py中存在两个on_ready事件处理函数,后定义的会覆盖先定义的,导致第一个on_ready里的启动提示逻辑不会执行,同时也可能引发加载逻辑的潜在问题。
核心问题2:Cog内命令未正确绑定
ping.py中的ping命令函数没有缩进,不属于ping类的成员方法,discord.py无法识别这个命令是Cog的一部分,因此不会注册该命令。
修正后的bot.py代码
import discord from discord.ext import commands, tasks import os BOT_TOKEN='my token' CHANNEL_ID='my id' bot=commands.Bot(command_prefix="!", intents=discord.Intents.all()) # 注意补充Session的导入语句,例如 from xxx import Session session=Session() @bot.event async def on_ready(): print('Hello! Bot is ready.') # 加载所有cogs并添加异常捕获 for filename in os.listdir('./cogs'): if filename.endswith('.py'): try: bot.load_extension(f'cogs.{filename[:-3]}') print(f"成功加载cog: {filename[:-3]}") except Exception as e: print(f"加载cog {filename[:-3]}失败: {e}") # 发送启动消息,CHANNEL_ID需转为整数 channel=bot.get_channel(int(CHANNEL_ID)) if channel: await channel.send('Hello! Bot is ready. My prefix is "!"') async def main(): await bot.start(BOT_TOKEN)
修正后的ping.py代码
from discord.ext import commands # 类名采用大驼峰命名法,符合Python规范 class Ping(commands.Cog): def __init__(self, bot): self.bot = bot # 缩进,将命令绑定为类的成员方法 @commands.command(name="ping") async def ping(self, ctx): await ctx.send("pong") def setup(bot): bot.add_cog(Ping(bot))
额外注意点:
CHANNEL_ID需要是整数类型,若存储为字符串需用int()转换,否则get_channel会返回None- 加载cogs时添加异常捕获,可快速定位加载失败的具体原因
- 确保
Session类已正确导入,原代码中缺失对应导入语句
内容的提问来源于stack exchange,提问作者Ziemniak
相关产品推荐
相关产品推荐

