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

如何配置Discord Bot使/verification命令仅允许发起者验证自身?

解决方案

核心问题说明

你之前尝试用ctx直接调用add_roles方法失败,是因为ctx是命令上下文对象,不是用户/成员对象,没有角色操作相关方法。要获取发起命令的用户,应该用ctx.author(属于discord.Member类型,具备add_roles/remove_roles等方法)。

方案1:允许所有用户发起命令,但仅能验证自身

这个方案下,任何用户都可以使用/verification命令,但只能给自己添加/移除角色,无法操作他人:

@bot.slash_command()
async def verification(ctx):
    # 获取发起命令的成员
    member = ctx.author
    # 获取目标角色
    test_role = discord.utils.get(ctx.guild.roles, name="test")
    unverified_role = discord.utils.get(ctx.guild.roles, name="untest")
    
    # 检查角色是否存在,避免报错
    if not test_role or not unverified_role:
        await ctx.send("角色未找到,请检查角色名称是否正确!", ephemeral=True)
        return
    
    # 执行角色操作
    await member.add_roles(test_role)
    await member.remove_roles(unverified_role)
    # 仅给发起者显示回复
    await ctx.send(f"欢迎你,{member.mention}!已完成验证。", ephemeral=True)

方案2:仅允许你自己发起命令(并验证自身)

如果希望只有你能使用这个命令,添加权限检查即可:

def is_authorized(ctx):
    # 替换成你的Discord用户ID(数字ID)
    return ctx.author.id == 123456789012345678

@bot.slash_command()
@discord.app_commands.check(is_authorized)
async def verification(ctx):
    member = ctx.author
    test_role = discord.utils.get(ctx.guild.roles, name="test")
    unverified_role = discord.utils.get(ctx.guild.roles, name="untest")
    
    if not test_role or not unverified_role:
        await ctx.send("角色未找到,请检查角色名称是否正确!", ephemeral=True)
        return
    
    await member.add_roles(test_role)
    await member.remove_roles(unverified_role)
    await ctx.send(f"欢迎回来,{member.mention}!已完成验证。", ephemeral=True)

# 处理无权限用户的调用
@verification.error
async def verification_error(ctx, error):
    if isinstance(error, discord.app_commands.CheckFailure):
        await ctx.send("你没有权限使用这个命令!", ephemeral=True)

额外:处理@Bot的消息

如果你需要Bot在被@时做出响应,可以添加消息监听事件:

@bot.event
async def on_message(message):
    # 忽略Bot自身的消息,避免循环
    if message.author.bot:
        return
    
    # 检查消息是否@了当前Bot
    if bot.user in message.mentions:
        await message.channel.send(f"你@我了,{message.author.mention}!如果需要验证,请使用`/verification`命令。")
    
    # 必须调用此方法,否则slash命令会失效
    await bot.process_commands(message)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:15:34