zbx-tg-bot/main.py

94 lines
2.9 KiB
Python

import logging as log
from zabbix import get_active_problems, check_state
from config import conf, icon_dict
from redis_db import (
get_all_keys,
get_value,
set_value,
del_value,
)
import asyncio
from telegram import (
del_message,
send_message,
start_bot,
send_zabbix_api_alert,
edit_message,
)
async def dashboard():
active_alerts = get_active_problems()
if active_alerts is None:
if check_state(False) == "DOWN":
send_state = await send_zabbix_api_alert(conf.zabbix.alert_text_down)
if send_state["status"] == 200:
conf.zabbix.api_state = "DOWN"
conf.zabbix.change_state_count = 0
return
else:
if check_state(True) == "UP":
send_state = await send_zabbix_api_alert(conf.zabbix.alert_text_up)
if send_state["status"] == 200:
conf.zabbix.api_state = "UP"
conf.zabbix.change_state_count = 0
telegram_alerts = await get_all_keys()
new_alerts_id = []
closed_alerts_id = []
for active_alert in active_alerts["event_ids"]:
if active_alert not in telegram_alerts:
new_alerts_id.append(active_alert)
for telegram_alert in telegram_alerts:
if telegram_alert not in active_alerts["event_ids"]:
closed_alerts_id.append(telegram_alert)
log.info("new " + str(new_alerts_id))
log.info("closed " + str(closed_alerts_id))
for new_alert in new_alerts_id:
message = (
icon_dict[active_alerts[new_alert]["severity"]]
+ f" {active_alerts[new_alert]['host']}\n"
+ f"{active_alerts[new_alert]['name']}"
)
msg_id = await send_message(message=message, event_id=new_alert)
if msg_id["status"] == 200:
await set_value(key=new_alert, value=msg_id["msg_id"])
for closed_alert in closed_alerts_id:
msg_id = await get_value(closed_alert)
if msg_id:
resp = await del_message(int(msg_id))
if resp["status"] == 200:
await del_value(closed_alert)
if resp["status"] == 400:
resp = await edit_message(int(msg_id), conf.tgbot.delete_msg)
if resp["status"] == 200:
await del_value(closed_alert)
if resp["status"] == 400:
log.warning(f"remove olg message {msg_id} from reddis")
await del_value(closed_alert)
async def dashboard_loop():
log.info("Dashboard loop started")
while True:
await dashboard()
await asyncio.sleep(conf.zabbix.upd_interval)
async def main():
await asyncio.gather(dashboard_loop(), start_bot())
if __name__ == "__main__":
log.info("Starting app")
try:
asyncio.run(main())
except KeyboardInterrupt:
log.info("Manual app stopped")
log.info("App stopped")