Discord py bot 限制玩家对投票的一个反应

Discord py bot limit player to one reaction for a poll

我一直在开发一个 discord py bot,并一直在尝试实现创建投票的能力,并让每个人只对投票做出一次反应。我已经成功创建了投票(包括开始投票的机器人反应)。但是,我正在努力将玩家的反应限制为仅列出的反应以及每次投票中只有一种反应。

到目前为止,这是控制对消息的反应的代码

async def on_reaction_add(reaction, user):
channel = discord.utils.get(user.guild.channels, name=pollchannel)
print(reaction.message.id)
if user.name != botname and reaction.message.channel == channel:
    cache_msg = discord.utils.get(client.cached_messages, id=reaction.message.id)
    print(cache_msg.reactions)
    print(reaction.emoji)
    if reaction.emoji not in cache_msg.reactions:
        await reaction.remove(user)
    elif len(reaction.message.reactions) > 1:
        await reaction.remove(user)

我一直在测试和尝试不同的东西,但无法让它按预期工作。目前它总是删除反应消息。似乎正在检查反应表情符号是否在缓存中(即使当我将它们打印到控制台时我可以看到它在缓存中)它没有找到它。 elif 语句几乎可以工作,但我想让每个人都能够添加一个反应,这似乎只是将消息限制为仅保留机器人添加的反应。

感谢任何帮助!

打印 cache_msg.reaction 时,您会得到一个反应列表以及其他信息,例如 reaction.authorreaction.countetcetera。因此,需要遍历具体的反应信息。这是下面的代码,以及进一步的解释。

@client.event
async def on_reaction_add(reaction, user):
    channel = discord.utils.get(user.guild.channels, name=pollchannel)
    print(reaction.message.id)
    # I recommend using ids instead, since any user could have your bot's name
    if user.id != botid and reaction.message.channel == channel:
        cache_msg = discord.utils.get(client.cached_messages, id=reaction.message.id)
        print(cache_msg.reactions)
        print(reaction.emoji)

        # Check every reaction in the cache_msg
        for r in cache_msg.reactions:
            # Check if the user is an author of the reaction
            # AND check if the user is not a bot
            # AND check if this reaction emoji isn't the one they just reacted with
            if user in await r.users().flatten() and not user.bot and str(r) != str(reaction.emoji):
                # Remove their previous reaction
                await cache_msg.remove_reaction(r.emoji, user)

有用的链接: