在commands.Bot子类中添加Slash命令后不显示的问题
解决Py-cord斜杠命令无法显示的问题
问题原因及修复方案
1. debug_guilds 参数类型错误
Py-cord要求debug_guilds接收整数类型的服务器ID列表,你当前传入的是字符串格式ID,会导致命令无法同步到目标服务器。
修复:
debug_guilds = [998467063972626513] # 移除引号,改为整数
2. 重写on_message未调用父类方法
自定义on_message方法后,必须调用super().on_message(msg),否则会阻断Py-cord内部的斜杠命令事件处理流程,导致命令无法被识别。
修复后的on_message方法:
async def on_message(self, msg): if not msg.author.bot: await self.process_commands(msg) await super().on_message(msg) # 添加该行以保留父类事件逻辑
3. 补充斜杠命令描述(可选但推荐)
给斜杠命令添加description参数,能让命令在Discord中显示说明,同时确保注册逻辑完整。
修复后的斜杠命令:
@self.slash_command(name="test", description="测试斜杠命令") async def test(ctx): await ctx.send("hi")
完整修复代码示例
import os, re, discord, asyncio from discord.ext import commands, pages class TalkToSushi(commands.Bot): def __init__(self): intents = discord.Intents.default() intents.members = True intents.presences = True intents.message_content = True debug_guilds = [998467063972626513] super().__init__(command_prefix=";", intents=intents, debug_guilds=debug_guilds, help_command=None) self.add_commands() def run(self, token): print("[*] Starting bot") super().run(token, reconnect=True) async def on_message(self, msg): if not msg.author.bot: await self.process_commands(msg) await super().on_message(msg) async def process_commands(self, msg): ctx = await self.get_context(msg, cls=commands.Context) if ctx.command is not None: await self.invoke(ctx) else: await self.process_tts(ctx) def add_commands(self): @self.command() async def help(ctx): paginator = pages.Paginator( pages=self.__embeds.help, show_menu=True, menu_placeholder="Select help" ) await paginator.send(ctx) @self.slash_command(name="test", description="测试斜杠命令") async def test(ctx): await ctx.send("hi")
额外检查项
- 确保Bot账号在目标服务器中拥有应用程序命令权限(可在服务器设置→整合→Bot权限中确认)
- 重启Bot应用修复后的代码,
debug_guilds模式下会自动同步命令到指定服务器
内容的提问来源于stack exchange,提问作者Perdana Arta
相关产品推荐
相关产品推荐

