import re import time from datetime import datetime import telebot from pytz import timezone from pyzabbix import ZabbixAPI import backend_bot from config import ZABBIX_URL, ZABBIX_API_TOKEN from utilities.telegram_utilities import show_main_menu def get_triggers_for_group(chat_id, group_id): triggers = get_zabbix_triggers(group_id) # Получаем все активные события без периода if not triggers: backend_bot.bot.send_message(chat_id, f"Нет активных событий.") show_main_menu(chat_id) else: send_triggers_to_user(triggers, chat_id) def get_triggers_for_all_groups(chat_id, region_id): try: zapi = ZabbixAPI(ZABBIX_URL) zapi.login(api_token=ZABBIX_API_TOKEN) 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()] all_triggers = [] for group in filtered_groups: triggers = get_zabbix_triggers(group['groupid']) if triggers: all_triggers.extend(triggers) if all_triggers: send_triggers_to_user(all_triggers, chat_id) else: backend_bot.bot.send_message(chat_id, f"Нет активных событий.") show_main_menu(chat_id) except Exception as e: backend_bot.bot.send_message(chat_id, f"Ошибка при получении событий.\n{str(e)}") show_main_menu(chat_id) def send_triggers_to_user(triggers, chat_id): for trigger in triggers: backend_bot.bot.send_message(chat_id, trigger, parse_mode="html") time.sleep(1 / 5) def extract_host_from_name(name): match = re.match(r"^(.*?)\s*->", name) return match.group(1) if match else "Неизвестный хост" def get_zabbix_triggers(group_id): try: zapi = ZabbixAPI(ZABBIX_URL) zapi.login(api_token=ZABBIX_API_TOKEN) telebot.logger.info(f"Fetching active hosts for group {group_id}") # Получаем список активных хостов в группе active_hosts = zapi.host.get( groupids=group_id, output=["hostid", "name"], filter={"status": "0"} # Только включенные хосты ) if not active_hosts: telebot.logger.info(f"No active hosts found for group {group_id}") return [] host_ids = [host["hostid"] for host in active_hosts] telebot.logger.info(f"Found {len(host_ids)} active hosts in group {group_id}") # Получение активных проблем для этих хостов problems = zapi.problem.get( output=["eventid", "name", "severity", "clock"], hostids=host_ids, suppressed=0, acknowledged=0, filter={"severity": ["4", "5"]}, # Только высокий и аварийный уровень sortorder="ASC" ) if not problems: telebot.logger.info(f"No active problems found for group {group_id}") return [] # Получение IP-адресов хостов host_interfaces = zapi.hostinterface.get( hostids=host_ids, output=["hostid", "ip"] ) host_ip_map = {iface["hostid"]: iface["ip"] for iface in host_interfaces} # print(host_ip_map) moscow_tz = timezone('Europe/Moscow') severity_map = {'4': 'HIGH', '5': 'DISASTER'} priority_map = {'4': '⚠️', '5': '⛔️'} problem_messages = [] for problem in problems: event_time_epoch = int(problem['clock']) event_time = datetime.fromtimestamp(event_time_epoch, tz=moscow_tz) event_time_formatted = event_time.strftime('%Y-%m-%d %H:%M:%S Мск') severity = severity_map.get(problem['severity'], 'Неизвестно') priority = priority_map.get(problem['severity'], '') description = problem.get('name', 'Нет описания') # Получаем хост из описания (или по-другому, если известно) host = extract_host_from_name(description) host_ip = host_ip_map.get(problem.get("hostid"), "Неизвестный IP") message = (f"{priority} Host: {host}\n" f"IP: {host_ip}\n" f"Описание: {description}\n" f"Критичность: {severity}\n" f"Время создания: {event_time_formatted}") problem_messages.append(message) return problem_messages except Exception as e: telebot.logger.error(f"Error fetching problems for group {group_id}: {e}") return None