Telezab/utilities/telegram_utilities.py

120 lines
4.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import re
import time
import telebot
import backend_bot
import backend_flask
import bot_database
import telezab
def validate_chat_id(chat_id):
"""Validate that chat_id is composed only of digits."""
return chat_id.isdigit()
def validate_telegram_id(telegram_id):
"""Validate that telegram_id starts with '@'."""
return telegram_id.startswith('@')
def validate_email(email):
"""Validate that email domain is '@rtmis.ru'."""
return re.match(r'^[\w.-]+@rtmis\.ru$', email) is not None
def format_message(data):
try:
priority_map = {
'High': '⚠️',
'Disaster': '⛔️'
}
priority = priority_map.get(data['severity'])
msg = escape_telegram_chars(data['msg'])
if data['status'].upper() == "PROBLEM":
message = (
f"{priority} {data['host']} ({data['ip']})\n"
f"<b>Описание</b>: {msg}\n"
f"<b>Критичность</b>: {data['severity']}\n"
f"<b>Время возникновения</b>: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(data['date_reception'])))} Мск\n"
)
if 'link' in data:
message += f'<b>URL</b>: <a href="{data['link']}">Ссылка на график</a>'
return message
else:
message = (
f"{data['host']} ({data['ip']})\n"
f"<b>Описание</b>: {msg}\n"
f"<b>Критичность</b>: {data['severity']}\n"
f"<b>Проблема устранена!</b>\n"
f"<b>Время устранения</b>: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(data['date_reception'])))} Мск\n"
)
if 'link' in data:
message += f'<b>URL</b>: <a href="{data['link']}">Ссылка на график</a>'
return message
except KeyError as e:
backend_flask.app.logger.error(f"Missing key in data: {e}")
raise ValueError(f"Missing key in data: {e}")
def extract_region_number(host):
# Используем регулярное выражение для извлечения цифр после первого символа и до первой буквы
match = re.match(r'^.\d+', host)
if match:
return match.group(0)[1:] # Возвращаем строку без первого символа
return None
def escape_telegram_chars(text):
"""
Экранирует запрещённые символы для Telegram API:
< -> &lt;
> -> &gt;
& -> &amp;
Также проверяет на наличие запрещённых HTML-тегов и другие проблемы с форматированием.
"""
replacements = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;', # Для кавычек
}
# Применяем замены
for char, replacement in replacements.items():
text = text.replace(char, replacement)
return text
def show_main_menu(chat_id):
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
if bot_database.is_whitelisted(chat_id):
telezab.state.set_state(chat_id, "MAIN_MENU")
markup.add('Настройки', 'Помощь', 'Активные события')
else:
telezab.state.set_state(chat_id, "REGISTRATION")
markup.add('Регистрация')
backend_bot.bot.send_message(chat_id, "Выберите действие:", reply_markup=markup)
def create_settings_keyboard(chat_id, admins_list):
markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
markup.row('Подписаться', 'Отписаться')
markup.row('Мои подписки', 'Режим уведомлений')
markup.row('Назад')
return markup
def show_settings_menu(chat_id):
if not bot_database.is_whitelisted(chat_id):
telezab.state.set_state(chat_id, "REGISTRATION")
backend_bot.bot.send_message(chat_id, "Вы неавторизованы для использования этого бота")
return
admins_list = bot_database.get_admins()
markup = create_settings_keyboard(chat_id, admins_list)
backend_bot.bot.send_message(chat_id, "Вы находитесь в режиме настроек. Выберите действие:", reply_markup=markup)