Fix Get Active Triggers now working with Zabbix
This commit is contained in:
parent
b65b6aee48
commit
2c06ccde2e
134
telezab.py
134
telezab.py
@ -3,7 +3,7 @@ from flask import Flask, request, jsonify
|
|||||||
import telebot
|
import telebot
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
import hashlib
|
import hashlib
|
||||||
#import logging
|
import logging
|
||||||
from logging.config import dictConfig
|
from logging.config import dictConfig
|
||||||
from threading import Thread, Lock, Timer
|
from threading import Thread, Lock, Timer
|
||||||
import sqlite3
|
import sqlite3
|
||||||
@ -295,7 +295,7 @@ def set_user_state(chat_id, state):
|
|||||||
def start_settings_timer(chat_id):
|
def start_settings_timer(chat_id):
|
||||||
if chat_id in user_timers:
|
if chat_id in user_timers:
|
||||||
user_timers[chat_id].cancel()
|
user_timers[chat_id].cancel()
|
||||||
timer = Timer(60, transition_to_notification_mode, [chat_id])
|
timer = Timer(30, transition_to_notification_mode, [chat_id])
|
||||||
user_timers[chat_id] = timer
|
user_timers[chat_id] = timer
|
||||||
timer.start()
|
timer.start()
|
||||||
|
|
||||||
@ -918,14 +918,53 @@ def handle_region_selection(call):
|
|||||||
region_id = call.data.split("_")[1]
|
region_id = call.data.split("_")[1]
|
||||||
chat_id = call.message.chat.id
|
chat_id = call.message.chat.id
|
||||||
|
|
||||||
# Получение триггеров из реального Zabbix API
|
try:
|
||||||
triggers = get_zabbix_triggers(region_id)
|
# Получение всех групп хостов, содержащих region_id в названии
|
||||||
if not triggers:
|
zapi = ZabbixAPI(ZABBIX_URL)
|
||||||
bot.send_message(chat_id, "Нет активных проблем по указанному региону за последние 24 часа.")
|
zapi.login(api_token=ZABBIX_API_TOKEN)
|
||||||
else:
|
|
||||||
bot.send_message(chat_id, triggers, parse_mode="Markdown")
|
host_groups = zapi.hostgroup.get(
|
||||||
|
output=["groupid", "name"],
|
||||||
|
search={"name": region_id}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Фильтрация групп хостов, исключая те, в названии которых есть "test"
|
||||||
|
filtered_groups = [group for group in host_groups if 'test' not in group['name'].lower()]
|
||||||
|
|
||||||
|
if not filtered_groups:
|
||||||
|
bot.send_message(chat_id, "Нет групп хостов, соответствующих данному региону.")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Отправка списка групп хостов пользователю в виде кнопок
|
||||||
|
markup = telebot.types.InlineKeyboardMarkup()
|
||||||
|
for group in filtered_groups:
|
||||||
|
markup.add(telebot.types.InlineKeyboardButton(text=group['name'], callback_data=f"group_{group['groupid']}"))
|
||||||
|
|
||||||
|
bot.send_message(chat_id, f"Найдены следующие группы хостов для региона {region_id}:", reply_markup=markup)
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error connecting to Zabbix API: {e}")
|
||||||
|
bot.send_message(chat_id, "Не удалось подключиться к Zabbix API. Пожалуйста, попробуйте позже.")
|
||||||
|
|
||||||
|
|
||||||
|
@bot.callback_query_handler(func=lambda call: call.data.startswith("group_"))
|
||||||
|
def handle_group_selection(call):
|
||||||
|
group_id = call.data.split("_")[1]
|
||||||
|
chat_id = call.message.chat.id
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Получение триггеров для выбранной группы хостов
|
||||||
|
triggers = get_zabbix_triggers(group_id)
|
||||||
|
if triggers is None:
|
||||||
|
bot.send_message(chat_id, "Не удалось подключиться к Zabbix API. Пожалуйста, попробуйте позже.")
|
||||||
|
elif not triggers:
|
||||||
|
bot.send_message(chat_id, "Нет активных проблем по указанной группе за последние 24 часа.")
|
||||||
|
else:
|
||||||
|
bot.send_message(chat_id, triggers, parse_mode="Markdown")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error processing group selection: {e}")
|
||||||
|
bot.send_message(chat_id, "Произошла ошибка при обработке вашего запроса. Пожалуйста, попробуйте позже.")
|
||||||
|
|
||||||
bot.answer_callback_query(call.id) # Завершение обработки callback
|
|
||||||
|
|
||||||
|
|
||||||
@bot.callback_query_handler(func=lambda call: call.data.startswith("prev_") or call.data.startswith("next_"))
|
@bot.callback_query_handler(func=lambda call: call.data.startswith("prev_") or call.data.startswith("next_"))
|
||||||
@ -947,37 +986,60 @@ def handle_pagination(call):
|
|||||||
|
|
||||||
|
|
||||||
# Функция для получения активных триггеров из Zabbix API
|
# Функция для получения активных триггеров из Zabbix API
|
||||||
def get_zabbix_triggers(region_id):
|
def get_zabbix_triggers(group_id):
|
||||||
zapi = ZabbixAPI(ZABBIX_URL)
|
try:
|
||||||
zapi.login(api_token=ZABBIX_API_TOKEN)
|
zapi = ZabbixAPI(ZABBIX_URL)
|
||||||
|
zapi.login(api_token=ZABBIX_API_TOKEN)
|
||||||
|
|
||||||
# Получение триггеров уровня "Высокая" и "Авария" за последние 24 часа
|
# Получение триггеров уровня "Высокая" и "Авария" за последние 24 часа для указанной группы хостов
|
||||||
triggers = zapi.trigger.get(
|
time_from = int(time.time()) - 24 * 3600 # последние 24 часа
|
||||||
output=["triggerid", "description", "priority"],
|
triggers = zapi.trigger.get(
|
||||||
selectHosts=["hostid", "name"],
|
output=["triggerid", "description", "priority"],
|
||||||
filter={"priority": ["4", "5"], "value": "1"},
|
selectHosts=["hostid", "name"],
|
||||||
search={"host": region_id},
|
groupids=group_id,
|
||||||
only_true=1,
|
filter={"priority": ["4", "5"], "value": "1"},
|
||||||
active=1,
|
only_true=1,
|
||||||
withLastEventUnacknowledged=1,
|
active=1,
|
||||||
limit=100
|
withLastEventUnacknowledged=1,
|
||||||
)
|
time_from=time_from,
|
||||||
|
expandDescription=1,
|
||||||
|
expandComment=1,
|
||||||
|
selectItems=["itemid", "lastvalue"]
|
||||||
|
)
|
||||||
|
|
||||||
|
priority_map = {
|
||||||
|
'4': 'Высокая',
|
||||||
|
'5': 'Авария'
|
||||||
|
}
|
||||||
|
|
||||||
|
trigger_messages = []
|
||||||
|
for trigger in triggers:
|
||||||
|
description = trigger['description']
|
||||||
|
host = trigger['hosts'][0]['name']
|
||||||
|
priority = priority_map.get(trigger['priority'], 'Неизвестно')
|
||||||
|
trigger_id = trigger['triggerid']
|
||||||
|
|
||||||
|
# Заменяем {HOST.NAME} на имя хоста
|
||||||
|
description = description.replace("{HOST.NAME}", host)
|
||||||
|
|
||||||
|
# Заменяем {ITEM.LASTVALUE1} и другие на соответствующие значения
|
||||||
|
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'])
|
||||||
|
|
||||||
|
message = f"*Host*: {host}\n*Критичность*: {priority}\n*Описание*: {description}"
|
||||||
|
if trigger_id:
|
||||||
|
message += f"\n[Ссылка на триггер]({ZABBIX_URL}/tr_events.php?triggerid={trigger_id})"
|
||||||
|
trigger_messages.append(message)
|
||||||
|
|
||||||
|
return "\n---\n".join(trigger_messages)
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error connecting to Zabbix API: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
priority_map = {
|
|
||||||
'4': 'Высокая',
|
|
||||||
'5': 'Авария'
|
|
||||||
}
|
|
||||||
|
|
||||||
trigger_messages = []
|
|
||||||
for trigger in triggers:
|
|
||||||
description = trigger['description']
|
|
||||||
host = trigger['hosts'][0]['name']
|
|
||||||
priority = priority_map.get(trigger['priority'], 'Неизвестно')
|
|
||||||
trigger_id = trigger['triggerid']
|
|
||||||
link = f"[Ссылка на триггер](https://{ZABBIX_URL}/tr_events.php?triggerid={trigger_id})"
|
|
||||||
trigger_messages.append(f"*Host*: {host}\n*Уровень*: {priority}\n*Описание*: {description}\n{link}")
|
|
||||||
|
|
||||||
return "\n\n---\n\n".join(trigger_messages)
|
|
||||||
|
|
||||||
|
|
||||||
# Test functions for admin
|
# Test functions for admin
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user