Answer the question
In order to leave comments, you need to log in
How to combine schedule and bot.polling()?
Hello!
I have a bot that checks the performance of a certain site after a fixed period of time (for example, every half hour). For this task, I found the schedule package on the Internet, the work with the Telegram api itself is carried out through pyTelegramBotAPI. I encountered the following problem: if the scheduler works, then bot.polling does not work and vice versa, please tell me how to synchronize them.
ps this is how bot get api response but schedule is not working
def main_loop():
bot.polling(True)
while 1:
schedule.run_pending()
time.sleep(1)
if __name__ == '__main__':
main_loop()
import telebot
from config import ACCESS_TOKEN
import config
from telebot.types import Message
import requests
import schedule
import time
import sys
bot = telebot.TeleBot(ACCESS_TOKEN)
chat_id = '434574930'
# @bot.message_handler(func=lambda message: True)
def send_message():
req_home = requests.get(config.HOME_URL, auth=(config.LOGIN, config.PASS))
req_ocr = requests.get(config.OCR_URL, auth=(config.LOGIN, config.PASS))
response = ''
# если ответ сервера не 200
# пока отлаживаю, ожидаю 200
if req_home.status_code == 200:
response = config.HOME_URL + " status code: " + str(req_home.status_code) + '\n'
# если ответ сервера не 200
if req_ocr.status_code == 200:
response = response + config.OCR_URL + " status code: " + str(req_ocr.status_code) + '\n'
# если сервер вернул ошибку
if response != '':
bot.send_message(chat_id, response)
# Планировщик для бота
schedule.every(config.SCHEDULE_DELAY).seconds.do(send_message)
@bot.message_handler(commands=['start'])
def set_chat_id(message: Message):
global chat_id
chat_id = message.chat.id
bot.reply_to(message, "Start checking ...")
def main_loop():
bot.polling(True)
while 1:
schedule.run_pending()
time.sleep(1)
if __name__ == '__main__':
main_loop()
Answer the question
In order to leave comments, you need to log in
Threading will help I think
https://docs.python.org/3/library/threading.html
def send_message():
<...>
schedule.every(5).minutes.do(send_message)
while True:
schedule.run_pending()
time.sleep(1)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question