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

如何在discord.py中仅向拥有Administrator权限的用户展示slash命令?

实现Discord Slash命令仅对管理员可见

有两种常用方法可以让你的/say命令仅对拥有管理员权限的用户可见并可使用:

方法1:设置命令默认权限

使用@app_commands.default_permissions装饰器,直接指定命令的默认权限为管理员专属。这种方式的好处是服务器管理员可以后续在Discord后台调整该命令的权限范围。

修改后的完整代码:

@bot.tree.command(name="say", description="Says something")
@app_commands.describe(channel="The channel you want to send the message to", message="The message you want to send")
@app_commands.default_permissions(administrator=True)  # 添加权限限制
async def say(interaction, channel: discord.TextChannel, message: str):
    # 原代码中bot.get_channel(channel.id)是冗余操作,直接使用传入的channel对象即可
    await channel.send(message)
    await interaction.response.send_message(f"Message sent! {channel.mention}", ephemeral=True)

方法2:使用权限检查器

通过@app_commands.checks.has_permissions装饰器做硬编码的权限校验,这会强制要求用户必须拥有管理员权限才能看到并执行命令,服务器管理员无法通过后台修改绕过这个限制。

代码示例:

from discord import app_commands

@bot.tree.command(name="say", description="Says something")
@app_commands.describe(channel="The channel you want to send the message to", message="The message you want to send")
@app_commands.checks.has_permissions(administrator=True)  # 添加权限检查
async def say(interaction, channel: discord.TextChannel, message: str):
    await channel.send(message)
    await interaction.response.send_message(f"Message sent! {channel.mention}", ephemeral=True)

注意事项

修改完代码后,需要重启机器人并同步命令才能让权限设置生效。同步命令的代码通常放在on_ready事件中:

@bot.event
async def on_ready():
    await bot.tree.sync()
    print(f"Logged in as {bot.user}!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:03:19