discord.py反应角色功能报错:bot模块无guilds属性
修复discord.py反应角色功能中的AttributeError问题
你遇到的AttributeError: module 'discord.ext.commands.bot' has no attribute 'guilds'是因为代码里的bot.guilds引用的是discord.ext.commands.bot这个模块,而非你创建的Bot客户端实例——模块本身没有guilds属性,因此触发报错。
核心修正步骤
- 统一客户端实例:无需同时创建
discord.Client和commands.Bot,commands.Bot是discord.Client的子类,包含所有Client功能且支持命令系统,只保留一个Bot实例即可。 - 修正模块/实例混淆:删除错误的
from discord.ext.commands import bot, Bot导入(已通过from discord.ext import commands导入模块),确保所有事件装饰器和属性调用都指向你的Bot实例。 - 优化资源获取:用discord.py提供的
bot.get_guild()和guild.get_member()替代discord.utils.find,这两个方法更高效简洁。
修正后的完整代码
import discord from discord.ext import commands import datetime import asyncio import random import json # 配置Intents并创建唯一的Bot实例 intents = discord.Intents.default() intents.message_content = True intents.members = True # 必须开启成员意图才能正常获取成员 bot = commands.Bot(command_prefix='.', intents=intents) @bot.event async def on_ready(): await bot.change_presence(status=discord.Status.online, activity=discord.Game('Doing What CCXLV Says')) print('We have logged in as {0.user}'.format(bot)) @bot.event async def on_raw_reaction_add(payload): # 直接通过ID获取服务器 guild = bot.get_guild(payload.guild_id) if not guild: return if payload.emoji.name == "🔴" and payload.message_id == 1019155450375176242: role = discord.utils.get(guild.roles, name="RED") if not role: return # 通过ID获取成员 member = guild.get_member(payload.user_id) if member: await member.add_roles(role) @bot.event async def on_raw_reaction_remove(payload): guild = bot.get_guild(payload.guild_id) if not guild: return if payload.emoji.name == "🔴" and payload.message_id == 1019155450375176242: role = discord.utils.get(guild.roles, name="RED") if not role: return member = guild.get_member(payload.user_id) if member: await member.remove_roles(role) # 替换为你的Bot Token并运行 # bot.run('YOUR_BOT_TOKEN')
额外注意事项
- 需在Discord开发者门户的Bot页面开启服务器成员意图(Server Members Intent),否则
guild.get_member()可能无法获取到成员。 - 确保Bot账号拥有管理角色的权限,否则添加/移除角色操作会失败。
内容的提问来源于stack exchange,提问作者ccxlv
相关产品推荐
相关产品推荐

