add
All checks were successful
Deploy Dev / Build (pull_request) Successful in 24s
Deploy Dev / Push (pull_request) Successful in 21s
Deploy Dev / Deploy dev (pull_request) Successful in 33s
Deploy Prod / Build (pull_request) Successful in 11s
Deploy Prod / Push (pull_request) Successful in 19s
Deploy Prod / Deploy prod (pull_request) Successful in 22s

This commit is contained in:
Administrator 2024-12-21 19:27:00 +03:00
parent 7ed7afbef4
commit 5a00dad803

View File

@ -1,5 +1,5 @@
import telebot
import threading
import multiprocessing
import time
from daemons import base
@ -10,45 +10,37 @@ from utils import queues
class Daemon(base.Daemon):
def __init__(self):
super().__init__()
self.telegram_bots: dict[str, dict[str, telebot.TeleBot|None]] = {}
self.threads: dict[str, dict[str, threading.Thread|None]] = {}
self.processes: 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] = {}
self.threads[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
self.threads[project_name][bot_name] = None
bot = self.telegram_bots[project_name][bot_name]
key = f'{project_name}_{bot_name}'
proc = self.processes.get(key)
if bot_info.get('poll_enabled'):
if bot is not None and self.threads[project_name][bot_name].is_alive():
if proc and proc.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'])
thread = self.start_polling(bot, bot_info['queue'])
self.telegram_bots[project_name][bot_name] = bot
self.threads[project_name][bot_name] = thread
process = multiprocessing.Process(target=self.start_polling, args=(bot_info['secrets']['telegram_token'], bot_info['queue']))
process.start()
self.processes[key] = process
print(f'started process for {project_name} {bot_name}')
else:
if bot is None:
if proc is None:
print(f'process for {project_name} {bot_name} is not alive')
continue
print(f'terminating process for {project_name} {bot_name}')
bot.stop_bot()
self.telegram_bots[project_name][bot_name] = None
proc.terminate()
self.processes[key] = None
print(f'terminated process for {project_name} {bot_name}')
time.sleep(10)
def start_polling(self, bot: telebot.TeleBot, queue: str) -> threading.Thread:
def start_polling(self, token: str, queue: str):
bot = telebot.TeleBot(token)
@bot.message_handler(content_types=['audio', 'photo', 'voice', 'video', 'document', 'animation', 'text', 'location', 'contact', 'sticker', 'video_note'])
def do_action(message: telebot.types.Message):
queues.set_task(self.stub, queue, message.json, 1)
thread = threading.Thread(target=bot.polling)
thread.start()
return thread
bot.polling()