Ожидание ответа до истечения времени ожидания - PullRequest
0 голосов
/ 03 июля 2019

Я хотел бы ввести команду в мой бот, которая ждет определенного ответа перед выполнением этой команды ответа.Если этот ответ не виден в течение минуты, он сбрасывается.

Я думал, что для этого потребуется модуль времени, в частности time.sleep ().Однако, поэкспериментировав с этим, обнаружил, что time.sleep () работает в течение всей своей продолжительности и не может быть остановлен до завершения.Имеет смысл, когда вы думаете об этом, задний план 20/20.Что я пробовал:

@commands.command()
@commands.guild_only()
async def challenge(self, ctx):
    # opens and loads in player one's character sheet. This is done in this method solely because I'm unsure if
    # loading json files in __init__ is actually a good idea. If I understand things correctly, things in a class's
    # __init__ is ran EVERY TIME a method is called within it. If so, then the json files would be opened, loaded,
    # and closed multiple times in a single run. Seems inefficient, and bad coding.
    if self.game == 0:
        player = str(ctx.message.author)
        path = os.getcwd()
        charFolder = os.path.join(path + "/characters/")
        charFile = Path(charFolder + player + ".txt")
        if not charFile.is_file():
            await ctx.send("You don't even have a character made to fight. What are you planning to do? Emoji the"
                           "opponent to death? Make a character, first.")
        elif self.game == 0.5:
            await ctx.send("A challenge has already been issued.")
        else:
            self.pOneUsername = ctx.message.author
            file = open(charFolder + player + ".txt", "r", encoding="utf-8")
            charStats = json.load(file)
            file.close()

            self.pOneInfo = charStats

            await ctx.send(self.pOneInfo['name'] + " has issued a challenge. Who accepts? (type !accept)")
            self.game = 0.5
            time.sleep(30)
            await ctx.send("30 seconds to respond to challenge.")
            time.sleep(20)
            await ctx.send("10 seconds to respond to challenge.")
            time.sleep(10)("closing challenge offered.")
            self.game = 0 

Я хочу, чтобы игра «ждала» нужную минуту, и это работает здесь, но поскольку она спит, она не отвечает никому, набрав «! Accept»Команда принять вызов, пока не пройдет минута, и к этому времени python self.game будет сброшено до 0, в результате чего команда '! accept' не будет работать.Любые идеи или шаги о том, как получить желаемый результат?

команда! Accept, если она вам нужна:

player = str(ctx.message.author)
path = os.getcwd()
charFolder = os.path.join(path + "/characters/")
charFile = Path(charFolder + player + ".txt")
if not charFile.is_file():
    await ctx.send("You don't even have a character made to fight. What are you planning to do? Emoji the "
                   "opponent to death? Make a character, first.")
elif ctx.message.author == self.pOneUsername:
    await ctx.send("You can't fight yourself. This isn't Street Fighter.")
else:
    self.game = 1
    self.pTwoUsername = ctx.message.author
    file = open(charFolder + player + ".txt", "r", encoding="utf-8")
    charStats = json.load(file)
    file.close()

    self.pTwoInfo = charStats

    self.pOneTotalHP = self.pOneInfo['hp']
    self.pTwoTotalHP = self.pTwoInfo['hp']
    self.pOneCurrentHP = self.pOneInfo['hp']
    self.pTwoCurrentHP = self.pTwoInfo['hp']
    self.pOneLevel = self.pOneInfo['level']
    self.pTwoLevel = self.pTwoInfo['level']
...