【问题标题】:How can I make a python thread count down and then perform an action?如何让 python 线程倒计时然后执行操作?
【发布时间】:2016-09-24 14:40:19
【问题描述】:

我有一个脚本可以访问 Telegram 机器人的 api,但不幸的是它一次只能处理一条消息。

我的最终目标是让它在有人开始游戏时启动计时器线程,并在一定时间后(如果他们尚未赢得游戏)重置游戏以避免阻止组中的其他用户玩游戏(我将其设置为一次只玩一个游戏以避免混淆)。

例如:

我尝试了一个单词解读游戏:

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)

但是,使用此代码,它将接收并处理第一条消息,然后等待 30 秒,发送失败的代码,然后处理第二条消息。

我对线程的过程不太熟悉,所以有没有办法可以设置它来启动一个新线程来处理倒数计时器,以便它可以继续处理消息,或者这一切都是失败的原因?

如果没有办法使用我当前访问电报 api 的方法设置计时器,那么更聪明的方法是什么?

【问题讨论】:

    标签: python multithreading python-telegram-bot


    【解决方案1】:

    还没有使用过 python-telegram-bot,但我所知道的关于 Python 中计时器使用的所有信息都是使用 sched 让您可以利用 Python 代码的计时器功能。因为在您的应用程序中multithreading 会更有意义,为此您可以留意threading.Timer 类。

    【讨论】:

    • 我尝试添加 threading.Timer() 并等待 30 分钟来执行我定义的方法,但是当我运行脚本时它没有等待 30 秒;它只是直接跳到新方法,然后移到下一条消息。代码是:“t = threading.Timer(30.0, check_status) t.Start” 我做错了什么吗?
    • 您放置的代码只会等待 30 秒,您可以使用不同的次数对其进行测试。如果你想让它等待 30 分钟,那就是 1800 秒
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多