Discord.py斜杠命令无法设置与显示问题求助
Discord.py斜杠命令/clearnono同步后无法显示的排查与解决
我尝试在discord.py中创建斜杠命令
/clearnono,用于清理指定数量的消息,但无论执行多少次同步命令,该命令都无法显示或使用,不过普通非斜杠命令可正常运行。
斜杠命令代码
@app_commands.command(name='clearnono', description="Cleaw the numbew of nono messages you want to wemove.") @app_commands.rename(num='quantity') @app_commands.describe(num='How many?') async def clear(interaction: discord.Interaction, num: int): await interaction.channel.purge(limit=num) await interaction.response.send_message(f"{num} messages were cleawed swccessfwlly.", ephemeral=True)
同步命令代码
@bot.command() @commands.guild_only() @commands.is_owner() async def sync( ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None: if not guilds: if spec == "~": synced = await ctx.bot.tree.sync(guild=ctx.guild) elif spec == "*": ctx.bot.tree.copy_global_to(guild=ctx.guild) synced = await ctx.bot.tree.sync(guild=ctx.guild) elif spec == "^": ctx.bot.tree.clear_commands(guild=ctx.guild) await ctx.bot.tree.sync(guild=ctx.guild) synced = [] else: synced = await ctx.bot.tree.sync() await ctx.send( f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}" ) return ret = 0 for guild in guilds: try: await ctx.bot.tree.sync(guild=guild) except discord.HTTPException: pass else: ret += 1 await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
排查与修复步骤
1. 确认机器人权限与邀请范围
- 重新邀请机器人到服务器时,必须勾选
applications.commandsscope(在Discord开发者门户→OAuth2→URL生成中勾选),否则机器人没有创建斜杠命令的权限 - 确保机器人拥有
Manage Messages权限,避免执行命令时因权限不足失败
2. 正确使用同步命令
- 全局命令同步后需要1小时左右的缓存时间,测试阶段优先用服务器专属同步:执行
!sync ~(假设机器人前缀为!),该命令会即时同步当前服务器的命令 - 若斜杠命令是全局注册的(未用
@app_commands.guilds指定服务器),执行!sync *可将全局命令复制到当前服务器,实现即时生效
3. 修正代码参数描述错误
你代码中@app_commands.describe的参数名与@app_commands.rename后的名称不匹配,会导致命令注册异常,修正如下:
@app_commands.rename(num='quantity') @app_commands.describe(quantity='How many?') # 将num改为quantity,与重命名后的参数名一致
4. 强制刷新命令缓存
- 先执行
!sync ^清空当前服务器的所有应用命令,再执行!sync *或!sync ~重新同步 - 重启机器人,确保所有命令正确加载到命令树中
5. 检查Intents配置
确保机器人开启必要的intents,尤其是message_content(同步命令为普通命令,需要该intents接收消息):
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents)
修复后的完整斜杠命令代码
@app_commands.command(name='clearnono', description="Cleaw the numbew of nono messages you want to wemove.") @app_commands.rename(num='quantity') @app_commands.describe(quantity='How many?') async def clear(interaction: discord.Interaction, num: int): try: await interaction.channel.purge(limit=num) await interaction.response.send_message(f"{num} messages were cleawed swccessfwlly.", ephemeral=True) except discord.Forbidden: await interaction.response.send_message("我没有清理消息的权限哦!", ephemeral=True) except discord.HTTPException as e: await interaction.response.send_message(f"清理消息失败:{str(e)}", ephemeral=True)
内容的提问来源于stack exchange,提问作者Thomas Thorpe
相关产品推荐
相关产品推荐

