这是一个基本代码,当您使用特定表情符号对特定消息做出反应时,它会为您提供角色,或者在您没有反应时移除角色
import discord
import os
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=',', intents=intents)
@bot.event
async def on_ready():
print('bot is online')
#this works
@bot.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
if message_id == 869153559042748446:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, bot.guilds)
if payload.emoji.name == '''1️⃣''':
role = discord.utils.get(guild.roles, id=868532817984901151)
else:
print('''else''')
role = None
if role is not None:
member = payload.member
if member is not None:
await member.add_roles(role)
print('''gave role {} to {}'''.format(role, member))
else:
print('''member not found''')
else:
print ('''role not found''')
#This is an exact copy of **on_raw_reaction_add** but
#**await member.add_roles(role)** changed to *await member.remove_roles(role)*
@bot.event
async def on_raw_reaction_remove(payload):
message_id = payload.message_id
if message_id == 869153559042748446:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, bot.guilds)
if payload.emoji.name == '''1️⃣''':
role = discord.utils.get(guild.roles, id=868532817984901151)
else:
print('''else''')
role = None
if role is not None:
member = payload.member
if member is not None:
await member.remove_roles(role)
print('''gave role {} to {}'''.format(role, member))
else:
print('''member not found''') #This always prints
else:
print ('''role not found''')
bot.run(os.getenv('TOKEN'))
on_raw_reaction_add 按预期工作,
但是当涉及到 on_raw_reaction_remove 时,它无法找到 member,即使它是 on_raw_reaction_add 的精确副本。
存在意图和服务器成员意图已开启。
答案 0 :(得分:1)
有效载荷上的 member
属性仅在添加反应 (Docs) 时有效
添加反应的成员。仅当 event_type 为 REACTION_ADD 且反应在公会内时可用。
您可以尝试使用 discord.utils
或 guild.get_member()
示例:
@bot.event
async def on_raw_reaction_remove(payload):
...
# discord.utils.get()
member = discord.utils.get(guild.members, id=payload.user_id)
# guild.get_member()
member = guild.get_member(payload.user_id)
...