简体   繁体   English

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

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

I am creating a telegram bot.我正在创建一个电报机器人。 There is a need to create a timer when you click on the button.单击按钮时需要创建一个计时器。 In the example, this is the button: "Hero".在示例中,这是按钮:“Hero”。 How to make sure that the timer is not re-created when the same button is clicked.如何确保在单击同一个按钮时不会重新创建计时器。

@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)

If I create a timer before processing the button, I get:如果我在处理按钮之前创建一个计时器,我会得到:

threads can only be started once

One of the idea is to use a global list其中一个想法是使用全局列表

Initialize a list globally on top of the file.在文件顶部全局初始化一个列表。

CACHE=[]

Create a timer free function.创建一个免费的计时器 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)

On the handler, check if the user id is in the CACHE list在处理程序上,检查用户 ID 是否在缓存列表中

-> on button click - >点击按钮

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