
Discord.py 2.4+ 中,用户机器人默认无法在私信(DM)或群组私信(GDM)中显示和执行 Slash 命令;需通过 @allowed_installs 和 @allowed_contexts 两个装饰器显式启用安装权限与使用上下文。
discord.py 2.4+ 中,用户机器人默认无法在私信(dm)或群组私信(gdm)中显示和执行 slash 命令;需通过 @allowed_installs 和 @allowed_contexts 两个装饰器显式启用安装权限与使用上下文。
在 Discord 中,用户机器人(Userbot)的 Slash 命令默认仅注册到服务器(guild)环境,因此即使命令逻辑正确,也不会出现在私信输入框的命令菜单中。这是因为 Discord 对用户机器人的命令可见性施加了双重限制:能否被安装到用户个人档案(install scope),以及能否在特定上下文(如 DM、GDM)中被调用(context scope)。
要解决该问题,必须同时应用以下两个装饰器:
-
@discord.app_commands.allowed_installs(guilds=True, users=True)
允许命令安装到服务器 和 单个用户(即出现在用户个人命令列表中); -
@discord.app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
允许命令在服务器、私信(DM)及群组私信(GDM,即private_channels)中被触发。
✅ 正确示例代码如下:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="/", intents=intents)
@bot.event
async def on_ready():
try:
await bot.tree.sync() # 同步全局命令(含用户安装项)
print(f"{bot.user.name} online")
except Exception as e:
print(f"Sync error: {e}")
@discord.app_commands.allowed_installs(guilds=True, users=True)
@discord.app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@bot.tree.command(name="ping", description="Replies with Pong in DM or server")
async def ping(interaction: discord.Interaction):
await interaction.response.send_message("Pong", ephemeral=True)
bot.run("YOUR_TOKEN")
⚠️ 注意事项:
-
bot.tree.sync()必须成功执行(无异常),且建议首次部署后等待 1–5 分钟,Discord 客户端才会刷新命令列表; - 若仅添加
allowed_contexts而未添加allowed_installs(users=True),命令仍不会出现在私信中——因为根本未被安装到用户侧; -
private_channels=True特指群组私信(Group DM),不可省略,否则 GDM 中命令不可见; - 用户机器人需以「应用程序 Bot」模式运行(非传统 bot 账户),且 Token 来自启用了
applications.commands和botscope 的 OAuth2 链接; - Discord 官方不鼓励用户机器人用于自动化行为,生产环境请优先考虑正规 Bot 应用。
完成配置后,重启机器人并等待同步完成,即可在任意私信窗口中输入 /ping 并看到命令提示。










