电报机器人无法处理多个用户

时间:2019-11-27 09:59:17

标签: python-3.x telegram telegram-bot python-telegram-bot

我正在用pytelegrambotapi构建电报机器人游戏“ Spelling Bee”。

根据游戏,向用户发送了语音音频,他必须正确拼写。

当我一个人玩时,游戏运行正常。 但是,当另一个用户玩同一游戏时,就会出现问题。

第二个用户一旦开始游戏,第一和第二个游戏就会停止。没有错误或引发异常,脚本只是冻结。

我已经跟踪了程序流程:似乎第二个用户开始游戏后,脚本的作用范围不超过talk(message),因此消息处理程序talking(msg)无法捕获其输入。

游戏实例保存在主脚本中定义的字典中。

bee_instances{}

这是主要脚本。

@bot.message_handler(commands=['bee'])
def talk(message):
    parameter = utils.extract_arg(message.text)
    if parameter != 'sting':
        bee_instances[message.from_user.id] = bee_class.SpellingBee(PATH_TO_DICTIONARIES + str(message.from_user.id)
                                                                    , bot, message)
        print(bee_instances[message.from_user.id])
        print(len(bee_instances))
        current = bee_instances[message.from_user.id]
        current.start()
    else:
        bee_instances[message.from_user.id] = bee_class.SpellingBee('stingy.txt', bot, message)
        print(bee_instances[message.from_user.id])
        print(len(bee_instances))
        current = bee_instances[message.from_user.id]
        current.start()
    print('Done')


@bot.message_handler(regexp='^[a-zA-Z]+')
def talking(msg):
    print('Intercepting')
    reply = msg.text
    try:
        current = bee_instances[msg.from_user.id]
    except Exception:
        raise Exception
    else:
        current.check_answer(reply)

这是SpellingBee类

class SpellingBee:
    def __init__(self, user_dictionary, bot, message):
        print('Instance created')
        print(self.__hash__())
        self.user_dictionary = user_dictionary
        self.bot = bot
        self.message = message
        self.list_of_words = utils.load_dictionary(self.user_dictionary)
        random.shuffle(self.list_of_words)
        print(self.list_of_words)
        self.game_is_on = False
        self.user_has_answered = False
        self.length = len(self.list_of_words)
        self.score = 0
        self.word = None
        self.article = None
        print("ID: %d" % self.message.from_user.id)

    def stop_game(self):
        print('Game stopped.')
        self.game_is_on = False
        self.user_has_answered = True

    def start(self):
        print('Starting game')
        self.game_is_on = True
        for _word in self.list_of_words:
            print('Entering for-loop.')
            print(self.__hash__())
            if self.game_is_on is True:
                self.user_has_answered = False
                self.word = _word.split(':')[0].lower().rstrip()
                print(self.word)
                utils.send_audio_general(self.message, self.bot, self.word)
                self.bot.send_message(self.message.from_user.id, "Can you spell it?")
                while self.user_has_answered is not True:
                    print('Waiting...')
                    time.sleep(5)
            else:
                print('Loop broken')
                break
        self.word = None
        self.bot.send_message(self.message.from_user.id, f"Game is over.\n "
                                                         f"Your score: {self.score} out of {self.length}")
        self.stop_game()

    def check_answer(self, user_reply):
        print('Checking answer')
        print("ID: %d" % self.message.from_user.id)

        if self.word is not None:
            if self.word.lower() == user_reply.lower():
                self.score += 1
                self.article = wordreference.WordReference(self.word,
                                                           emo_presets['classic']).get_full_info()
                self.bot.send_message(self.message.from_user.id, f"{emo['green check']}"
                                                                 f"Correct!\nAnswer: {self.word}"
                                                                 f"\n{self.article}")
                self.user_has_answered = True

            elif user_reply.lower() == 'stopit':
                self.stop_game()

            else:
                self.bot.send_message(self.message.from_user.id, f"{emo['red cross']}Wrong!"
                                                                 f"\nAnswer: {self.word}\n"
                                                                 f"{self.article}")
                self.user_has_answered = True
        else:
            pass

0 个答案:

没有答案