botalka/daemons/poll.py
emmatveev 03fcd8894b
All checks were successful
Deploy Dev / Build (pull_request) Successful in 7s
Deploy Dev / Push (pull_request) Successful in 8s
Deploy Dev / Deploy dev (pull_request) Successful in 11s
fix
2024-11-28 22:55:42 +03:00

49 lines
2.2 KiB
Python

import multiprocessing
import telebot
import threading
import time
from daemons import base
from utils import platform
from utils import queues
class Daemon(base.Daemon):
def __init__(self):
self.telegram_bots: dict[str, dict[str, multiprocessing.Process|None]] = {}
def execute(self):
while True:
bots = platform.platform_client.get_config('bots')
for project_name, project in bots.items():
if project_name not in self.telegram_bots:
self.telegram_bots[project_name] = {}
for bot_name, bot_info in project.items():
if bot_name not in self.telegram_bots[project_name]:
self.telegram_bots[project_name][bot_name] = None
bot = self.telegram_bots[project_name][bot_name]
if bot_info.get('poll_enabled'):
if bot is not None and bot.is_alive:
print(f'process for {project_name} {bot_name} is alive')
continue
print(f'starting process for {project_name} {bot_name}')
bot = telebot.TeleBot(bot_info['secrets']['telegram_token'])
self.start_polling(bot, bot_info['queue'], project_name, bot_name)
print(f'started process for {project_name} {bot_name}')
else:
if bot is None:
print(f'process for {project_name} {bot_name} is not alive')
continue
print(f'terminating process for {project_name} {bot_name}')
bot.terminate()
self.telegram_bots[project_name][bot_name] = None
print(f'terminated process for {project_name} {bot_name}')
time.sleep(10)
def start_polling(self, bot: telebot.TeleBot, queue: str, project_name: str, bot_name: str):
@bot.message_handler()
def do_action(message: telebot.types.Message):
queues.set_task(queue, message.json, 1)
process = multiprocessing.Process(target=bot.polling)
self.telegram_bots[project_name][bot_name] = process