You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让discord.py开发的Discord机器人在所有服务器同步斜杠命令?

解决方案:Discord.py 全局斜杠命令生效问题

你遇到的核心问题是混淆了服务器专属斜杠命令和全局斜杠命令的创建方式,以下是具体解决步骤:

1. 移除服务器ID指定,创建全局命令

你之前通过guild=discord.Object(id=xxx)指定服务器ID,这会让命令仅对该服务器可见。要让命令在所有机器人加入的服务器生效,只需去掉guild参数:

错误写法(仅指定服务器可见)

from discord import app_commands, Object
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=your_intents)

@bot.tree.command(name="your_command", description="命令描述", guild=Object(id=123456789))
async def your_command(interaction):
    await interaction.response.send_message("仅指定服务器可见")

正确写法(全局生效)

from discord import app_commands
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=your_intents)

@bot.tree.command(name="your_command", description="命令描述")
async def your_command(interaction):
    await interaction.response.send_message("所有服务器可见")

2. 同步全局命令

在机器人启动时执行全局命令同步,确保Discord服务器能接收到你的命令定义:

async def setup_hook():
    # 同步全局命令,无需指定guild
    await bot.tree.sync()

bot.setup_hook = setup_hook

bot.run("你的机器人Token")

3. 关键注意事项

  • 同步延迟:Discord的全局命令同步需要1-24小时才能在所有服务器生效,这是平台限制,不是代码问题。如果需要快速测试,可先使用服务器专属命令验证功能,再切换为全局命令。
  • 权限检查:邀请机器人时必须勾选applications.commands权限(OAuth2设置中需包含该Scope),否则机器人无法在服务器中创建斜杠命令。
  • 命令冲突:避免全局命令与已存在的服务器专属命令重名,否则可能导致命令显示异常。

内容的提问来源于stack exchange,提问作者polysteel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:07:41