refactor: modularize Telegram bot and add RabbitMQ client foundation
Build and Push Docker Images / build (push) Successful in 1m28s

- Рефакторинг Telegram бота на модульную структуру для удобства поддержки и расширения
- Создан общий RabbitMQ клиент для Flask и Telegram компонентов
- Подготовлена базовая архитектура для будущего масштабирования и новых функций

Signed-off-by: UdoChudo <stream@udochudo.ru>
This commit is contained in:
2025-06-16 09:08:46 +05:00
parent 52e31864b3
commit ccb47d527f
72 changed files with 1677 additions and 1675 deletions
@@ -0,0 +1,56 @@
from telebot import types
from app.bot.keyboards.main_menu import get_main_menu
from app.bot.utils.zabbix import get_region_groups, get_all_groups_for_region, fetch_filtered_triggers
from app.bot.utils.tg_formatter import format_trigger_message # ⬅️ добавлено
def process_region_selection(bot,chat_id, region_id):
try:
groups = get_region_groups(region_id)
if not groups:
return bot.send_message(chat_id, "Нет групп хостов для этого региона.")
markup = types.InlineKeyboardMarkup()
for group in groups:
markup.add(types.InlineKeyboardButton(text=group['name'], callback_data=f"group_{group['groupid']}"))
markup.add(types.InlineKeyboardButton(text="Все группы региона\n(Долгое выполнение)", callback_data=f"all_groups_{region_id}"))
bot.send_message(chat_id, "Выберите группу хостов:", reply_markup=markup)
except Exception as e:
bot.send_message(chat_id, f"Ошибка при получении групп: {str(e)}", reply_markup=get_main_menu())
def process_group_selection(bot, chat_id, group_id):
try:
triggers = fetch_filtered_triggers(group_id)
if not triggers:
bot.send_message(chat_id, "Нет активных событий.")
else:
send_trigger_messages(chat_id, triggers)
except Exception as e:
bot.send_message(chat_id, f"Ошибка при получении событий: {str(e)}")
def process_all_groups_request(bot, chat_id, region_id):
try:
all_triggers = []
groups = get_all_groups_for_region(region_id)
for group in groups:
try:
triggers = fetch_filtered_triggers(group['groupid'])
if triggers:
all_triggers.extend(triggers)
except Exception:
continue
if all_triggers:
send_trigger_messages(chat_id, all_triggers)
else:
bot.send_message(chat_id, "Нет активных событий.")
except Exception as e:
bot.send_message(chat_id, f"Ошибка при получении данных: {str(e)}")
def send_trigger_messages(chat_id, triggers):
for trigger in triggers:
text = format_trigger_message(trigger)
bot.send_message(chat_id, text, parse_mode="MarkdownV2")
@@ -0,0 +1,39 @@
from flask import Flask
from telebot import TeleBot, logger
from telebot.types import Message
from app.bot.constants import UserStates
from app.bot.keyboards.settings_menu import get_settings_menu
from app.bot.states import UserStateManager
from app.bot.utils.auth import auth
from app.models import Regions, Subscriptions
from app.bot.utils.regions import format_regions_list
def handle_my_subscriptions(message: Message, bot: TeleBot, app: Flask, state_manager: UserStateManager):
chat_id = message.chat.id
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
if not auth(chat_id, app):
bot.send_message(chat_id, "❌Вы не авторизованы для использования этого бота.")
logger.warning(f"Неавторизованный пользователь {chat_id} @{username}")
state_manager.set_state(chat_id, UserStates.REGISTRATION)
return
with app.app_context():
user_regions = (
Regions.query
.with_entities(Regions.region_id, Regions.region_name)
.join(Subscriptions, Subscriptions.region_id == Regions.region_id)
.filter(
Subscriptions.chat_id == chat_id,
Subscriptions.active == True,
Subscriptions.skip == False
)
.order_by(Regions.region_id.asc())
.all()
)
if not user_regions:
bot.send_message(chat_id, "ℹ️Вы не подписаны ни на один регион.", reply_markup=get_settings_menu())
else:
regions_list = format_regions_list(user_regions)
bot.send_message(chat_id, f"ℹ️Ваши активные подписки:\n{regions_list}", reply_markup=get_settings_menu())
+75
View File
@@ -0,0 +1,75 @@
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, MessageID
from app.bot.keyboards.settings_menu import get_settings_menu
from app.extensions.db import db
from app import Regions, Subscriptions
from app.bot.utils.tg_audit import log_user_event
from app.bot.constants import UserStates
def process_subscription_button(message: Message, app, bot, chat_id: int, state_manager, bot_message: MessageID):
parts = [part.strip() for part in message.text.split(',')]
if not parts or not all(part.isdigit() for part in parts):
markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton(text="Отмена", callback_data="cancel_input"))
bot.send_message(chat_id,
"❌ Неверный ввод, введите число(а) через запятую, либо нажмите отмена.",
reply_markup=markup)
def delayed_handler(msg):
process_subscription_button(msg, app, bot, chat_id, state_manager)
bot.register_next_step_handler(message, delayed_handler)
return
bot.delete_message(chat_id, bot_message)
region_ids = [int(part) for part in parts]
try:
with app.app_context():
valid_region_ids = [r.region_id for r in Regions.query.filter(Regions.active == True).all()]
subbed_regions = []
invalid_regions = []
for region_id in region_ids:
if region_id not in valid_region_ids:
invalid_regions.append(str(region_id))
continue
subscription = Subscriptions.query.filter_by(chat_id=chat_id, region_id=region_id).first()
if subscription:
if not subscription.active:
subscription.active = True
db.session.add(subscription)
subbed_regions.append(str(region_id))
else:
new_sub = Subscriptions(chat_id=chat_id, region_id=region_id, active=True)
db.session.add(new_sub)
subbed_regions.append(str(region_id))
db.session.commit()
except Exception as e:
bot.send_message(chat_id, "⚠️ Произошла ошибка при обработке запроса. Попробуйте позже.")
return
if invalid_regions:
bot.send_message(chat_id,
f"⚠️ Регион с ID {', '.join(invalid_regions)} не существует. Введите корректные номера или 'отмена'.")
# Можно не менять состояние, чтобы пользователь мог повторить ввод
# И снова ждём ввод:
bot.register_next_step_handler(message, process_subscription_button, bot, chat_id, state_manager)
return
if subbed_regions:
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
log_user_event(chat_id, app, username, f"Подписался на регионы: {', '.join(subbed_regions)}")
# Сбрасываем состояние, чтобы не продолжать ждать ввод
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
# Показываем меню
bot.send_message(chat_id, f"✅ Подписка на регионы: {', '.join(subbed_regions)} оформлена.", reply_markup=get_settings_menu())
@@ -0,0 +1,65 @@
from flask import Flask
from telebot import TeleBot, logger
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from app.bot.keyboards.settings_menu import get_settings_menu
from app.bot.utils.helpers import get_user_subscribed_regions
from app import Subscriptions
from app.bot.utils.tg_audit import log_user_event
from app.extensions.db import db
from app.bot.states import UserStateManager
from app.bot.constants import UserStates
def process_unsubscribe_button(message: Message, app: Flask, bot: TeleBot, chat_id: int, state_manager: UserStateManager):
unsubbed_regions = []
invalid_regions = []
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
parts = [part.strip() for part in message.text.split(',')]
if not parts or not all(part.isdigit() for part in parts):
markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton('Отмена', callback_data='cancel_input'))
bot.send_message(chat_id,
"Неверный ввод, введите число(а) через запятую, либо нажмите отмена.",
reply_markup=markup)
def delayed_handler(msg):
process_unsubscribe_button(msg, app, bot, chat_id, state_manager)
bot.register_next_step_handler(message, delayed_handler)
return
region_ids = [int(part) for part in parts]
try:
with app.app_context():
valid_region_ids = [int(region[0]) for region in get_user_subscribed_regions(chat_id)]
for region_id in region_ids:
if region_id not in valid_region_ids:
invalid_regions.append(str(region_id))
continue
subscription = Subscriptions.query.filter_by(chat_id=chat_id, region_id=region_id).first()
if subscription:
subscription.active = False
db.session.add(subscription)
unsubbed_regions.append(str(region_id))
db.session.commit()
except Exception as e:
bot.send_message(chat_id, "⚠ Произошла ошибка при обработке запроса. Попробуйте позже.")
logger.error(f"Unexpected Error: {e}")
return
if unsubbed_regions:
bot.send_message(chat_id, f"✅ Вы успешно отписались от регионов: {', '.join(unsubbed_regions)}")
log_user_event(chat_id, app, username, f"Отписался от регионов: {', '.join(unsubbed_regions)}")
if invalid_regions:
bot.send_message(chat_id,
f"⚠ Регионы с ID {', '.join(invalid_regions)} не найдены среди ваших подписок и не были изменены.")
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
bot.send_message(chat_id, "⚙ Вернулись в меню настроек.", reply_markup=get_settings_menu())