Reputation: 25
i need to execute code every x minutes in pyTelegramBotAPI how i need to do it?
import telebot
from datetime import timedelta, datetime
@bot.message_handler(commands=['start'])
def start_message(message):
???
Upvotes: 1
Views: 1561
Reputation: 176
time.sleep
and threading
work wonders. Let's say that the audience of your bot is people who constantly forget to buy carrots. And you want to remind them every minute.
In the following code, the send_reminder
function sends a reminder to all bot users every 60 seconds (the variable delay
is responsible for the number of seconds). To run the function, we use threading, and to create a delay, we use time.sleep(delay)
. threading
is needed so that time.sleep()
stops only the target function, and not the entire bot.
The function uses an infinite loop, in which the bot first sends reminders to all users from the ids
, then waits for 1 minute, and everything repeats again.
import telebot
import threading
from time import sleep
bot = telebot.TeleBot('token')
delay = 60 # in seconds
ids = []
@bot.message_handler(commands=['start'])
def start_message(message):
global ids
id = message.from_user.id
ids.append(id)
bot.send_message(id, 'Hi!')
def send_reminder():
global ids
while True:
for id in ids:
bot.send_message(id, 'Buy some carrots!')
sleep(delay)
t = threading.Thread(target=send_reminder)
t.start()
while True:
try:
bot.polling(none_stop=True, interval=0)
except:
sleep(10)
Upvotes: 1