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

如何在Discord.py的on_message事件中为通过测试的用户添加角色

解决Discord.py中on_message事件添加角色的问题

你的代码存在两个核心问题导致角色添加失败:

  • add_roles 是异步方法,必须用 await 关键字调用
  • 不能直接传入角色名称字符串,需要先获取对应的Role对象

修正后的代码示例

@bot.event
async def on_message(message):
    # 保留命令逻辑,避免on_message拦截导致bot命令失效
    await bot.process_commands(message)
    
    if 'verification' not in message.channel.name:
        return
    elif message.attachments:
        attachment = message.attachments[0].url  # 移除多余的content=赋值
        confID = random.randint(100000000, 999999999)

        getImage(attachment, confID) # 获取图片的外部函数
        await message.delete()
        
        # 运行OCR算法
        if ocrVerify(str(confID) + '.png'):
            # 通过角色名称获取Role对象
            role = discord.utils.get(message.guild.roles, name="Test ROle")
            if role:
                await message.author.add_roles(role)
            else:
                print("找不到指定角色")
        else:
            print("DM A MOD")

额外注意事项

  • 确保机器人拥有管理角色的权限,且机器人的角色层级要高于目标角色(否则无法为用户添加该角色)
  • 若服务器存在重名角色,建议用角色ID获取更精准:role = message.guild.get_role(角色ID数字)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:50:30