python - Discord.py:我如何让机器人获取在给定时间内对消息做出反应的用户列表
问题描述
我正在 python 3.8.6 上制作一个 discord.py 机器人。
我希望这个特定的功能以特定的方式工作......
- 机器人发送嵌入
message = await ctx.send(embed=e)
- 机器人将添加对嵌入的反应
await message.add_reaction('✅')
- 机器人将等待 30 秒让其他用户做出反应,并列出在 30 秒内做出反应的人
- 继续执行其他命令
代码-
@bot.command()
async def command_name(ctx, function):
#code for function 1
#code for function 2
# making the embed
message = await ctx.send(embed=e)
await message.add_reaction('✅')
def check(reaction, user):
if user not in players and not user.bot:
players.append(user.mention)
return reaction.message == message and str(reaction.emoji) == '✅'
try:
await bot.wait_for('reaction_add', timeout=10, check=check)
except asyncio.TimeoutError:
await ctx.send('time is up, and not enough players')
else:
await ctx.send(players)
# further code
问题:机器人立即发送列表玩家
问题:我可以添加什么让它等待 30 秒,将列表附加到对嵌入做出反应的用户,然后发送列表,如果 30 秒后 len(players) 不是 3 或更多发送 -
await ctx.send('time is up, and not enough players')
解决方案
问题是await bot.wait_for('reaction_add', timeout=10, check=check)
在做出的第一个反应中进行。在这种情况下,机器人反应会立即触发此事件,因此将返回一个空列表。
我想到了两个选择:
- 使检查函数始终返回 False,但仍附加用户。这样,wait_for 函数将保持活动状态,直到超时,然后引发异常。在 except 块中继续您的代码或传递它。
- 等待 30 秒,然后再次获取消息并附加所有对复选标记做出反应的用户。
第一个选项:
@client.command()
async def command_name(ctx):
players = []
message = await ctx.send("Message")
await message.add_reaction('✅')
def check(reaction, user):
if user not in players and not user.bot:
players.append(user.mention)
return False
try:
await client.wait_for('reaction_add', timeout=30, check=check)
except asyncio.TimeoutError:
pass
if len(players) < 3:
await ctx.send('Time is up, and not enough players')
else:
await ctx.send(players)
第二个(首选)选项:
@client.command()
async def command_name(ctx):
players = []
message = await ctx.send("Message")
await message.add_reaction('✅')
await asyncio.sleep(30)
message = await ctx.fetch_message(message.id)
for reaction in message.reactions:
if reaction.emoji == '✅':
async for user in reaction.users():
if user != client.user:
players.append(user.mention)
if len(players) < 3:
await ctx.send('Time is up, and not enough players')
else:
await ctx.send(players)
推荐阅读
- mysql - 如何延迟删除?
- sql - sql 数据透视表 为 PIV 多次指定了“CreateDate”列
- git - 来自私有 git 存储库的 Golang 和依赖项
- regex - Visual Studio Find in Files 在其他字符串中搜索确切的字符串
- mysql - 为什么克隆 RDS 集群比 snapc 更快、更节省空间
- join - Oracle SQL Developer - 将更多行连接成一行
- apache-spark - Spark SQL where 子句中谓词的计算顺序
- reactjs - 反应地图功能不重新渲染
- sql - 如何在 Oracle 触发器主体中使用带引号的“引用”标识符
- android - 从对象调用 findViewById()