Improve polling

This commit is contained in:
Yeet 2024-09-10 19:08:18 +02:00
parent 5a19e2360a
commit 30cb4df6dc

View File

@ -1,4 +1,5 @@
import telebot import telebot
import logging
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
import time import time
@ -421,11 +422,12 @@ class TelegramBot:
if not self.watchlist[chat_id]: if not self.watchlist[chat_id]:
del self.watchlist[chat_id] # Remove chat_id from watchlist if empty del self.watchlist[chat_id] # Remove chat_id from watchlist if empty
def calculate_polling_interval(self, slot_time): def calculate_polling_interval(self, slot_time):
now = datetime.now().replace(tzinfo=timezone.utc) now = datetime.now().replace(tzinfo=timezone.utc)
time_until_slot = (slot_time - now).total_seconds() time_until_slot = (slot_time - now).total_seconds()
intervals = sorted(lambda x: x[0], [(k,v) for k,v in config.INTERVALS.items()]) intervals = sorted([(k,v) for k,v in config.INTERVALS.items()], key=lambda x: x[0])
last_wait = 1800 last_wait = 1800
@ -439,16 +441,24 @@ class TelegramBot:
def poll_periodically(self): def poll_periodically(self):
# Continuously poll the watchlist at dynamically adjusted intervals # Continuously poll the watchlist at dynamically adjusted intervals
logging.info(f"POLLING {self.watchlist}")
while True: while True:
self.check_watchlist() self.check_watchlist()
# Calculate the minimum polling interval based on upcoming slots # Calculate the minimum polling interval based on upcoming slots
polling_interval = 1800 # Default 30 minutes polling_interval = 1800 # Default 30 minutes
watching = 0
for chat_id, slots in self.watchlist.items(): for chat_id, slots in self.watchlist.items():
watching += len(slots)
for slot in slots: for slot in slots:
interval = self.calculate_polling_interval(slot.start) interval = self.calculate_polling_interval(slot.start)
polling_interval = min(polling_interval, interval) polling_interval = min(polling_interval, interval)
if watching == 0:
polling_interval = 15
time.sleep(polling_interval) # Wait before checking the watchlist again time.sleep(polling_interval) # Wait before checking the watchlist again
def run(self): def run(self):