繁体   English   中英

如何创建带验证的计时器(python + telegram)

[英]how to create a timer with validation (python + telegram)

我正在创建一个电报机器人。 单击按钮时需要创建一个计时器。 在示例中,这是按钮:“Hero”。 如何确保在单击同一个按钮时不会重新创建计时器。

@bot.message_handler(content_types=['text'])
def buttons(message):
    if message.chat.type == 'private':
        if message.text == 'Hero':
            def hello():
                print ('hello')

            t = threading.Timer(4, hello)

            if t.is_alive():
                print('wait to end')
            else: 
                t.start()
                print('timer is up')
        else:
            bot.send_message(message.chat.id, 'default1')
    else:
        bot.send_message(message.chat.id, 'default2')

#RUN
bot.polling(none_stop=True)

如果我在处理按钮之前创建一个计时器,我会得到:

threads can only be started once

其中一个想法是使用全局列表

在文件顶部全局初始化一个列表。

CACHE=[]

创建一个免费的计时器 function。

def free_user(t: Timer, user_id): # here t is Timer
    t.is_alive ... wait for the timer to end
    if user_id in CACHE:
         CACHE.remove(user_id)

在处理程序上,检查用户 ID 是否在缓存列表中

- >点击按钮

if user_id in CACHE:
    # already clicked user
    callback.answer("dude please wait")
else:
    # new user going to click for the first time
    global CACHE
    CACHE.append(user_id)
    free_user(timer....., user_id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM