如何在Pycord的main.py中正确导入Cog?Cog无报错但无法运行
Pycord Cog无报错但无法工作的排查与解决
问题描述
Cog文件加载时无报错,但其中的Slash命令无法正常触发,尝试直接import文件名的方式无效,使用Pycord库,相关代码如下:
main.py 代码
import discord from discord.ext import commands import os client = commands.Bot(command_prefix = "!") client.remove_command('help') @client.event async def on_ready(): await client.change_presence(status = discord.Status.do_not_disturb, activity = discord.Game("Being Handy.")) print("Bot is ready!") ## - Cog Loader -------------------------------------------------- cogs = ["cogs.Secondary"] Start_Decor="----- Connecting Cogs -----\n---------------------------" End_Decor = "\n---------------------------\n----- Cogs Connected -----" Fail = "N/A" Success = False for cog in cogs: try: client.load_extension(cog) Success = True except Exception as e: if Fail == "N/A": Fail = f'🚫 Failed to connect the following:\n\n{cog}: {str(e)}' else: Fail += f'\n{cog}: {str(e)}' if Success == True and Fail == "N/A": print(f'{Start_Decor}\n✅ Connecting Cogs\n{End_Decor}') elif Success == True and not Fail == "N/A": print(f'{Start_Decor}\n✅ Connecting Cogs\n\n{Fail}\n{End_Decor}') else: print(f"{Start_Decor}\n{Fail}\n{End_Decor}") @client.slash_command() async def main_test(ctx): await ctx.respond("Working", ephemeral = False) ## - Code Below -------------------------------------------------- client.run(os.environ.get("BOT_TOKEN"))
Cog文件(Secondary.py)代码
import discord from discord.ext import commands from datetime import datetime class Secondary(commands.Cog): def __init__(self, client): self.client = client @commands.slash_command() async def cog_test(self, ctx): await ctx.respond("Working.", ephemeral = False) def setup(client): client.add_cog(Secondary(client))
排查与解决步骤
1. 确认目录结构正确性
确保项目目录结构符合以下格式,否则load_extension无法定位到Cog文件:
- 项目根目录
- main.py
- cogs/
- init.py (空文件即可,用于标记该目录为Python包)
- Secondary.py (你的Cog文件)
2. 同步Slash命令到Discord
Pycord的Slash命令需要主动同步到Discord服务器才能被识别,即使Cog加载成功,未同步的命令也无法触发。修改on_ready事件添加同步逻辑:
@client.event async def on_ready(): await client.change_presence(status = discord.Status.do_not_disturb, activity = discord.Game("Being Handy.")) # 全局同步Slash命令(首次运行或命令修改后执行) await client.sync_commands() print("Bot is ready! 命令已同步")
如果需要仅同步到特定服务器,可指定guild_ids参数:
await client.sync_commands(guild_ids=[你的服务器ID])
3. 验证Cog是否真的加载成功
在Cog文件的setup函数中添加打印语句,确认Cog被正确加载:
def setup(client): client.add_cog(Secondary(client)) print("Secondary Cog 已成功加载")
运行Bot后查看控制台输出,若该打印信息出现,说明Cog加载正常。
4. 纠正直接import的误区
Pycord加载Cog必须使用client.load_extension()方法,直接import文件不会将Cog注册到Bot实例中,因此这种方式无效,保持现有load_extension的加载逻辑即可。
内容的提问来源于stack exchange,提问作者Akio_
相关产品推荐
相关产品推荐

