Compare commits
7
Commits
295c1f68e0
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
085be262b0 | ||
|
|
9fd69cc3a6 | ||
|
|
161ad3eaa3 | ||
|
|
ab33329e31 | ||
|
|
3d5a237d4d | ||
|
|
2b65d11622 | ||
|
|
a1c36de342 |
@@ -1,15 +1,16 @@
|
|||||||
# app/bot/handlers/start.py
|
# app/bot/handlers/start.py
|
||||||
from telebot.types import Message
|
|
||||||
from telebot import logger
|
from telebot import logger
|
||||||
from app.bot.keyboards.main_menu import get_main_menu
|
from telebot.types import Message
|
||||||
|
|
||||||
from app.bot.constants import UserStates
|
from app.bot.constants import UserStates
|
||||||
|
from app.bot.keyboards.main_menu import get_main_menu
|
||||||
from app.bot.states import UserStateManager
|
from app.bot.states import UserStateManager
|
||||||
from app.bot.utils.auth import check_registration
|
from app.bot.utils.auth import check_registration
|
||||||
|
|
||||||
|
|
||||||
def register_handlers(bot,app, state_manager: UserStateManager):
|
def register_handlers(bot,app, state_manager: UserStateManager):
|
||||||
@bot.message_handler(commands=['start'])
|
@bot.message_handler(commands=['start'])
|
||||||
@bot.message_handler(func=lambda msg: msg.text == "Продолжить" and state_manager.get_state(msg.chat.id) == UserStates.REGISTRATION)
|
@bot.message_handler(func=lambda msg: msg.text == "Продолжить")
|
||||||
def start_handler(message: Message):
|
def start_handler(message: Message):
|
||||||
chat_id = message.chat.id
|
chat_id = message.chat.id
|
||||||
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
|
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, C
|
|||||||
|
|
||||||
from app import Subscriptions
|
from app import Subscriptions
|
||||||
from app.bot.constants import UserStates
|
from app.bot.constants import UserStates
|
||||||
|
from app.bot.keyboards.settings_menu import get_settings_menu
|
||||||
from app.bot.processors.subscribe_processor import process_subscription_button, process_subscribe_all_regions
|
from app.bot.processors.subscribe_processor import process_subscription_button, process_subscribe_all_regions
|
||||||
from app.bot.states import UserStateManager
|
from app.bot.states import UserStateManager
|
||||||
from app.bot.utils.auth import auth
|
from app.bot.utils.auth import auth
|
||||||
@@ -28,10 +29,16 @@ def register_handlers(bot: TeleBot, app, state_manager: UserStateManager):
|
|||||||
# Получаем регионы
|
# Получаем регионы
|
||||||
regions = get_sorted_regions()
|
regions = get_sorted_regions()
|
||||||
|
|
||||||
|
if not regions:
|
||||||
|
bot.send_message(chat_id, "ℹ️ У вас нет доступных для подписки регионов.",reply_markup=get_settings_menu())
|
||||||
|
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
|
||||||
|
return
|
||||||
|
|
||||||
# Получаем список подписанных регионов пользователя
|
# Получаем список подписанных регионов пользователя
|
||||||
subscribed = {s.region_id for s in Subscriptions.query.filter_by(chat_id=chat_id, active=True).all()}
|
subscribed = {s.region_id for s in Subscriptions.query.filter_by(chat_id=chat_id, active=True).all()}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Формируем строку с пометками
|
# Формируем строку с пометками
|
||||||
regions_text = format_regions_list_marked(regions, subscribed)
|
regions_text = format_regions_list_marked(regions, subscribed)
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from telebot import logger
|
||||||
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
|
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
|
||||||
|
|
||||||
from app.bot.keyboards.groups import create_groups_keyboard
|
from app.bot.keyboards.groups import create_groups_keyboard
|
||||||
@@ -12,10 +13,14 @@ from app.bot.utils.zabbix_alt import (
|
|||||||
def process_region_selection(bot, chat_id, region_id):
|
def process_region_selection(bot, chat_id, region_id):
|
||||||
try:
|
try:
|
||||||
groups = get_region_groups(region_id)
|
groups = get_region_groups(region_id)
|
||||||
|
if groups is None:
|
||||||
|
return bot.send_message(chat_id, "❌ Сервер Zabbix временно недоступен. Попробуйте позже.", reply_markup=get_main_menu())
|
||||||
if not groups:
|
if not groups:
|
||||||
return bot.send_message(chat_id, "Нет групп хостов для этого региона.")
|
return bot.send_message(chat_id, "Нет групп хостов для этого региона.", reply_markup=get_main_menu())
|
||||||
|
|
||||||
markup = create_groups_keyboard(groups, region_id)
|
markup = create_groups_keyboard(groups, region_id)
|
||||||
bot.send_message(chat_id, "Выберите группу хостов:", reply_markup=markup)
|
bot.send_message(chat_id, "Выберите группу хостов:", reply_markup=markup)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
bot.send_message(chat_id, f"Ошибка при получении групп: {str(e)}", reply_markup=get_main_menu())
|
bot.send_message(chat_id, f"Ошибка при получении групп: {str(e)}", reply_markup=get_main_menu())
|
||||||
|
|
||||||
@@ -23,40 +28,61 @@ def process_region_selection(bot, chat_id, region_id):
|
|||||||
def process_group_selection(bot, chat_id, group_id):
|
def process_group_selection(bot, chat_id, group_id):
|
||||||
try:
|
try:
|
||||||
triggers = fetch_triggers_data(group_id)
|
triggers = fetch_triggers_data(group_id)
|
||||||
|
if triggers is None:
|
||||||
|
return bot.send_message(chat_id, "❌ Сервер Zabbix временно недоступен. Попробуйте позже.")
|
||||||
|
|
||||||
if not triggers:
|
if not triggers:
|
||||||
bot.send_message(chat_id, "Нет активных событий.")
|
return bot.send_message(chat_id, "Нет активных событий.")
|
||||||
return
|
|
||||||
|
|
||||||
for trigger in triggers:
|
for trigger in triggers:
|
||||||
text, url = format_trigger_for_tg(trigger)
|
try:
|
||||||
markup = InlineKeyboardMarkup()
|
text, url = format_trigger_for_tg(trigger)
|
||||||
markup.add(InlineKeyboardButton(text="Открыть график", url=url))
|
markup = InlineKeyboardMarkup()
|
||||||
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML")
|
markup.add(InlineKeyboardButton(text="Открыть график", url=url))
|
||||||
|
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[Bot] Ошибка при отправке сообщения о триггере: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
bot.send_message(chat_id, f"Ошибка при получении событий: {str(e)}")
|
bot.send_message(chat_id, f"Ошибка при получении событий: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def process_all_groups_request(bot, chat_id, region_id):
|
def process_all_groups_request(bot, chat_id, region_id):
|
||||||
try:
|
try:
|
||||||
all_triggers = []
|
all_triggers = []
|
||||||
groups = get_all_groups_for_region(region_id)
|
groups = get_all_groups_for_region(region_id)
|
||||||
|
zabbix_error = False
|
||||||
|
|
||||||
for group in groups:
|
for group in groups:
|
||||||
try:
|
try:
|
||||||
triggers = fetch_triggers_data(group['groupid'])
|
triggers = fetch_triggers_data(group['groupid'])
|
||||||
|
if triggers is None:
|
||||||
|
zabbix_error = True
|
||||||
|
continue
|
||||||
if triggers:
|
if triggers:
|
||||||
all_triggers.extend(triggers)
|
all_triggers.extend(triggers)
|
||||||
except Exception:
|
except Exception as e:
|
||||||
|
logger.error(f"[Bot] Ошибка при обработке группы {group['name']}: {e}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
if zabbix_error and not all_triggers:
|
||||||
|
return bot.send_message(chat_id, "❌ Сервер Zabbix временно недоступен. Попробуйте позже.")
|
||||||
|
|
||||||
if not all_triggers:
|
if not all_triggers:
|
||||||
bot.send_message(chat_id, "Нет активных событий.")
|
return bot.send_message(chat_id, "Нет активных событий.")
|
||||||
return
|
|
||||||
|
|
||||||
for trigger in all_triggers:
|
for trigger in all_triggers:
|
||||||
text, url = format_trigger_for_tg(trigger)
|
try:
|
||||||
markup = InlineKeyboardMarkup()
|
text, url = format_trigger_for_tg(trigger)
|
||||||
markup.add(InlineKeyboardButton(text="Открыть график", url=url))
|
markup = InlineKeyboardMarkup()
|
||||||
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML")
|
markup.add(InlineKeyboardButton(text="Открыть график", url=url))
|
||||||
|
bot.send_message(chat_id, text, reply_markup=markup, parse_mode="HTML")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"[Bot] Ошибка при отправке события: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
bot.send_message(chat_id, f"Ошибка при получении данных: {str(e)}")
|
bot.send_message(chat_id, f"Ошибка при получении данных: {str(e)}")
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
# composer.py
|
# composer.py
|
||||||
|
|
||||||
import time
|
from datetime import datetime
|
||||||
from typing import Optional, Tuple
|
from typing import Optional, Tuple
|
||||||
from app.bot.utils.tg_escape_chars import escape_telegram_chars # или твоя функция, если кастомная
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from app.bot.utils.tg_escape_chars import escape_telegram_chars # или твоя функция, если кастомная
|
||||||
|
from config import ZABBIX_TZ
|
||||||
|
|
||||||
|
|
||||||
def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
||||||
"""
|
"""
|
||||||
@@ -19,6 +23,12 @@ def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
|||||||
'High': '⚠️',
|
'High': '⚠️',
|
||||||
'Disaster': '⛔️'
|
'Disaster': '⛔️'
|
||||||
}
|
}
|
||||||
|
convert_time_format = {
|
||||||
|
"h": "ч",
|
||||||
|
"m": "м",
|
||||||
|
"s": "с"
|
||||||
|
}
|
||||||
|
|
||||||
priority = priority_map.get(data.get('severity', ''), '')
|
priority = priority_map.get(data.get('severity', ''), '')
|
||||||
msg = escape_telegram_chars(data.get('msg', ''))
|
msg = escape_telegram_chars(data.get('msg', ''))
|
||||||
host = escape_telegram_chars(data.get('host', ''))
|
host = escape_telegram_chars(data.get('host', ''))
|
||||||
@@ -26,7 +36,8 @@ def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
|||||||
severity = escape_telegram_chars(data.get('severity', ''))
|
severity = escape_telegram_chars(data.get('severity', ''))
|
||||||
status = data.get('status', '').upper()
|
status = data.get('status', '').upper()
|
||||||
timestamp = int(data.get('date_reception', 0))
|
timestamp = int(data.get('date_reception', 0))
|
||||||
time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
|
dt = datetime.fromtimestamp(timestamp, tz=ZoneInfo(ZABBIX_TZ))
|
||||||
|
time_str = dt.strftime('%d.%m.%Y %H:%M:%S')
|
||||||
|
|
||||||
if status == "PROBLEM":
|
if status == "PROBLEM":
|
||||||
message = (
|
message = (
|
||||||
@@ -36,16 +47,36 @@ def compose_telegram_message(data: dict) -> Tuple[str, Optional[str]]:
|
|||||||
f"<b>Время возникновения</b>: {time_str} Мск\n"
|
f"<b>Время возникновения</b>: {time_str} Мск\n"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
|
event_duration = data.get('event_duration', '')
|
||||||
|
duration = ' '.join(
|
||||||
|
f"{part[:-1]}{convert_time_format.get(part[-1], part[-1])}"
|
||||||
|
for part in event_duration.split()
|
||||||
|
)
|
||||||
|
|
||||||
|
# Переформатируем event_date из '2025.06.27 16:46:04' в '27.06.2025 16:46:04'
|
||||||
|
event_date_str = data.get('event_date', '')
|
||||||
|
if event_date_str:
|
||||||
|
try:
|
||||||
|
dt_start = datetime.strptime(event_date_str, "%Y.%m.%d %H:%M:%S")
|
||||||
|
# не меняем timezone, просто меняем формат
|
||||||
|
time_start = dt_start.strftime('%d.%m.%Y %H:%M:%S')
|
||||||
|
except Exception:
|
||||||
|
time_start = event_date_str # fallback — оставляем как есть
|
||||||
|
else:
|
||||||
|
time_start = ''
|
||||||
|
|
||||||
message = (
|
message = (
|
||||||
f"✅ {host} ({ip})\n"
|
f"✅ {host} ({ip})\n"
|
||||||
f"<b>Описание</b>: {msg}\n"
|
f"<b>Описание</b>: {msg}\n"
|
||||||
f"<b>Критичность</b>: {severity}\n"
|
f"<b>Критичность</b>: {severity}\n"
|
||||||
f"<b>Проблема устранена!</b>\n"
|
f"<b>Проблема устранена!</b>\n"
|
||||||
|
f"<b>Время начала</b>: {time_start} Мск\n"
|
||||||
f"<b>Время устранения</b>: {time_str} Мск\n"
|
f"<b>Время устранения</b>: {time_str} Мск\n"
|
||||||
|
f"<b>Длительность проблемы</b>: {duration}\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
link = data.get("link")
|
link = data.get("link")
|
||||||
return message, link
|
return message, link
|
||||||
|
|
||||||
except KeyError as e:
|
except KeyError as e:
|
||||||
raise ValueError(f"Missing key in data: {e}")
|
raise ValueError(f"Missing key in data: {e}")
|
||||||
@@ -12,6 +12,6 @@ def create_link_button(link: Optional[str]) -> Optional[InlineKeyboardMarkup]:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
markup = InlineKeyboardMarkup()
|
markup = InlineKeyboardMarkup()
|
||||||
button = InlineKeyboardButton(text="График", url=link)
|
button = InlineKeyboardButton(text="Открыть график", url=link)
|
||||||
markup.add(button)
|
markup.add(button)
|
||||||
return markup
|
return markup
|
||||||
|
|||||||
+10
-11
@@ -9,7 +9,9 @@ from config import ZABBIX_URL, ZABBIX_API_TOKEN, ZABBIX_VERIFY_SSL
|
|||||||
|
|
||||||
def get_region_groups(region_id: str):
|
def get_region_groups(region_id: str):
|
||||||
"""
|
"""
|
||||||
Получает список групп, имя которых содержит регион region_id, исключая 'test' и группы, не соответствующие шаблону 'имя_число'.
|
Получает список групп, имя которых содержит регион region_id,
|
||||||
|
исключая 'test' и группы, не соответствующие шаблону 'имя_число'.
|
||||||
|
Возвращает None при ошибке подключения.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
zapi = ZabbixAPI(ZABBIX_URL)
|
zapi = ZabbixAPI(ZABBIX_URL)
|
||||||
@@ -17,8 +19,7 @@ def get_region_groups(region_id: str):
|
|||||||
zapi.session.verify = ZABBIX_VERIFY_SSL
|
zapi.session.verify = ZABBIX_VERIFY_SSL
|
||||||
|
|
||||||
host_groups = zapi.hostgroup.get(output=["groupid", "name"], search={"name": region_id})
|
host_groups = zapi.hostgroup.get(output=["groupid", "name"], search={"name": region_id})
|
||||||
|
pattern = re.compile(r'.+_\d+$')
|
||||||
pattern = re.compile(r'.+_\d+$') # строка с нижним подчёркиванием перед числом в конце
|
|
||||||
|
|
||||||
filtered_groups = [
|
filtered_groups = [
|
||||||
group for group in host_groups
|
group for group in host_groups
|
||||||
@@ -28,7 +29,7 @@ def get_region_groups(region_id: str):
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"[Zabbix] Error getting region groups for '{region_id}': {e}")
|
logger.error(f"[Zabbix] Error getting region groups for '{region_id}': {e}")
|
||||||
return []
|
return None # ← это важно
|
||||||
|
|
||||||
def get_all_groups_for_region(region_id: str):
|
def get_all_groups_for_region(region_id: str):
|
||||||
"""
|
"""
|
||||||
@@ -39,16 +40,15 @@ def get_all_groups_for_region(region_id: str):
|
|||||||
|
|
||||||
def fetch_triggers_data(group_id):
|
def fetch_triggers_data(group_id):
|
||||||
"""
|
"""
|
||||||
Возвращает список триггеров с необходимыми данными,
|
Возвращает список триггеров или None при ошибке подключения к Zabbix.
|
||||||
без форматирования сообщений.
|
|
||||||
"""
|
"""
|
||||||
pnet_mediatypes = {"Pnet integration JS 2025", "Pnet integration JS 2024", "Pnet integration new2"}
|
pnet_mediatypes = {"Pnet integration JS 2025", "Pnet integration JS 2024", "Pnet integration new2"}
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
try:
|
try:
|
||||||
zapi = ZabbixAPI(ZABBIX_URL)
|
zapi = ZabbixAPI(ZABBIX_URL)
|
||||||
zapi.login(api_token=ZABBIX_API_TOKEN)
|
zapi.login(api_token=ZABBIX_API_TOKEN)
|
||||||
|
zapi.session.verify = ZABBIX_VERIFY_SSL
|
||||||
|
|
||||||
# Получаем проблемы с высокой и критической важностью
|
|
||||||
problems = zapi.problem.get(
|
problems = zapi.problem.get(
|
||||||
severities=[4, 5],
|
severities=[4, 5],
|
||||||
suppressed=0,
|
suppressed=0,
|
||||||
@@ -56,7 +56,6 @@ def fetch_triggers_data(group_id):
|
|||||||
groupids=group_id
|
groupids=group_id
|
||||||
)
|
)
|
||||||
trigger_ids = [problem["objectid"] for problem in problems]
|
trigger_ids = [problem["objectid"] for problem in problems]
|
||||||
|
|
||||||
if not trigger_ids:
|
if not trigger_ids:
|
||||||
logger.info(f"No triggers found for group {group_id}")
|
logger.info(f"No triggers found for group {group_id}")
|
||||||
return []
|
return []
|
||||||
@@ -90,14 +89,14 @@ def fetch_triggers_data(group_id):
|
|||||||
break
|
break
|
||||||
|
|
||||||
triggers_sorted = sorted(pnet_triggers, key=lambda t: int(t['lastEvent']['clock']))
|
triggers_sorted = sorted(pnet_triggers, key=lambda t: int(t['lastEvent']['clock']))
|
||||||
logger.debug(f"Found {len(pnet_triggers)} pnet triggers for group {group_id}")
|
|
||||||
end_time = time.time()
|
end_time = time.time()
|
||||||
logger.info(f"[Zabbix] Fetched {len(triggers_sorted)} triggers for group {group_id} in {end_time - start_time:.2f} seconds.")
|
logger.info(f"[Zabbix] Fetched {len(triggers_sorted)} triggers for group {group_id} in {end_time - start_time:.2f} seconds.")
|
||||||
return triggers_sorted
|
return triggers_sorted
|
||||||
|
|
||||||
except ZabbixAPIException as e:
|
except ZabbixAPIException as e:
|
||||||
logger.error(f"[Zabbix] Zabbix API error for group {group_id}: {e}")
|
logger.error(f"[Zabbix] Zabbix API error for group {group_id}: {e}")
|
||||||
return []
|
return None # ← отличие
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"[Zabbix] Unexpected error fetching triggers for group {group_id}: {e}")
|
logger.error(f"[Zabbix] Unexpected error fetching triggers for group {group_id}: {e}")
|
||||||
return []
|
return None # ← отличие
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -10,5 +10,7 @@ Werkzeug~=3.1.3
|
|||||||
aio-pika~=9.5.5
|
aio-pika~=9.5.5
|
||||||
pika~=1.3.2
|
pika~=1.3.2
|
||||||
pytz~=2025.2
|
pytz~=2025.2
|
||||||
|
tzdata~=2025.2
|
||||||
|
concurrent-log-handler~=0.9.26
|
||||||
requests~=2.32.3
|
requests~=2.32.3
|
||||||
gunicorn~=23.0.0
|
gunicorn~=23.0.0
|
||||||
|
|||||||
Reference in New Issue
Block a user