如何让Discord特定斜杠命令仅管理员可执行?
如何设置仅管理员可使用特定Discord斜杠命令?
有两种常用方法可以让你的Discord斜杠命令仅对管理员开放:
方法一:使用Discord原生权限装饰器(推荐)
通过@app_commands.default_permissions装饰器,能直接在Discord层面限制命令的可见性和可用性,普通用户看不到这个命令,自然也无法执行。
修改你的8ball命令代码如下:
@client.tree.command(name="8ball", description="gives an 8-ball style answer to any question") @app_commands.default_permissions(administrator=True) # 添加这行权限限制 @app_commands.describe(thing_to_say="question?") async def _8ball(interaction: discord.Interaction, thing_to_say: str): responses = [ 'It is certain', 'It is decidedly so', 'Without a doubt', 'Yes definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy, try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Dont count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful' ] await interaction.response.send_message(f'Question: {thing_to_say}\nAnswer: {random.choice(responses)}')
注意:添加装饰器后,需要重新同步命令到Discord服务器,修改才会生效。
方法二:在命令内部检查管理员权限
如果需要给无权限用户明确提示,可以在命令函数开头检查用户权限,不符合则直接回复拒绝信息:
@client.tree.command(name="8ball", description="gives an 8-ball style answer to any question") @app_commands.describe(thing_to_say="question?") async def _8ball(interaction: discord.Interaction, thing_to_say: str): # 检查用户是否拥有管理员权限 if not interaction.user.guild_permissions.administrator: await interaction.response.send_message("你没有权限使用这个命令!", ephemeral=True) return responses = [ 'It is certain', 'It is decidedly so', 'Without a doubt', 'Yes definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy, try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Dont count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful' ] await interaction.response.send_message(f'Question: {thing_to_say}\nAnswer: {random.choice(responses)}')
这里ephemeral=True让回复仅对执行命令的用户可见,避免无关用户看到提示信息。
内容的提问来源于stack exchange,提问作者CYKLER
相关产品推荐
相关产品推荐

