Bugfix, add some extra test buttons

This commit is contained in:
Udo Chudo 2024-07-15 23:52:05 +05:00
parent 5ccd21ab18
commit 2d4d3f265e

View File

@ -13,6 +13,8 @@ import aiohttp
import pika
import json
from concurrent.futures import ThreadPoolExecutor
from pyzabbix import ZabbixAPI
import requests # Добавлено для имитации POST запроса
# Load environment variables
load_dotenv()
@ -45,8 +47,11 @@ app = Flask(__name__)
# Get the token from environment variables
TOKEN = os.getenv('TELEGRAM_TOKEN')
if not TOKEN:
raise ValueError("No TELEGRAM_TOKEN found in environment variables")
ZABBIX_URL = os.getenv('ZABBIX_URL')
ZABBIX_API_TOKEN = os.getenv('ZABBIX_API_TOKEN')
if not TOKEN or not ZABBIX_URL or not ZABBIX_API_TOKEN:
raise ValueError("One or more required environment variables are missing")
ADMIN_CHAT_IDS = os.getenv('ADMIN_CHAT_IDS', '').split(',')
@ -261,7 +266,7 @@ def transition_to_notification_mode(chat_id):
def show_main_menu(chat_id):
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
if is_whitelisted(chat_id):
markup.add('Настройки', 'Помощь')
markup.add('Настройки', 'Помощь', 'Активные триггеры')
else:
markup.add('Регистрация')
bot.send_message(chat_id, "Выберите действие:", reply_markup=markup)
@ -271,6 +276,7 @@ def show_settings_menu(chat_id):
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
if str(chat_id) in ADMIN_CHAT_IDS:
markup.add('Подписаться', 'Отписаться', 'Мои подписки', 'Активные регионы', 'Добавить регион', 'Удалить регион', 'Назад')
markup.add('Тестовое событие', 'Тест триггеров')
else:
markup.add('Подписаться', 'Отписаться', 'Мои подписки', 'Активные регионы', 'Назад')
bot.send_message(chat_id, "Вы находитесь в режиме настроек. Выберите действие:", reply_markup=markup)
@ -306,6 +312,8 @@ def handle_menu_selection(message):
show_settings_menu(chat_id)
elif text == 'помощь':
handle_help(message)
elif text == 'активные триггеры':
handle_active_triggers(message)
else:
bot.send_message(chat_id, "Команда не распознана или у вас нет прав для выполнения этой команды.")
show_main_menu(chat_id)
@ -327,6 +335,10 @@ def handle_settings_menu_selection(message):
prompt_admin_for_region(chat_id, 'add')
elif text == 'удалить регион' and str(chat_id) in ADMIN_CHAT_IDS:
prompt_admin_for_region(chat_id, 'remove')
elif text == 'тестовое событие' and str(chat_id) in ADMIN_CHAT_IDS:
simulate_event(message)
elif text == 'тест триггеров' and str(chat_id) in ADMIN_CHAT_IDS:
simulate_triggers(message)
elif text == 'назад':
set_user_state(chat_id, NOTIFICATION_MODE)
show_main_menu(chat_id)
@ -772,6 +784,124 @@ def format_message(data):
f"Trigger: {data['trigger']}\n"
f"Value: {data['value']}")
# Handle active triggers
def handle_active_triggers(message):
chat_id = message.chat.id
regions = get_user_subscribed_regions(chat_id)
regions_per_page = 3
start_index = 0
markup = create_region_markup(regions, start_index, regions_per_page)
bot.send_message(chat_id, "По какому региону хотите получить активные проблемы:", reply_markup=markup)
def create_region_markup(regions, start_index, regions_per_page):
markup = telebot.types.InlineKeyboardMarkup()
end_index = min(start_index + regions_per_page, len(regions))
buttons = []
for i in range(start_index, end_index):
region_id, region_name = regions[i]
buttons.append(telebot.types.InlineKeyboardButton(text=region_id, callback_data=f"region_{region_id}"))
prev_button = telebot.types.InlineKeyboardButton(text="<", callback_data=f"prev_{start_index}") if start_index > 0 else None
next_button = telebot.types.InlineKeyboardButton(text=">", callback_data=f"next_{start_index}") if end_index < len(regions) else None
row_buttons = [prev_button] + buttons + [next_button]
row_buttons = [btn for btn in row_buttons if btn is not None] # Remove None values
markup.row(*row_buttons)
return markup
@bot.callback_query_handler(func=lambda call: call.data.startswith("region_"))
def handle_region_selection(call):
region_id = call.data.split("_")[1]
chat_id = call.message.chat.id
# Mocking the Zabbix triggers for the given region_id
triggers = get_mocked_zabbix_triggers(region_id)
if not triggers:
bot.send_message(chat_id, "Нет активных проблем по указанному региону за последние 24 часа.")
else:
bot.send_message(chat_id, triggers, parse_mode="Markdown")
@bot.callback_query_handler(func=lambda call: call.data.startswith("prev_") or call.data.startswith("next_"))
def handle_pagination(call):
direction, index = call.data.split("_")
index = int(index)
regions = get_user_subscribed_regions(call.message.chat.id)
regions_per_page = 3
if direction == "prev":
start_index = max(0, index - regions_per_page)
else:
start_index = min(len(regions) - regions_per_page, index + regions_per_page)
markup = create_region_markup(regions, start_index, regions_per_page)
bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id, reply_markup=markup)
def get_mocked_zabbix_triggers(region_id):
# Mocked Zabbix triggers
triggers = [
{
"triggerid": "1",
"description": f"Проблема {region_id}-1",
"priority": "4",
"hosts": [{"hostid": region_id, "name": f"Хост {region_id}-1"}]
},
{
"triggerid": "2",
"description": f"Проблема {region_id}-2",
"priority": "5",
"hosts": [{"hostid": region_id, "name": f"Хост {region_id}-2"}]
}
]
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
def simulate_event(message):
chat_id = message.chat.id
test_event = {
"region": "12",
"host": "Тестовое сообщение",
"item": "Марий Эл",
"trigger": "Спасайте её",
"value": "Авария!"
}
app.logger.info(f"Simulating event: {test_event}")
# Use requests to simulate a POST request
response = requests.post('http://localhost:5000/webhook', json=test_event)
app.logger.info(f"Response from webhook: {response.status_code} - {response.text}")
bot.send_message(chat_id, f"Тестовое событие отправлено. Статус ответа: {response.status_code}")
def simulate_triggers(message):
chat_id = message.chat.id
regions = ["12", "19", "35", "40"]
trigger_messages = []
for region_id in regions:
triggers = get_mocked_zabbix_triggers(region_id)
if triggers:
trigger_messages.append(f"Регион {region_id}:\n{triggers}")
if trigger_messages:
bot.send_message(chat_id, "\n\n".join(trigger_messages), parse_mode="Markdown")
else:
bot.send_message(chat_id, "Нет активных проблем по указанным регионам за последние 24 часа.")
def run_polling():
bot.polling(none_stop=True, interval=0)