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

如何在私信中隐藏Discord分组斜杠命令?

如何在私信(DM)中隐藏分组斜杠命令

问题出在你仅给分组内的子命令添加了@discord.app_commands.guild_only(),但分组本身未设置仅服务器可见,因此分组仍会在私信中显示。要解决这个问题,需要给整个分组对象开启guild_only属性,以下是两种可行方案:

方案一:在Group初始化时传入guild_only参数

修改TestGroup类的构造方法,调用父类构造时传入guild_only=True,让整个分组默认仅服务器可见:

import discord
from discord.ext import commands


# Setup
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)

# Simple login confirmation
@bot.event
async def on_ready():
    await bot.tree.sync()
    print(f"{bot.user} is online!")

# @discord.app_commands.guild_only() hides the command if the user try's to use it in DMs.
@bot.tree.command(name="hidden-test", description="This command can only be used in guilds!")
@discord.app_commands.guild_only()
async def hidden_command(interaction: discord.Interaction):
    await interaction.response.send_message("This command can only be used in guilds!", ephemeral=True)

# 修改分组初始化逻辑,添加guild_only参数
class TestGroup(discord.app_commands.Group):
    def __init__(self):
        super().__init__(name="hidden", description="These command can only be used in guilds!", guild_only=True)

    @discord.app_commands.command(name="true", description="This command can only be used in guilds!")
    @discord.app_commands.guild_only()
    async def true_command(self, interaction: discord.Interaction):
        await interaction.response.send_message("This command can only be used in guilds! (not really :d)", ephemeral=True)

bot.tree.add_command(TestGroup())

# Replace with your bot token, if you're going to test it.
bot.run("YOUR-TOKEN")

方案二:给分组实例直接设置guild_only属性

如果不想修改类的构造逻辑,也可以在将分组添加到命令树前,直接给实例设置属性:

# ... 其余代码保持不变 ...

# 创建分组实例并设置仅服务器可见
test_group = TestGroup()
test_group.guild_only = True
bot.tree.add_command(test_group)

# ... 其余代码保持不变 ...

两种方案都能让hidden分组像hidden-test命令一样不在私信中显示,同时子命令的guild_only装饰器仍可限制使用场景,形成双重保障。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:35:00