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

Discord.py机器人按成员消息分配角色时报AttributeError错误如何解决

问题根源

你报错的核心原因是add_roles()方法接收的参数是Discord的Role对象,而你当前传入的是战队名的字符串,Discord API在尝试获取角色id的时候自然会报错str对象没有id属性。

代码修改步骤

  1. 你之前用discord.utils.get查出来的角色对象没有存下来,只是判断了存在性,先把查询结果赋值给变量备用
  2. 把add_roles的入参换成查到的Role对象即可

修正后的代码如下:

msg = str(message.content)
msgspl = msg.split(", ", 2)
# 增加格式校验,避免不符合格式的消息导致索引越界报错
if len(msgspl) != 3 or msgspl[0] != "INTRO":
    return
role_name = msgspl[2] # 提取战队名(角色名)
# 先查询角色,把结果存到role变量里
role = discord.utils.get(message.guild.roles, name=role_name)
if role: # 角色存在的情况
    await message.author.add_roles(role) # 这里传入Role对象,不是字符串
    await message.channel.send("Thank you for introducing yourselves! The required roles have been allotted.")
else:
    await message.channel.send(
            "Hey! This team name doesn't exist in our records. Please recheck your team name and send the introduction message. If this issue persists, contact one of the admins.")
    await message.delete()

额外注意事项

  • 要确保你的机器人账号有「管理角色」的权限,且机器人的角色排序要高于你要分配的角色,不然分配操作还是会失败
  • 上面新增的格式校验逻辑可以避免用户发送不符合格式的消息时代码抛出索引异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:39:04