如何让Discord斜杠命令在DM(私信)中正常使用?
Discord私信中使用斜杠命令的问题解决思路
你的代码目前仅将斜杠命令同步到了指定服务器,导致私信(DM)环境下无法触发命令。以下是具体的解决步骤:
1. 同步全局命令
全局命令会在所有环境(包括私信和服务器)生效,修改setup_hook方法,添加全局同步逻辑:
async def setup_hook(self) -> None: import os # 补充os模块导入,原代码中遗漏该依赖 for filename in os.listdir("./cogs"): if filename.endswith(".py"): await self.load_extension(f"cogs.{filename[:-3]}") # 保留原有服务器同步,不影响服务器内命令使用 await bot.tree.sync(guild=discord.Object(id=guild_id)) # 同步全局命令,支持私信场景 await bot.tree.sync()
注意:全局命令同步后需要等待约1小时才能在所有环境生效,这是Discord的机制限制。
2. 添加私信使用权限控制(可选)
如果需要限制仅特定用户(比如机器人所有者)能在私信使用命令,可以在命令函数中增加判断:
@app_commands.command(name="test", description="Test command") async def test(self, interaction: discord.Interaction): # 判断是否为私信环境,且用户不是机器人所有者 if interaction.guild is None and interaction.user.id != self.bot.owner_id: await interaction.response.send_message("你无权在私信中使用此命令", ephemeral=True) return await interaction.response.send_message(f'Hello')
3. 确认机器人权限配置
确保在Discord开发者后台的Bot页面开启了Message Content Intent(消息内容权限),代码中保持intents = discord.Intents.all()即可覆盖所需权限。
4. 快速测试:同步到指定私信会话(可选)
若不想等待全局同步的1小时,可以直接将命令同步到目标私信会话,仅对该会话生效:
在on_ready方法中添加同步逻辑:
async def on_ready(self): application_info = await self.application_info() bot_owner = application_info.owner await bot_owner.create_dm() self.bot_owner_dm_channel = bot_owner.dm_channel # 同步命令到所有者的私信会话 await self.tree.sync(guild=self.bot_owner_dm_channel) await self.change_presence(activity=discord.Game(presence_message)) print(f"Logged in as\n\tName: {self.user.name}\n\tID: {self.user.id}") print(f"Running pycord version: {discord.__version__}") print(f"Synced commands to guild with id {guild_id}.")
内容的提问来源于stack exchange,提问作者julius28
相关产品推荐
相关产品推荐

