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

Discord机器人自定义加入角色报错:NameError与AttributeError求助

Discord自定义加入角色机器人报错修复方案

报错原因分析

  1. NameError: name 'r' is not defined:早期版本未全局定义r,当前代码虽已声明r = None,但check_join_role函数未显式引用全局变量,存在作用域歧义风险。
  2. AttributeError: 'NoneType' object has no attribute 'id':
    • 角色ID被存储为字符串,而discord.utils.get查找角色时,id参数要求整数类型,导致找不到角色返回None,调用add_roles(None)触发报错。
    • 若未通过/joinrole设置角色ID就有成员加入,r为None,转成字符串后同样无法匹配角色,返回None引发错误。

具体修复步骤

  • 修正角色ID类型:在join_role命令中,将输入的角色ID字符串转为整数存储,确保查找角色时类型匹配。
  • 增加空值校验:在on_member_join事件中,先检查r是否为有效整数,且找到的角色不为None,再执行添加角色操作。
  • 显式声明全局变量:在需要读取或修改全局变量的函数中添加global r声明,避免作用域混淆。
  • 开启成员意图:在Discord开发者平台的机器人设置中,开启"Privileged Gateway Intents"下的Server Members Intent,否则on_member_join事件不会触发。

修正后的完整代码

import discord
from discord import app_commands
from discord.ext import commands
import nest_asyncio

nest_asyncio.apply()
# 全局变量存储角色ID,初始为None
r = None

# 开启所有意图,重点确保成员意图有效
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="/", intents=intents)

@bot.tree.command(name="joinrole", description="设置新成员加入时的角色ID")
@app_commands.describe(join_role = "输入角色ID(纯数字)")
async def join_role(interaction: discord.Interaction, join_role: str):
    global r
    try:
        # 将输入的字符串转为整数
        role_id = int(join_role)
        r = role_id
        await interaction.response.send_message(content=f"已设置加入角色ID为 {role_id}。", ephemeral=True)
    except ValueError:
        # 处理非数字输入的情况
        await interaction.response.send_message(content="输入无效!请输入纯数字的角色ID。", ephemeral=True)

@bot.tree.command(name="checkjoinrole", description="查看当前设置的加入角色ID")
async def check_join_role(interaction: discord.Interaction):
    global r
    if r is not None:
        await interaction.response.send_message(content=f"当前加入角色ID为 {r}", ephemeral=True)
    else:
        await interaction.response.send_message(content="尚未设置加入角色ID!", ephemeral=True)

@bot.event
async def on_member_join(member):
    global r
    # 检查r是否为有效整数,且能找到对应角色
    if r is not None:
        role = discord.utils.get(member.guild.roles, id=r)
        if role is not None:
            await member.add_roles(role)
        # 可选:找不到角色时打印日志
        else:
            print(f"无法找到ID为{r}的角色")
    else:
        print("尚未设置加入角色ID,跳过添加角色操作")

# 替换为你的机器人Token
bot.run("YOUR_BOT_TOKEN")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:22:46