关于Discord.py中bot.wait_for()与反应交互的技术求助
解决discord.py中
bot.wait_for('reaction_add')结合消息反应的问题 我仔细看了你这段用discord.py实现的反应角色代码,问题出在wait_for的check函数里,咱们来一步步修复:
核心问题:Check函数的用户判断错误
你当前的check函数里写了user == message.author,但这里的message是bot发送的测试消息,所以message.author指向的是bot自己的账号,而不是发起命令的用户。这就导致只有bot自己点反应才会触发逻辑,自然收不到用户的操作。
修正后的check函数应该对比发起命令的用户(也就是你定义的member变量):
def check(reaction, user): return user == member and str(reaction.emoji) == '\u2642'
其他需要注意的细节
- 补充必要的导入:代码里用到了
get和asyncio.TimeoutError,要确保顶部导入了这两个模块:
import asyncio from discord.utils import get
- 可选:支持多表情对应不同角色:如果之后想扩展功能,让不同表情对应不同代词角色,可以优化check和后续逻辑:
def check(reaction, user): # 判断用户是命令发起者,且表情在预设列表里 return user == member and str(reaction.emoji) in emojis
然后在成功触发的分支里根据表情分配角色:
else: emoji = str(reaction.emoji) # 建立表情和角色名的映射 role_mapping = { '\u2642': "He/Him", '\u2640': "She/Her", '\u2716': "Remove Pronouns" } target_role = get(member.guild.roles, name=role_mapping[emoji]) if target_role: if emoji == '\u2716': await member.remove_roles(target_role) print(f"Removed pronoun role from {member.name}") else: await member.add_roles(target_role) print(f"Assigned {member.name} {target_role.name} pronouns.") else: await ctx.send("对应的角色不存在,请联系管理员配置。")
- 优化超时提示:可以选择编辑原测试消息并移除表情,让频道界面更整洁:
except asyncio.TimeoutError: await message.edit(content="Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.") await message.clear_reactions()
修正后的完整代码
import asyncio from discord.utils import get # 假设kelutralBot是你定义的bot实例 @kelutralBot.command(name='testreaction') async def testReaction(ctx): member = ctx.message.author message = await ctx.send("This is a test message.") emojis = ['\u2642','\u2640','\u2716'] for emoji in emojis: await message.add_reaction(emoji) def check(reaction, user): return user == member and str(reaction.emoji) == '\u2642' try: reaction, user = await kelutralBot.wait_for('reaction_add', timeout=60.0, check=check) except asyncio.TimeoutError: await message.edit(content="Window has passed to self-assign pronouns. Please DM a mod if you would still like to do so.") await message.clear_reactions() else: print(reaction) male = get(member.guild.roles, name="He/Him") await member.add_roles(male) print(f"Assigned {member.name} He/Him pronouns.")
内容的提问来源于stack exchange,提问作者skipper587
相关产品推荐
相关产品推荐

