我的不和谐机器人有问题。当我专门单击第二次迭代时,它会停止工作,而当我单击任何其他迭代时,它不会执行任何操作。当我点击反应时,它应该调用 check() 函数。
import asyncio
from discord.ui import Button, View
import discord
from discord.commands import slash_command
from discord.ext import commands
class Test(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.stop_loop = False
@slash_command(name='test', description='')
async def test(self, ctx):
def check(reaction, user): # Our check for the reaction
self.stop_loop = True
print("clicked")
return user == ctx.author and str(reaction.emoji) in ["✅"]
for i in range(1, 100):
if self.stop_loop:
return
if i == 1:
embed = discord.Embed(title="1x")
interaction: discord.Interaction = await ctx.respond(embed=embed)
sent_embed = await interaction.original_response()
await sent_embed.add_reaction('✅')
await asyncio.sleep(2)
embed = discord.Embed(title=f"{i}x")
await interaction.edit_original_response(embed=embed)
await sent_embed.add_reaction('✅')
try:
reaction, user = await self.bot.wait_for("reaction_add", check=check, timeout=2.0)
print(reaction)
if reaction:
embed = discord.Embed(title=f"You clicked on {i}")
await interaction.edit_original_response(embed=embed)
return
except asyncio.exceptions.TimeoutError:
await asyncio.sleep(1)
def setup(bot):
bot.add_cog(Test(bot))
我的结果:
没有抛出任何错误,但不会停止工作。
使用事件代替 bot.wait_for()
bot.wait_for() 等待消息得到响应。当消息得到除机器人反应之外的第一反应时,它将停止等待。
使用 on_raw_reaction_add() 或 on_reaction_add() 事件。当消息收到用户的新反应时会触发这些。