S
S
sanitardev2021-08-20 18:53:30
Python
sanitardev, 2021-08-20 18:53:30

How to make a cooldown for using a command in pytelegrambotapi?

How to make a cooldown for using a command in pytelegrambotapi?
Let's say that you can milk a cow once an hour.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RusiDev, 2021-08-20
@RusiDev

Primitive, but gets the job done

import time


def korova():
    start = 10
    while True:
        time.sleep(1)
        print('Ждите')
        start = start - 1
        if int(start) == 0:
            print('Доим корову')
        else:
            continue

korova()

I
Ilhomidin Bakhoraliev, 2021-08-23
@ilhomidin

All you need is a place to store the last date the command was used and add one check to the handler.
Here is a small example:

import datetime

context = {}

@bot.message_handler(commands=["cow"])
def cow_command(message):
    last_command_use_time = context.get(message.user_id)
    if not last_command_use_time or (datetime.datetime.now() - last_command_use_time).hour > 1:
            # Логика команды /cow
            context[message.user_id] = datetime.datetime.now()
    else:
        # Сообщение об ограничениях использования команды

For the correct operation of the limiter, the persistance context store is required. when the bot is stopped, the dates will be lost, which means that when the bot is restarted, regardless of the last use of the command, users will have access to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question