Discord自动角色分配脚本故障:状态含.gg/maven无法授予角色
Discord自动角色分配代码故障排查与修复
核心问题分析与修复步骤
角色ID配置错误
你在on_ready事件中误将服务器ID当作角色ID使用:role=discord.utils.get(guild.roles,id=998691667831951442)该ID与服务器ID完全一致,角色ID不可能和服务器ID重复。请在Discord开启开发者模式后,右键目标角色复制正确ID,替换此处数值。
Activity匹配逻辑冗余且易出错
直接将整个Activity对象转为字符串进行匹配,可能导致不必要的匹配偏差。应直接提取Activity的name属性做判断,同时简化冗余代码:@bot.event async def on_member_update(before, after): if online: old_name = before.activity.name.lower() if before.activity else "" new_name = after.activity.name.lower() if after.activity else "" if adString in new_name and role not in after.roles: await after.add_roles(role) elif adString in old_name and adString not in new_name and role in after.roles: await after.remove_roles(role)删除多余的
user=guild.get_member(after.id)语句,after本身就是Member对象,可直接调用方法。验证后台Intents权限
即便代码中声明了intents = discord.Intents().all(),仍需在Discord开发者后台的机器人页面,手动开启服务器成员意图(Server Members Intent)和Presence意图(Presence Intent),否则机器人无法接收on_member_update事件。
修复后的完整代码示例
import discord from discord.ext import commands intents = discord.Intents().all() online = False bot = commands.Bot(command_prefix='.', case_insensitive=True, intents=intents, status=discord.Status.online, activity=discord.Game(name="ignore", type=2)) bot.remove_command('help') @bot.event async def on_ready(): print("ONLINE") global guild, adString, role, online guild = bot.get_guild(998691667831951442) adString = "maven" # 替换为正确的角色ID role = discord.utils.get(guild.roles, id=123456789012345678) online = True @bot.event async def on_member_update(before, after): if online: old_name = before.activity.name.lower() if before.activity else "" new_name = after.activity.name.lower() if after.activity else "" if adString in new_name and role not in after.roles: await after.add_roles(role) elif adString in old_name and adString not in new_name and role in after.roles: await after.remove_roles(role) # 替换为你的机器人Token bot.run("YOUR_BOT_TOKEN")
内容的提问来源于stack exchange,提问作者Conetic
相关产品推荐
相关产品推荐

