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



我有一个命令,它允许人们对消息做出反应,输入";战斗";。然后通过另一个命令,选择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循环中,因为它得到了消息,消息没有任何反应,所以没有列表,所以列表超出了修复范围,你必须添加try和except,所以它跳过了消息,没有反应。

代码:

@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,因为如果已经有一个,它将不断检查消息