【问题标题】:Discord.py bot: How to make a bot respond to command only in certain circumstances?Discord.py bot:如何让机器人仅在特定情况下响应命令?
【发布时间】:2021-12-01 18:17:43
【问题描述】:

我正在用 Python 制作一个 Discord 机器人,我想在机器人仅在某些情况下响应命令时添加这样的功能。

例如:

我:!quiz

Bot:提供变体 - !a; !b; !c

我:选择变体和机器人响应

  • 关键是如果有人使用命令!a!b!c 在使用 !quiz 命令之前,机器人不会响应。有什么想法吗?

【问题讨论】:

    标签: python discord bots


    【解决方案1】:

    您可以使用bot.wait_for() 等待用户回复:

    @bot.command(pass_context=True)
    async def quiz(ctx):
    channel, author = ctx.channel, ctx.message.author
    await ctx.send('Choose one:\n!a;\n!b;\n!c;')
    
    answer = await bot.wait_for(
        "message", 
        check=lambda x: x.content.startswith('!') and x.channel == channel and x.author == author
    )
    if answer.content.strip() == '!a':
        # here goes your logic
    

    【讨论】:

      【解决方案2】:

      偏离 Mahrkeenerh 所说的可以使用 wait_for() 下面是一个示例:

      @bot.command()
      async def quiz(ctx):
          await ctx.send("A, B or C")
      
          try:
              msg = await bot.wait_for('message', check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=30.0)
      
          except asyncio.TimeoutError:
              await ctx.send("You took to long...")
      
          else:
              if msg.content == "A":
                  await ctx.send("Correct")
              elif msg.content == "B":
                  await ctx.send("Wrong")
              elif msg.content == "C":
                  await ctx.send("Wrong")
              else:
                  await ctx.send("Huh?")
      

      我们正在发送一条消息,然后等待回复,我们也在检查它是否是原始作者和原始频道。如果是这样,那么我们正在检查是否回答以查看响应是什么。

      【讨论】:

        【解决方案3】:

        你可以使用wait_for():

        Discord.py Make bot wait for reply

        或者,如果您使用了!quiz 命令,您可以使用一个全局变量(一个标志 - 布尔值)来标记。然后在 answers 命令中,检查这个全局变量是否为True,如果是,则响应(并将其重置回False),否则忽略。

        【讨论】:

          猜你喜欢
          • 2021-10-06
          • 2021-11-28
          • 2018-07-09
          • 2020-09-12
          • 2019-12-11
          • 2021-10-22
          • 2020-12-02
          • 2018-05-10
          • 2019-10-17
          相关资源
          最近更新 更多