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

Discord机器人欢迎Cog角色授予校验问题:仅允许新用户触发

解决方案:限定仅新成员的点赞操作触发角色授予

当然可行!你的核心问题在于校验逻辑没有正确过滤操作用户——原代码里的react_check几乎没做有效校验,而且后续的机器人判断逻辑也完全颠倒了。我们可以通过强化wait_for的校验条件,精准只响应新加入用户的点赞操作。

问题分析

  1. 原react_check里的return user==user是无效判断,等于允许任何用户操作
  2. 机器人自己添加的表情会触发reaction_add事件,需要排除机器人自身的操作
  3. 后续的if self.bot: pass逻辑错误,应该判断操作用户是否为目标新成员,而非机器人是否存在

修正后的完整代码

import discord
from discord.ext import commands
from discord.utils import get
import random

thumbs_up = "\N{THUMBS UP SIGN}"

def react_check(target_user, target_msg, target_emoji):
    def check(reaction, user):
        # 三个核心校验:
        # 1. 操作用户不是机器人(排除机器人自己加的反应)
        # 2. 操作用户是刚加入的目标用户
        # 3. 反应对应正确的消息和表情
        return (not user.bot 
                and user == target_user 
                and reaction.message.id == target_msg.id 
                and reaction.emoji == target_emoji)
    return check

class Welcome(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, user: discord.Member):
        guildName = user.guild.name
        channel = self.bot.get_channel(555844758778544160)
        
        embed = discord.Embed(colour=discord.Color(random.randint(0x000000, 0xFFFFFF)))
        embed.title = "Hello {}, welcome to {}!".format(user, guildName)
        embed.description = "Before you continue we just want to make sure you have read up on our all important group guidelines. if you haven't you can find them in <#546694486391128066>. Once you're satified with them go ahead and give my message a :thumbsup:."
        embed.set_image(url='')
        
        msg = await channel.send(embed=embed)
        await msg.add_reaction(thumbs_up)

        # 等待符合校验条件的反应
        await self.bot.wait_for('reaction_add', check=react_check(user, msg, thumbs_up))

        # 校验通过,直接授予角色
        role = get(user.guild.roles, name="Members")
        if role:  # 先判断角色是否存在,避免报错
            await user.add_roles(role)
        
        await channel.send(':thumbsup: Awesome! you\'re now set to go. If you would like to add some roles head over to <#555913791615926302> for more details. ')

def setup(bot):
    bot.add_cog(Welcome(bot))

关键修改点说明

  • 强化校验函数:react_check现在明确接收target_user(新加入的用户),并在内部的check函数里同时校验:
    • not user.bot:排除机器人自身的反应(包括你预先添加的点赞表情)
    • user == target_user:只有新加入的用户自己点赞才会触发
  • 移除错误判断:删掉了原代码里逻辑错误的if self.bot: pass分支,因为wait_for已经过滤出了合法操作,直接执行角色授予即可
  • 增加角色存在校验:添加if role:判断,避免因角色不存在导致的运行时错误

这样修改后,就只有新加入的用户自己对欢迎消息点赞时,才会触发「Members」角色的授予,完全解决了你提到的漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:27:28