refactor: modularize Telegram bot and add RabbitMQ client foundation
Build and Push Docker Images / build (push) Successful in 1m28s
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:
@@ -0,0 +1,32 @@
|
||||
from app.models.users import Users
|
||||
from config import SUPPORT_EMAIL
|
||||
|
||||
def check_registration(bot, message,app):
|
||||
chat_id = message.chat.id
|
||||
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
|
||||
|
||||
with app.app_context():
|
||||
user = Users.query.filter_by(chat_id=chat_id).first()
|
||||
|
||||
if not user:
|
||||
text = (
|
||||
f'❌ Вы не зарегистрированы.\n\n'
|
||||
f'Для продолжения регистрации необходимо отправить с корпоративного почтового адреса "РТ МИС" письмо на адрес {SUPPORT_EMAIL}\n'
|
||||
f'В теме письма указать "<b>Подтверждение регистрации в боте TeleZab</b>".\n'
|
||||
f'В теле письма указать:\n'
|
||||
f'1. <b>ФИО</b>\n'
|
||||
f'2. <b>Ваш Chat ID</b>: {chat_id}\n'
|
||||
f'3. <b>Ваше имя пользователя</b>: @{username}'
|
||||
)
|
||||
bot.send_message(chat_id, text, parse_mode="HTML", reply_markup=None)
|
||||
return None
|
||||
|
||||
return user
|
||||
|
||||
def auth(chat_id,app) -> bool:
|
||||
"""
|
||||
Проверка, есть ли chat_id в белом списке (whitelist)
|
||||
"""
|
||||
with app.app_context():
|
||||
user = Users.query.filter_by(chat_id=chat_id).first()
|
||||
return user is not None
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import telebot
|
||||
|
||||
from app.extensions.db import db
|
||||
from app.models.users import Users
|
||||
from app.models.regions import Regions
|
||||
from app.models.subscriptions import Subscriptions
|
||||
from app.models.userevents import UserEvents
|
||||
|
||||
|
||||
def is_whitelisted(chat_id: int) -> tuple[bool, str | None]:
|
||||
"""Проверяет, есть ли пользователь с заданным chat_id и не заблокирован ли он."""
|
||||
user = Users.query.filter_by(chat_id=chat_id).first()
|
||||
if user:
|
||||
if user.is_blocked:
|
||||
return False, "Ваш доступ заблокирован."
|
||||
return True, None
|
||||
return False, None
|
||||
|
||||
|
||||
def get_sorted_regions() -> list[tuple[int, str]]:
|
||||
"""Возвращает список всех активных регионов, отсортированных по region_id."""
|
||||
return (
|
||||
Regions.query
|
||||
.filter_by(active=True)
|
||||
.with_entities(Regions.region_id, Regions.region_name)
|
||||
.order_by(Regions.region_id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def get_user_subscribed_regions(chat_id: int) -> list[tuple[int, str]]:
|
||||
"""Возвращает список активных подписанных регионов пользователя."""
|
||||
regions = (
|
||||
Regions.query
|
||||
.join(Subscriptions, Subscriptions.region_id == Regions.region_id)
|
||||
.filter(
|
||||
Subscriptions.chat_id == chat_id,
|
||||
Subscriptions.active.is_(True),
|
||||
Subscriptions.skip.is_(False),
|
||||
Regions.active.is_(True)
|
||||
)
|
||||
.with_entities(Regions.region_id, Regions.region_name)
|
||||
.order_by(Regions.region_id.asc())
|
||||
.all()
|
||||
)
|
||||
return regions
|
||||
|
||||
|
||||
def format_regions_list(regions: list[tuple[int, str]]) -> str:
|
||||
"""Форматирует список регионов для отображения."""
|
||||
return '\n'.join(f"{region_id} - {region_name}" for region_id, region_name in regions)
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# app/bot/utils/regions.py
|
||||
from typing import List, Dict
|
||||
|
||||
from app.models import Regions
|
||||
|
||||
def get_sorted_regions():
|
||||
"""
|
||||
Получить отсортированный список регионов (из базы, например).
|
||||
"""
|
||||
# Здесь предполагается, что вызывающий код находится в контексте Flask (app.app_context())
|
||||
return Regions.query.filter(Regions.active == True).order_by(Regions.region_id).all()
|
||||
|
||||
def get_sorted_regions_plain() -> List[Dict[str, str]]:
|
||||
regions = Regions.query.filter(Regions.active == True).order_by(Regions.region_id).all()
|
||||
return [{"id": r.region_id, "name": r.region_name} for r in regions]
|
||||
|
||||
def format_regions_list(regions):
|
||||
"""
|
||||
Форматировать список регионов в удобочитаемый текст
|
||||
"""
|
||||
lines = []
|
||||
for region in regions:
|
||||
lines.append(f"✅ {region.region_id}: {region.region_name}")
|
||||
return "\n".join(lines)
|
||||
|
||||
def format_regions_list_marked(regions, subscribed_region_ids):
|
||||
lines = []
|
||||
for region in regions:
|
||||
mark = "✅" if region.region_id in subscribed_region_ids else "❌"
|
||||
lines.append(f"{mark} {region.region_id}: {region.region_name}")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,30 @@
|
||||
# app/bot/utils/logging.py
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from app.extensions.db import db
|
||||
from app.models import UserEvents
|
||||
from telebot import logger
|
||||
|
||||
def log_user_event(chat_id: int, app: Flask, username: str, action: str) -> None:
|
||||
"""
|
||||
Логирует действие пользователя в базу с использованием ORM.
|
||||
"""
|
||||
try:
|
||||
with app.app_context():
|
||||
timestamp = datetime.now(timezone.utc)
|
||||
|
||||
event = UserEvents(
|
||||
chat_id=chat_id,
|
||||
telegram_id=username,
|
||||
action=action,
|
||||
timestamp=timestamp
|
||||
)
|
||||
db.session.add(event)
|
||||
db.session.commit()
|
||||
|
||||
formatted_time = timestamp.strftime('%Y-%m-%d %H:%M:%S')
|
||||
logger.info(f"User event logged: {chat_id} (@{username}) - {action} at {formatted_time}.")
|
||||
except Exception as e:
|
||||
logger.error(f"Error logging user event: {e}")
|
||||
@@ -0,0 +1,20 @@
|
||||
def escape_telegram_chars(text):
|
||||
"""
|
||||
Экранирует запрещённые символы для Telegram API:
|
||||
< -> <
|
||||
> -> >
|
||||
& -> &
|
||||
Также проверяет на наличие запрещённых HTML-тегов и другие проблемы с форматированием.
|
||||
"""
|
||||
replacements = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"', # Для кавычек
|
||||
}
|
||||
|
||||
# Применяем замены
|
||||
for char, replacement in replacements.items():
|
||||
text = text.replace(char, replacement)
|
||||
|
||||
return text
|
||||
@@ -0,0 +1,35 @@
|
||||
from datetime import datetime
|
||||
from pytz import timezone
|
||||
from app.bot.utils.tg_escape_chars import escape_telegram_chars
|
||||
|
||||
def format_trigger_message(trigger, zabbix_url: str) -> str:
|
||||
tz = timezone('Europe/Moscow')
|
||||
priority_map = {'4': 'HIGH', '5': 'DISASTER'}
|
||||
|
||||
event_time_epoch = int(trigger.get('lastEvent', {}).get('clock', trigger.get('lastchange', 0)))
|
||||
event_time = datetime.fromtimestamp(event_time_epoch, tz=tz)
|
||||
event_time_formatted = event_time.strftime('%Y-%m-%d %H:%M:%S Мск')
|
||||
|
||||
host = trigger.get('hosts', [{}])[0].get('name', 'Неизвестно')
|
||||
priority = priority_map.get(str(trigger.get('priority')), 'Неизвестно')
|
||||
description = escape_telegram_chars(trigger.get('description', '')).replace("{HOST.NAME}", host)
|
||||
|
||||
items = trigger.get('items', [])
|
||||
item_ids = [item['itemid'] for item in items]
|
||||
|
||||
for i, item in enumerate(items):
|
||||
placeholder = f"{{ITEM.LASTVALUE{i + 1}}}"
|
||||
if placeholder in description:
|
||||
description = description.replace(placeholder, item.get('lastvalue', '?'))
|
||||
|
||||
batchgraph_link = f"{zabbix_url}/history.php?action=batchgraph&"
|
||||
batchgraph_link += "&".join([f"itemids[{item_id}]={item_id}" for item_id in item_ids])
|
||||
batchgraph_link += "&graphtype=0"
|
||||
|
||||
return (
|
||||
f"<b>Host</b>: {host}\n"
|
||||
f"<b>Описание</b>: {description}\n"
|
||||
f"<b>Критичность</b>: {priority}\n"
|
||||
f"<b>Время создания</b>: {event_time_formatted}\n"
|
||||
f'<b>URL</b>: <a href="{batchgraph_link}">Ссылка на график</a>'
|
||||
)
|
||||
@@ -0,0 +1,119 @@
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pytz import timezone
|
||||
from pyzabbix import ZabbixAPI, ZabbixAPIException
|
||||
from telebot import logger
|
||||
|
||||
from config import ZABBIX_URL, ZABBIX_API_TOKEN, ZABBIX_VERIFY_SSL, ZABBIX_TZ
|
||||
from app.bot.utils.tg_escape_chars import escape_telegram_chars
|
||||
TZ = timezone(ZABBIX_TZ)
|
||||
verify_ssl = ZABBIX_VERIFY_SSL
|
||||
|
||||
def get_region_groups(region_id: str):
|
||||
"""
|
||||
Получает список групп, имя которых содержит регион region_id, исключая 'test'.
|
||||
"""
|
||||
try:
|
||||
zapi = ZabbixAPI(ZABBIX_URL)
|
||||
zapi.login(api_token=ZABBIX_API_TOKEN)
|
||||
zapi.session.verify = verify_ssl
|
||||
|
||||
host_groups = zapi.hostgroup.get(output=["groupid", "name"], search={"name": region_id})
|
||||
filtered_groups = [group for group in host_groups if 'test' not in group['name'].lower()]
|
||||
return filtered_groups
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting region groups for '{region_id}': {e}")
|
||||
return []
|
||||
|
||||
def get_all_groups_for_region(region_id: str):
|
||||
"""
|
||||
Аналогично get_region_groups, получение всех групп по региону.
|
||||
"""
|
||||
return get_region_groups(region_id)
|
||||
|
||||
def fetch_filtered_triggers(group_id):
|
||||
"""
|
||||
Получение и фильтрация триггеров с severities 4 и 5,
|
||||
формирование HTML сообщений для отправки в Telegram.
|
||||
"""
|
||||
try:
|
||||
zapi = ZabbixAPI(ZABBIX_URL)
|
||||
zapi.login(api_token=ZABBIX_API_TOKEN)
|
||||
zapi.session.verify = verify_ssl
|
||||
|
||||
problems = zapi.problem.get(
|
||||
severities=[4, 5],
|
||||
suppressed=0,
|
||||
acknowledged=0,
|
||||
groupids=group_id
|
||||
)
|
||||
trigger_ids = [problem["objectid"] for problem in problems]
|
||||
|
||||
if not trigger_ids:
|
||||
return []
|
||||
|
||||
triggers = zapi.trigger.get(
|
||||
triggerids=trigger_ids,
|
||||
output=["triggerid", "description", "priority"],
|
||||
selectHosts=["hostid", "name"],
|
||||
monitored=1,
|
||||
expandDescription=1,
|
||||
expandComment=1,
|
||||
selectItems=["itemid", "lastvalue"],
|
||||
selectLastEvent=["clock", "eventid"]
|
||||
)
|
||||
|
||||
events = zapi.event.get(
|
||||
severities=[4, 5],
|
||||
objectids=trigger_ids,
|
||||
select_alerts="mediatype"
|
||||
)
|
||||
|
||||
pnet_mediatypes = {"Pnet integration JS 2025", "Pnet integration JS 2024", "Pnet integration new2"}
|
||||
|
||||
pnet_triggers = []
|
||||
event_dict = {event["objectid"]: event for event in events}
|
||||
|
||||
for trigger in triggers:
|
||||
event = event_dict.get(trigger["triggerid"])
|
||||
if event:
|
||||
for alert in event["alerts"]:
|
||||
if alert["mediatypes"] and alert["mediatypes"][0]["name"] in pnet_mediatypes:
|
||||
pnet_triggers.append(trigger)
|
||||
break
|
||||
|
||||
triggers_sorted = sorted(pnet_triggers, key=lambda t: int(t['lastEvent']['clock']))
|
||||
|
||||
|
||||
priority_map = {'4': 'HIGH', '5': 'DISASTER'}
|
||||
trigger_messages = []
|
||||
|
||||
for trigger in triggers_sorted:
|
||||
event_time_epoch = int(trigger['lastEvent']['clock'])
|
||||
event_time = datetime.fromtimestamp(event_time_epoch, tz=TZ)
|
||||
description = escape_telegram_chars(trigger['description'])
|
||||
host = trigger['hosts'][0]['name']
|
||||
priority = priority_map.get(trigger['priority'], 'Неизвестно')
|
||||
item_ids = [item['itemid'] for item in trigger['items']]
|
||||
batchgraph_link = f"{ZABBIX_URL}/history.php?action=batchgraph&"
|
||||
batchgraph_link += "&".join([f"itemids[{item_id}]={item_id}" for item_id in item_ids])
|
||||
batchgraph_link += "&graphtype=0"
|
||||
description = description.replace("{HOST.NAME}", host)
|
||||
for i, item in enumerate(trigger['items']):
|
||||
lastvalue_placeholder = f"{{ITEM.LASTVALUE{i + 1}}}"
|
||||
if lastvalue_placeholder in description:
|
||||
description = description.replace(lastvalue_placeholder, item['lastvalue'])
|
||||
event_time_formatted = event_time.strftime('%Y-%m-%d %H:%M:%S Мск')
|
||||
message = (f"<b>Host</b>: {host}\n"
|
||||
f"<b>Описание</b>: {description}\n"
|
||||
f"<b>Критичность</b>: {priority}\n"
|
||||
f"<b>Время создания</b>: {event_time_formatted}\n"
|
||||
f'<b>URL</b>: <a href="{batchgraph_link}">Ссылка на график</a>')
|
||||
trigger_messages.append(message)
|
||||
|
||||
logger.info(f"Fetched {len(triggers_sorted)} triggers for group {group_id}.")
|
||||
return trigger_messages
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error fetching triggers for group {group_id}: {e}")
|
||||
return []
|
||||
Reference in New Issue
Block a user