Python中Discord斜杠命令无法显示问题求助
问题诊断与解决方案
核心问题:命令同步时机错误
你的on_ready事件中先同步命令,再加载cogs。但混合命令是在cogs加载时才注册到bot.tree的,同步操作执行时cogs还未加载,自然无法将/hello同步到Discord服务器。
修复步骤:
调整on_ready的执行顺序,先加载所有cogs,再同步命令:
@bot.event async def on_ready(): # 先加载cogs for fn in os.listdir("./cogs"): if fn.endswith(".py"): try: await bot.load_extension(f"cogs.{fn[:-3]}") print(f"\n loaded extensions: {fn}") except Exception as e: print(f" failed to load extension(s) {fn}: {e}") # 再同步命令 try: guild = discord.Object(id={guild_id_here}) # 替换为实际服务器数字ID # 优先同步到指定服务器(服务器同步即时生效,适合开发阶段) await bot.tree.sync(guild=guild) print(f"Slash commands synced to guild: {guild.id}") except Exception as e: print(f"Failed to sync commands: {e}") print("\n bot is ready!")
其他排查点
- 确认服务器ID正确:确保
{guild_id_here}替换为实际的服务器数字ID,而非名称或其他字符串。 - 机器人权限验证:在Discord开发者门户的授权页面,确认勾选
applications.commands权限范围,且邀请链接包含scope=bot+applications.commands,重新邀请机器人到服务器。 - 清理客户端缓存:按
Ctrl+R刷新Discord客户端,或退出重新登录,避免旧命令列表被缓存。 - 避免重复同步:开发阶段不要同时执行全局和服务器同步,全局同步存在1小时左右的缓存延迟,优先用服务器同步。
带可视化参数的混合命令示例
直接为函数参数添加类型标注,discord.py会自动生成斜杠命令的可视化参数:
@commands.hybrid_command(name="greet", description="Greet a user with a custom message") async def greet(self, ctx, user: discord.Member, message: str = "Hello there!"): await ctx.send(f"{user.mention}, {message}")
斜杠命令启动模态框示例
from discord.ui import Modal, TextInput @commands.hybrid_command(name="feedback", description="Submit feedback via a modal form") async def feedback(self, ctx): # 创建模态框 modal = Modal(title="Feedback Submission") # 添加多行输入框 modal.add_item(TextInput(label="Your Feedback", style=discord.TextStyle.long, placeholder="Type your feedback here...")) # 定义模态框提交后的处理逻辑 async def handle_submit(interaction): feedback_content = interaction.data["components"][0]["components"][0]["value"] await interaction.response.send_message(f"Thanks for your feedback: {feedback_content}", ephemeral=True) modal.on_submit = handle_submit # 发送模态框 await ctx.send_modal(modal)
内容的提问来源于stack exchange,提问作者jay
相关产品推荐
相关产品推荐

