Fix get only current problem without ack and suppress
This commit is contained in:
parent
bfe4b1e938
commit
8a5acf5dc2
115
telezab.py
115
telezab.py
@ -1243,82 +1243,81 @@ def escape_telegram_chars(text):
|
|||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
def get_zabbix_triggers(group_id):
|
||||||
try:
|
try:
|
||||||
zapi = ZabbixAPI(ZABBIX_URL)
|
zapi = ZabbixAPI(ZABBIX_URL)
|
||||||
zapi.login(api_token=ZABBIX_API_TOKEN)
|
zapi.login(api_token=ZABBIX_API_TOKEN)
|
||||||
telebot.logger.info(f"Fetching triggers for group {group_id}")
|
telebot.logger.info(f"Fetching active hosts for group {group_id}")
|
||||||
|
|
||||||
# Получение событий
|
# Получаем список активных хостов в группе
|
||||||
triggers = zapi.trigger.get(
|
active_hosts = zapi.host.get(
|
||||||
output=["triggerid", "description", "priority"],
|
groupids=group_id,
|
||||||
selectHosts=["hostid", "name"],
|
output=["hostid", "name"],
|
||||||
groupids=group_id,
|
filter={"status": "0"} # Только включенные хосты
|
||||||
filter={"priority": ["4", "5"], "value": "1"}, # Высокий приоритет и авария
|
|
||||||
only_true=1,
|
|
||||||
active=1,
|
|
||||||
withLastEventUnacknowledged=1,
|
|
||||||
expandDescription=1,
|
|
||||||
expandComment=1,
|
|
||||||
selectItems=["itemid", "lastvalue"],
|
|
||||||
selectLastEvent=["clock"]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Сортировка триггеров по полю clock в локальном коде
|
if not active_hosts:
|
||||||
triggers_sorted = sorted(triggers, key=lambda t: int(t['lastEvent']['clock']))
|
telebot.logger.info(f"No active hosts found for group {group_id}")
|
||||||
|
return []
|
||||||
|
|
||||||
telebot.logger.info(f"Found {len(triggers)} triggers for group {group_id}")
|
host_ids = [host["hostid"] for host in active_hosts]
|
||||||
|
telebot.logger.info(f"Found {len(host_ids)} active hosts in group {group_id}")
|
||||||
|
|
||||||
# Московское время
|
# Получение активных проблем для этих хостов
|
||||||
moskva_tz = timezone('Europe/Moscow')
|
problems = zapi.problem.get(
|
||||||
|
output=["eventid", "name", "severity", "clock"],
|
||||||
|
hostids=host_ids,
|
||||||
|
suppressed=0,
|
||||||
|
acknowledged=0,
|
||||||
|
filter={"severity": ["4", "5"]}, # Только высокий и аварийный уровень
|
||||||
|
sortorder="ASC"
|
||||||
|
)
|
||||||
|
|
||||||
priority_map = {
|
if not problems:
|
||||||
'4': 'HIGH',
|
telebot.logger.info(f"No active problems found for group {group_id}")
|
||||||
'5': 'DISASTER'
|
return []
|
||||||
}
|
|
||||||
|
|
||||||
trigger_messages = []
|
# Получение IP-адресов хостов
|
||||||
|
host_interfaces = zapi.hostinterface.get(
|
||||||
for trigger in triggers_sorted:
|
hostids=host_ids,
|
||||||
event_time_epoch = int(trigger['lastEvent']['clock'])
|
output=["hostid", "ip"]
|
||||||
event_time = datetime.fromtimestamp(event_time_epoch, tz=moskva_tz)
|
)
|
||||||
|
host_ip_map = {iface["hostid"]: iface["ip"] for iface in host_interfaces}
|
||||||
description = escape_telegram_chars(trigger['description'])
|
print(host_ip_map)
|
||||||
host = trigger['hosts'][0]['name']
|
moscow_tz = timezone('Europe/Moscow')
|
||||||
priority = priority_map.get(trigger['priority'], 'Неизвестно')
|
severity_map = {'4': 'HIGH', '5': 'DISASTER'}
|
||||||
|
priority_map = {'4': '⚠️', '5': '⛔️'}
|
||||||
# Получаем itemids
|
problem_messages = []
|
||||||
item_ids = [item['itemid'] for item in trigger['items']]
|
|
||||||
|
|
||||||
telebot.logger.info(f"Trigger {trigger['triggerid']} on host {host} has itemids: {item_ids}")
|
|
||||||
|
|
||||||
# Формируем ссылку для batchgraph
|
|
||||||
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"
|
|
||||||
|
|
||||||
# Заменяем {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'])
|
|
||||||
|
|
||||||
|
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 Мск')
|
event_time_formatted = event_time.strftime('%Y-%m-%d %H:%M:%S Мск')
|
||||||
|
|
||||||
message = (f"<b>Host</b>: {host}\n"
|
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"<b>{priority} Host</b>: {host}\n"
|
||||||
|
f"<b>IP</b>: {host_ip}\n"
|
||||||
f"<b>Описание</b>: {description}\n"
|
f"<b>Описание</b>: {description}\n"
|
||||||
f"<b>Критичность</b>: {priority}\n"
|
f"<b>Критичность</b>: {severity}\n"
|
||||||
f"<b>Время создания</b>: {event_time_formatted}\n"
|
f"<b>Время создания</b>: {event_time_formatted}")
|
||||||
f'<b>URL</b>: <a href="{batchgraph_link}">Ссылка на график</a>')
|
|
||||||
|
|
||||||
trigger_messages.append(message)
|
problem_messages.append(message)
|
||||||
|
|
||||||
return trigger_messages
|
return problem_messages
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
telebot.logger.error(f"Error fetching triggers for group {group_id}: {e}")
|
telebot.logger.error(f"Error fetching problems for group {group_id}: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user