【问题标题】:Repeating a function when someone reacts to it当有人对它做出反应时重复一个功能
【发布时间】:2021-05-31 21:15:00
【问题描述】:

试图做到这一点,以便当有人使用表情符号对消息做出反应时,它会重复该功能 - 尝试在批处理文件中找到类似于 goto 的内容

例如:我输入$randomcar

Bot 发送:Your chosen car is the bmw! 和 ????反应。当我按下它时,它会再次重复该功能:

Bot 发送 Your chosen car is the audi! 和 ????我可以再次按下以重复该功能的反应

@bot.command()
async def randomcar(ctx):
 while True:
   msg = await ctx.send("Your chosen car is the {}!".format(random.choice(cars)))
   await msg.add_reaction("????")
   async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
     if msg.reaction=="????" and msg.id:
      continue

我收到错误:

Syntax error: continue not properly in loop

谢谢

【问题讨论】:

  • while True 不是个好主意 - 它可能会阻止所有代码。
  • 有什么建议吗?
  • 不确定您的案例的复杂性 - 但也许值得考虑在 python 中实现观察者模式。 ^^ 基本上你想观察输入数据并在出现某种模式时对其做出反应。
  • 对不起,我是个初学者 - 你介意解释一下吗?
  • 成为初学者始终是开发的最佳心态,因为我们必须找到或开发的每一个解决方案对我们来说都是新的。所以我们总是开始寻找一个好的解决方案。 ^^ 提出观察者模式作为硬编码解决方案对于您的情况来说有点棘手 - 即使它是某些编程语言(如 java)中的关键概念之一 - 所以如果有更简单或更多的方法,我建议您进行一些研究适合您的解决方案,您已经通过等待输入来编写核心概念,然后对其进行响应。

标签: python discord.py


【解决方案1】:

这可以使用递归来完成:

@bot.command()
async def randomcar(ctx):
    msg = await ctx.send("Your chosen car is the {}!".format(random.choice(cars)))
    # you may need to check if your bot has the "add reactions" permission
    await msg.add_reaction("?")
    await bot.wait_for(
        "reaction_add",
        check=lambda reaction, user: user == ctx.author and reaction.emoji == "?" and reaction.message == msg,
    )
    await randomcar(ctx)

您还可以添加timeout,之后它将停止重复:

@bot.command()
async def randomcar(ctx):
    msg = await ctx.send("Your chosen car is the {}!".format(random.choice(cars)))
    await msg.add_reaction("?")
    try:
        await bot.wait_for(
            "reaction_add",
            timeout=10.0,  # 10 second timeout
            check=lambda reaction, user: user == ctx.author and reaction.emoji == "?" and reaction.message == msg,
        )
    except asyncio.TimeoutError:
        try:
            await msg.remove_reaction("?", bot.user)
        except discord.NotFound:
            pass
    else:
        await randomcar(ctx)

【讨论】:

  • 抱歉,您介意解释一下为什么第二个更好吗?
  • @Pricysquirrl 第二个选项使机器人在超时后停止检查新反应。因此,如果该命令被多次使用,机器人不需要永远检查每条消息的新反应。
  • 哦,这会导致将来出现性能问题吗?
  • @Pricysquirrl 是的,它可能会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2021-03-06
  • 1970-01-01
  • 2021-06-28
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多