How can I make a python thread count down and then perform an action?
<p>I have a script that accesses the api for Telegram bots, but it unfortunately can only process one message at a time.</p>

<p>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).</p>

<p>So for example:</p>

<p>With a word unscramble game I tried:</p>

<pre><code>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
        &lt;game function, defines word_to_unscramble&gt;
        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('&lt;my api token&gt;')

bot.message_loop(handle)
</code></pre>

<p>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.</p>

<p>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?</p>

<p>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?</p>

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

python multithreading python-telegram-bot