![](/img/trans.png)
[英]How can I make a loop to perform action on Neighbours of my start box in python?
[英]How can I make a python thread count down and then perform an action?
我有一個腳本可以訪問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-telegram-bot上工作,但是我所知道的有關在Python中使用計時器的所有信息都是使用sched
使您可以利用python代碼的計時器功能。 由於在您的應用程序中, multithreading
會更有意義,因此您可以查找threading.Timer
類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.