从反应角色中手动选择用户

Manually picking users from reaction roles

我有一个命令可以让人们对消息做出反应以进入“战斗”。然后用另一个命令,选择了 2 个人。这是我的代码:

@client.command(aliases=['start', 'g'])

async def startbattle(ctx):    
 
    msg = await ctx.send("React to enter battle")
    await msg.add_reaction("")
    await asyncio.sleep(10000000000000000)
    message = await ctx.fetch_message(msg.id)
    for reaction in message.reactions:
        if str(reaction.emoji) == "":
            users = await reaction.users().flatten()
            if len(users) == 1:
                return await msg.edit(embed=discord.Embed(title="Nobody has won the giveaway."))
    try:
        user1 = random.choice(users)
        user2 = random.choice(users)
    except ValueError:
        return await ctx.send("not enough participants")
   

    await ctx.send(f'Battle will be against {user1} and {user2}')


@client.command()
async def pick(ctx):
    async for message in ctx.channel.history(limit=100, oldest_first=False):
        if message.author.id == client.user.id and message.embeds:
            reroll = await ctx.fetch_message(message.id)
            users = await reroll.reactions[0].users().flatten()
            users.pop(users.index(client.user))
            winner1 = random.choice(users)
            winner2 = random.choice(users)
            await ctx.send(f"The battle will be against {winner1.mention} and {winner2.mention}")
            break
    else:
        await ctx.send("No giveaways going on in this channel.")

这是我在使用“pick”命令时遇到的错误,

users = await reroll.reactions[0].users().flatten()
IndexError: list index out of range

错误出现在 for 循环中,因为它获取 msg,而 msg 没有任何反应,所以它没有列表,所以列表超出范围来解决这个问题,你必须添加 try and except there 所以它会跳过没有反应的消息。

代码:

@client.command()
async def pick(ctx):
    async for message in ctx.channel.history(limit=100, oldest_first=False):
        if message.author.id == client.user.id and message.embeds:
            reroll = await ctx.fetch_message(message.id)
            try:
                users = await reroll.reactions[0].users().flatten()
            except:
                break
            users.pop(users.index(client.user))
            winner1 = random.choice(users)
            winner2 = random.choice(users)
            await ctx.send(f"The battle will be against {winner1.mention} and {winner2.mention}")
            return # <--- was the break
    else:
        await ctx.send("No giveaways going on in this channel.")

建议不要在 if 语句中添加 break,因为它会不断检查 msg 是否已经收到