discord.py中Cog内命令不显示及RuntimeWarning问题求助
问题解决步骤
1. 修复load_extension异步调用报错
discord.py v2.x版本后,load_extension改为异步协程方法,必须在异步上下文内用await调用,同步调用会触发RuntimeWarning。
修改加载Cog的代码(需放在机器人初始化的异步逻辑中):
import os import discord from discord.ext import commands # 初始化机器人,记得替换前缀和Intents bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) async def load_cogs(): for filename in os.listdir("cogs"): if filename.endswith(".py"): await bot.load_extension(f"cogs.{filename[:-3]}") print(f'[✅]Loaded cogs.{filename[:-3]}') @bot.event async def on_ready(): await load_cogs() # 同步Slash命令:全局同步需1小时生效,测试可指定服务器ID await bot.tree.sync() # 测试用指定服务器:await bot.tree.sync(guild=discord.Object(id=你的服务器ID)) print(f'已登录为 {bot.user}') bot.run("你的机器人TOKEN")
2. 修复Cog内命令不显示的问题
核心错误点修正:
- 前缀命令:
@commands.command的参数应为ctx(上下文),而非interaction,响应需用await ctx.send() - Slash命令:
@commands.Cog.slash_command写法错误,正确装饰器是@discord.app_commands.command() - setup函数:
add_Cog拼写错误,应为小写的add_cog - 文本笔误:
goodmidday命令的描述里Mttag改为Mittag
修改后的Cog代码:
import discord from discord.ext import commands from discord import app_commands class Wuensche(commands.Cog): def __init__(self, bot): self.bot = bot # 前缀命令(使用ctx参数) @commands.command(name="goodnight", description="Wünsche allen eine gute Nacht") async def goodnight(self, ctx): embedVar = discord.Embed(title="Gute Nacht!", description=f"{ctx.author.mention} wünscht allen eine gute Nacht.", color=0x000000) await ctx.send(embed=embedVar) # Slash命令(使用interaction参数) @app_commands.command(name="goodmorning", description="Wünsche allen einen schönen Morgen.") async def goodmorning(self, interaction: discord.Interaction): embedVar = discord.Embed(title="Guten Morgen!", description=f"{interaction.user.mention} wünscht allen einen guten Morgen.", color=0xFFFF00) await interaction.response.send_message(embed=embedVar) @app_commands.command(name="goodmidday", description="Wünsche allen einen guten Mittag.") async def goodmidday(self, interaction: discord.Interaction): embedVar = discord.Embed(title="Guten Mittag", description=f"{interaction.user.mention} wünscht allen einen guten Mittag.", color=0x1a4646) await interaction.response.send_message(embed=embedVar) def setup(bot): bot.add_cog(Wuensche(bot)) # 修正拼写错误
3. 额外注意事项
- 确保机器人开启了
message_content等必要Intents,否则前缀命令无法触发 - Slash命令全局同步需等待约1小时,测试阶段建议用指定服务器同步快速生效
- 确认
cogs文件夹存在且处于Python可识别的路径中
内容的提问来源于stack exchange,提问作者65454
相关产品推荐
相关产品推荐

