我正在尝试让用户回复漫游器响应,然后发送另一条消息

时间:2020-05-26 23:40:01

标签: python discord discord.py

如何让机器人再次响应?我试图让机器人使用户响应所发送的消息,然后响应说是否为时已晚或他们做到了。

  import discord
  from discord.ext import commands
  import time
  import random
  @commands.command(aliases=["RandomChocolate", "choco"])
  @commands.cooldown(1, 15, commands.BucketType.user)
  async def chocolate(self, ctx):
    food=["hershey", "kitkat", "milk"]
    rF = random.choice(food)
    rFC = rF[:1]
    rFL = rF[-1]
    await ctx.send(f"**Hint:** It starts with **{rFC}** 
    and ends with **{rFL}**, you have 15 seconds to answer 
     by the way.")
     if ctx.message.content == rF:
       await ctx.send("Ok")
     else:
       time.sleep(15)
       await ctx.send(f"Too Late!")

2 个答案:

答案 0 :(得分:1)

您可以使用await bot.wait_for('message')等待消息。通过传递check参数,我们还可以指定有关我们正在等待的消息的详细信息。我正在重用this other answer中的message_check代码

class MyCog(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
  @commands.command(aliases=["RandomChocolate", "choco"])
  @commands.cooldown(1, 15, commands.BucketType.user)
  async def chocolate(self, ctx):
    food=["hershey", "kitkat", "milk"]
    rF = random.choice(food)
    rFC = rF[:1]
    rFL = rF[-1]
    await ctx.send(f"**Hint:** It starts with **{rFC}** 
    and ends with **{rFL}**, you have 15 seconds to answer 
     by the way.")
    try:
      response = await self.bot.wait_for("message", timeout=15, check=message_check(channel=ctx.channel, author=ctx.author, content=rF))
      await ctx.send("OK")
    except asyncio.TimeoutError:
      await ctx.send("Too Late!")

答案 1 :(得分:0)

您不想将其捆绑为一个命令。此外,time.sleep会停止整个程序,asyncio.sleep会暂停当前正在运行的协程。

import asyncio
import discord
from discord.ext import commands
import time
import random

chocolate_users = {}


    @commands.command(aliases=["RandomChocolate", "choco"])
    @commands.cooldown(1, 15, commands.BucketType.user)
    async def chocolate(self, ctx):
        food = ["hershey", "kitkat", "milk"]
        rF = random.choice(food)
        rFC = rF[:1]
        rFL = rF[-1]
        await ctx.send(f"**Hint:** It starts with **{rFC}** and ends with **{rFL}**, you have 15 seconds to answer by the way.")
        chocolate_users[ctx.message.author.id] = [rF, time.time()+15]

@client.event()
async def on_message(message):
    if message.author.id in chocolate_users.keys(): # check if the user started a guess, otherwise do nothing
        data = chocolate_users[message.author.id]
        if time.time() > data[1]:
            await message.channel.send('You exceeded the 15 second time limit, sorry.')
            del chocolate_users[message.author.id]
        elif message.content.lower() != data[0]:
            await message.channel.send('Sorry, that is wrong. Please try again.')
        else:
            await message.channel.send('Great job, that is correct!')
            ## other stuff to happen when you get it right ##
            del chocolate_users[message.author.id]

唯一的缺点是它会等到您发送一条消息,然后才告诉您您已经过去了。