Как поставить кулдаун на кнопку? Пример: вы уже забрали бонус, через 24 часа заберите снова

Рейтинг: -1Ответов: 2Опубликовано: 23.05.2023

Бот работает, ошибок не выдает, но функция кулдауна ни в какую не хочет работать. Может там какие-то БД создавать нужно или ещё чего. Те кто могут на примере моего кода написать, как будет правильно, тем хвала! А именно я не могу понять, как реализовать (исходя из моего кода prize_received_time)

import datetime
import time
from time import time

import telebot
from telebot import types

import constants

# Insert your Telegram bot token here
TOKEN = '***'

dt_now = datetime.datetime.now

dt_now = str(dt_now)

# Create a new Telegram bot instance
bot = telebot.TeleBot(TOKEN)

@bot.message_handler(commands=['start'])
def main(message):
    keyboard = types.InlineKeyboardMarkup()
    end='\n'

    bot.send_message(message.chat.id, '👋Привет, {0.first_name}!''\n🎁 Дарим подарки каждый день!🎁''\n🤖Посмотри что может делать этот бот /coupon🤖'.format(message.from_user), reply_markup = keyboard)

@bot.message_handler(content_types=['text'])
def handle_text(message):
         bot.send_message(message.chat.id, constants.random_message() + '\n🏷 выдан  ' + str(datetime.datetime.now()))
         print(dt_now)
# This function will be called every 24 hours to issue a coupon
def issue_coupon():
    # TODO: Add code to issue a coupon here
    print('Купон выдан в', datetime.datetime.now())

    # Set the time interval for the reminder
time_interval_hours = 24

# Set the time when the prize was received (replace with your actual date and time)
prize_received_time = datetime

REWARD_INTERVAL_SEC = 24 * 60 * 60  # 24 hours in seconds
# Define a function to check if the time interval has passed and send the reminder if so
def check_reminder():
    current_time = datetime.now()
    time_elapsed = current_time - prize_received_time
    if time_elapsed.total_seconds() / 3600 > time_interval_hours:
        print("Напоминание: Вы можете снова забрать свой приз!")

        REWARD_INTERVAL_SEC = 24 * 60 * 60  # 24 hours in seconds

def can_receive_reward(last_reward_time):
    """Проверяет, может ли человек получить вознаграждение на основе его последнего времени вознаграждения."""
    current_time = datetime.datetime.now()
    elapsed_time_sec = current_time - last_reward_time
    if elapsed_time_sec >= REWARD_INTERVAL_SEC:
        return True
    else:
        remaining_time_sec = REWARD_INTERVAL_SEC - elapsed_time_sec
        remaining_time_min = remaining_time_sec // 60
        print(f"Ты уже недавно забирал свою награду, подожди  {remaining_time_min} минут, чтобы снова получить вознаграждение.")
        return False
    
        # Start the bot and automatically issue a coupon every 24 hours
def main():
            while True:
                issue_coupon()
                time.sleep(24 * 60 * 60)

                if __name__ == '__main__':
                    main()

bot.polling(none_stop = True)

Ответы

▲ 0

Вопрос решился добавление этих строчек:

elapsed_time = current_time - last_reward_time[chat_id]
if elapsed_time >= datetime.timedelta(days=1):
return True
else:
return False
else:
return True
▲ -1

Я добавил к функции issue_coupon таймер на каждый 24 часа, которая вызывает функцию check_reminder. Ниже код:

import datetime
import time
from time import time
import schedule
import telebot
from telebot import types



# Insert your Telegram bot token here
TOKEN = '***'

dt_now = datetime.datetime.now

dt_now = str(dt_now)

# Create a new Telegram bot instance
bot = telebot.TeleBot(TOKEN)


@bot.message_handler(commands=['start'])
def main(message):
    keyboard = types.InlineKeyboardMarkup()
    btn1 = types.InlineKeyboardButton(text='Продолжить', callback_data='cont')
    keyboard.add(btn1)

    bot.send_message(message.chat.id,
                     '👋Привет, {0.first_name}!''\n🎁 Дарим подарки каждый день!🎁''\n🤖Посмотри что может делать этот бот /coupon🤖'.format(
                         message.from_user), reply_markup=keyboard)


@bot.callback_query_handler(func=lambda call: True)
def handle_text(call):
    if call.data == 'cont':
        bot.send_message(call.message.chat.id,  '\n🏷 выдан  ' + str(datetime.datetime.now()))
        print(dt_now)


# This function will be called every 24 hours to issue a coupon
def issue_coupon():
    schedule.every().day.at("00:00").do(check_reminder(message=True))

    # Set the time interval for the reminder


time_interval_hours = 24

# Set the time when the prize was received (replace with your actual date and time)
prize_received_time = datetime

REWARD_INTERVAL_SEC = 24 * 60 * 60  # 24 hours in seconds


# Define a function to check if the time interval has passed and send the reminder if so
def check_reminder(message):
    current_time = datetime.datetime.now()
    time_elapsed = current_time - prize_received_time
    if time_elapsed.total_seconds() / 3600 > time_interval_hours:
        bot.send_message(chat_id=message.chat.id, text="Напоминание: Вы можете снова забрать свой приз!")

        REWARD_INTERVAL_SEC = 24 * 60 * 60  # 24 hours in seconds


def can_receive_reward(last_reward_time):
    """Проверяет, может ли человек получить вознаграждение на основе его последнего времени вознаграждения."""
    current_time = datetime.datetime.now()
    elapsed_time_sec = current_time - last_reward_time
    if elapsed_time_sec >= REWARD_INTERVAL_SEC:
        return True
    else:
        remaining_time_sec = REWARD_INTERVAL_SEC - elapsed_time_sec
        remaining_time_min = remaining_time_sec // 60
        print(
            f"Ты уже недавно забирал свою награду, подожди  {remaining_time_min} минут, чтобы снова получить вознаграждение.")
        return False

        # Start the bot and automatically issue a coupon every 24 hours


def main():
    while True:
        issue_coupon()
        time.sleep(24 * 60 * 60)

        if __name__ == '__main__':
            main()


bot.polling(none_stop=True)