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

如何为Discord机器人的Say命令设置角色权限要求?

给Discord机器人Say命令添加等级权限限制

我来帮你搞定这个权限配置的问题!要让Say命令只对特定等级(角色)的用户开放,discord.py提供了几种简单的实现方式,我给你详细拆解一下:

方法一:使用内置角色检查装饰器

这是最直接的方式,适合单一角色或多个指定角色的场景。你只需要在命令上方添加@commands.has_role()或@commands.has_any_role()装饰器即可。

示例代码(适配你的现有代码结构)

import asyncio
import discord
from discord.ext import commands  # 调整导入方式,方便使用装饰器

bot = commands.Bot(command_prefix='>')  # 新版本推荐用command_prefix参数

# 给Say命令添加角色权限要求,替换成你的目标角色名称/ID
@bot.command(pass_context=True)
@commands.has_role("高级用户")  # 可以替换成角色ID,比如@commands.has_role(123456789012345678)
async def Say(ctx, *args):
    mesg = ' '.join(args)
    await bot.delete_message(ctx.message)
    await bot.say(mesg)  # 补全你未写完的发送消息逻辑

# 处理权限不足的错误提示
@Say.error
async def say_error(ctx, error):
    if isinstance(error, commands.MissingRole):
        await bot.send_message(ctx.channel, "抱歉,你需要拥有指定等级的角色才能使用这个命令!")

如果允许多个等级角色使用命令,可以换成:

@commands.has_any_role("Rank 3", "Rank 4", "Rank 5")  # 多个角色任选其一

方法二:自定义等级检查逻辑

如果你的等级系统比较复杂(比如需要判断用户的最高等级、从数据库读取等级等),可以自定义检查函数:

示例代码

import asyncio
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='>')

# 自定义等级检查函数
def has_required_rank(ctx):
    # 这里编写你的等级判断逻辑,比如检查用户角色中是否包含指定等级
    allowed_ranks = ["Rank 3", "Rank 4", "Rank 5"]
    for role in ctx.message.author.roles:
        if role.name in allowed_ranks:
            return True
    return False

# 应用自定义检查到Say命令
@bot.command(pass_context=True)
@commands.check(has_required_rank)
async def Say(ctx, *args):
    mesg = ' '.join(args)
    await bot.delete_message(ctx.message)
    await bot.say(mesg)

# 处理检查失败的提示
@Say.error
async def say_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await bot.send_message(ctx.channel, "你的等级不足,无法使用这个命令!")

版本适配注意事项

如果你使用的是**discord.py v1.0+**的新版本,代码可以简化(pass_context不再需要,API方法也有更新):

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='>')

@bot.command()
@commands.has_role("高级用户")
async def say(ctx, *, mesg):  # 用*直接接收完整消息内容,更简洁
    await ctx.message.delete()
    await ctx.send(mesg)

@say.error
async def say_error(ctx, error):
    if isinstance(error, commands.MissingRole):
        await ctx.send("抱歉,你需要拥有指定等级的角色才能使用这个命令!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:15:52