Я пытаюсь заставить пользователя ответить на ответ бота, а затем отправить другое сообщение - PullRequest
0 голосов
/ 27 мая 2020

Как заставить бота снова ответить? Я пытаюсь заставить бота заставить пользователя отвечать на отправленное сообщение, а затем отвечать, говоря, что уже слишком поздно или они это сделали.

  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 ]

1 голос
/ 27 мая 2020

Вы можете использовать await bot.wait_for('message'), чтобы дождаться сообщения. Передав аргумент check, мы также можем указать подробности ожидаемого сообщения. Я повторно использую свой код 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!")
0 голосов
/ 27 мая 2020

Вы не хотите объединять это в одну команду. Также 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]

Единственным недостатком этого является то, что он ждет, пока вы не отправите сообщение, прежде чем сообщить вам, что вы прошли время.

...