Search code examples
pythonmultithreadingpython-telegram-bot

How can I make a python thread count down and then perform an action?


I have a script that accesses the api for Telegram bots, but it unfortunately can only process one message at a time.

My end goal is to have it start a timer thread when someone starts a game, and after a certain time (if they haven't already won the game) it would reset the game to avoid preventing another user in the group from playing a game (I set it up to only have one game at a time to avoid confusion).

So for example:

With a word unscramble game I tried:

import time
import telepot

def handle(msg):
    message_text = msg['text']
    message_location_id = msg['chat']['id']
    global game_active
    global word_to_unscramble
    if message_text == '/newgame':
        game_active = True
        <game function, defines word_to_unscramble>
        time.sleep(30)
        if game_active:
            game_active = False
            word_to_unscramble = None
            bot.sendMessage(message_location_id, 'Sorry the answer was ' + word_to_unscramble)
    if message_text == 'word_to_unscramble':
        game_active = False
        bot.sendMessage(message_location_id, 'You win!')

# I added this part in as an echo, just to see when it processed the message
    if 'text' in msg:
        bot.sendMessage(message_location_id, message_text)

game_active = False

word_to_unscramble = None

bot = telepot.Bot('<my api token>')

bot.message_loop(handle)

With this code, however, it would receive and process the first message, then wait 30 seconds, send the failed code, and then process the second one.

I'm not too familiar with the process of threading, so is there a way I can set it up to start a new thread to handle the countdown timer so it can continue to process messages or is that all a lost cause?

If there's not a way to set up a timer using my current method of accessing the telegram api, what would the smarter way be?


Solution

  • Haven't worked over python-telegram-bot yet, But all I know about the timer use in Python is using sched gives you leverage to timer abilities to your python code. Since in your app multithreading will make more sense and for that you can look out for threading.Timer class.