如何用discord.py实现Discord服务器专属命令?报错修复与疑问
问题1:修复
!test命令找不到的报错 报错核心是混用了前缀命令与斜杠命令的注册逻辑,再加上代码里的异步调用错误,导致前缀命令未正确注册。具体修复步骤:
- 前缀命令(
!test)必须用@bot.command()装饰器,不能用斜杠命令专属的@app_commands.command或@bot.tree.command。 - 删掉
ctx.guild.name前的await——ctx.guild是同步属性,无需异步等待。 - 移除
on_ready事件里的bot.tree.add_command(test, guild=srvr),这是给斜杠命令树添加命令的操作,和前缀命令无关。
修复后的前缀命令代码:
@bot.command(name="test") async def test(ctx): # 可选:限制仅指定服务器可执行,实现单服务器生效 if ctx.guild.id != 你的服务器ID: await ctx.send("此命令仅在指定服务器可用") return guild_name = ctx.guild.name await ctx.send(f"Test command. Server: {guild_name}")
如果需要更严格的单服务器限制,也可以用commands.check装饰器:
def is_target_guild(): def predicate(ctx): return ctx.guild.id == 你的服务器ID return commands.check(predicate) @bot.command(name="test") @is_target_guild() async def test(ctx): guild_name = ctx.guild.name await ctx.send(f"Test command. Server: {guild_name}")
执行!test前确认机器人已上线,且使用的前缀和你设置的一致(默认前缀为!,自定义过需对应)。
问题2:改为斜杠命令的实现方式
斜杠命令无需前缀,实现逻辑和前缀命令完全不同,不需要沿用前缀命令的方式,更简洁的写法如下:
方法1:用装饰器直接指定生效服务器
# 用@app_commands.guilds直接指定仅在目标服务器生效 @app_commands.command(name="test") @app_commands.guilds(你的服务器ID) async def test(interaction: discord.Interaction): # 斜杠命令用interaction而非ctx,获取服务器名称无需await guild_name = interaction.guild.name await interaction.response.send_message(f"Test command. Server: {guild_name}")
在on_ready事件里同步命令(指定guild可加快同步速度):
@bot.event async def on_ready(): print(f'Logged as {bot.user.name}') try: # 仅同步指定服务器的斜杠命令 synced = await bot.tree.sync(guild=discord.Object(id=你的服务器ID)) print(f"Synced {len(synced)} command(s)") except Exception as e: print(e)
方法2:动态添加到指定服务器(适合批量管理)
如果需要运行时动态添加命令到指定服务器,可使用bot.tree.add_command,注意斜杠命令参数为interaction而非ctx:
async def test(interaction: discord.Interaction): guild_name = interaction.guild.name await interaction.response.send_message(f"Test command. Server: {guild_name}") @bot.event async def on_ready(): print(f'Logged as {bot.user.name}') target_guild = discord.Object(id=你的服务器ID) bot.tree.add_command(app_commands.Command(name="test", callback=test), guild=target_guild) try: synced = await bot.tree.sync(guild=target_guild) print(f"Synced {len(synced)} command(s)") except Exception as e: print(e)
注意:斜杠命令需要机器人拥有applications.commands权限,同步后可能需等待几分钟才会在服务器中显示。
内容的提问来源于stack exchange,提问作者Oczek22
相关产品推荐
相关产品推荐

