Initial commit: PteraPyManager v2.5 with modular architecture, auto venv, python downloader, and resource quotas
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
import queue
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from typing import Optional, Dict, Any
|
||||
import requests
|
||||
|
||||
from core.models import TelegramConfig, DiscordConfig
|
||||
from core.logger import log_err, log_warn, log_debug
|
||||
|
||||
|
||||
class Notifier:
|
||||
"""Асинхронный диспетчер уведомлений для Telegram и Discord Webhook"""
|
||||
|
||||
def __init__(self):
|
||||
self._tg_cfg = TelegramConfig()
|
||||
self._dc_cfg = DiscordConfig()
|
||||
self._queue: queue.Queue = queue.Queue()
|
||||
self._shutdown_event = threading.Event()
|
||||
self._worker_thread = threading.Thread(
|
||||
target=self._worker, daemon=True, name="NotifierWorker"
|
||||
)
|
||||
self._worker_thread.start()
|
||||
|
||||
def update_configs(self, tg_cfg: TelegramConfig, dc_cfg: DiscordConfig):
|
||||
self._tg_cfg = tg_cfg
|
||||
self._dc_cfg = dc_cfg
|
||||
|
||||
def send(
|
||||
self,
|
||||
text: str,
|
||||
title: Optional[str] = None,
|
||||
level: str = "info",
|
||||
fields: Optional[Dict[str, str]] = None
|
||||
):
|
||||
"""
|
||||
Помещает уведомление в очередь отправки.
|
||||
:param text: Основной текст
|
||||
:param title: Заголовок (для Discord Embed)
|
||||
:param level: "info", "success", "warning", "error"
|
||||
:param fields: Словарь дополнительных полей {ключ: значение}
|
||||
"""
|
||||
if not self._tg_cfg.enabled and not self._dc_cfg.enabled:
|
||||
return
|
||||
|
||||
payload = {
|
||||
"text": text,
|
||||
"title": title or "PyTaskManager",
|
||||
"level": level,
|
||||
"fields": fields or {},
|
||||
"timestamp": datetime.utcnow().isoformat()
|
||||
}
|
||||
self._queue.put(payload)
|
||||
|
||||
def _worker(self):
|
||||
while not self._shutdown_event.is_set():
|
||||
try:
|
||||
item = self._queue.get(timeout=1.0)
|
||||
except queue.Empty:
|
||||
continue
|
||||
|
||||
try:
|
||||
if self._tg_cfg.enabled:
|
||||
self._send_telegram(item)
|
||||
if self._dc_cfg.enabled:
|
||||
self._send_discord(item)
|
||||
except Exception as e:
|
||||
log_debug(f"Ошибка в Notifier worker: {e}")
|
||||
finally:
|
||||
self._queue.task_done()
|
||||
|
||||
def _send_telegram(self, item: dict):
|
||||
if not self._tg_cfg.token or not self._tg_cfg.chat_id:
|
||||
return
|
||||
|
||||
url = f"https://api.telegram.org/bot{self._tg_cfg.token}/sendMessage"
|
||||
|
||||
# Преобразуем заголовок и поля в HTML для Telegram
|
||||
html_msg = item["text"]
|
||||
if item.get("fields"):
|
||||
field_lines = [f"• <b>{k}:</b> {v}" for k, v in item["fields"].items()]
|
||||
html_msg += "\n" + "\n".join(field_lines)
|
||||
|
||||
payload = {
|
||||
"chat_id": self._tg_cfg.chat_id,
|
||||
"text": html_msg,
|
||||
"parse_mode": "HTML"
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.post(url, json=payload, timeout=8)
|
||||
if not resp.ok:
|
||||
# Fallback без разметки
|
||||
payload.pop("parse_mode", None)
|
||||
payload["text"] = payload["text"].replace("<b>", "").replace("</b>", "").replace("<code>", "").replace("</code>", "")
|
||||
requests.post(url, json=payload, timeout=5)
|
||||
except requests.RequestException as e:
|
||||
log_err(f"Ошибка отправки Telegram: {e}")
|
||||
|
||||
def _send_discord(self, item: dict):
|
||||
if not self._dc_cfg.webhook_url:
|
||||
return
|
||||
|
||||
colors = {
|
||||
"success": 0x2ECC71, # Зеленый
|
||||
"error": 0xE74C3C, # Красный
|
||||
"warning": 0xF1C40F, # Желтый
|
||||
"info": 0x3498DB # Синий
|
||||
}
|
||||
embed_color = colors.get(item.get("level", "info"), 0x3498DB)
|
||||
|
||||
embed_fields = []
|
||||
for k, v in item.get("fields", {}).items():
|
||||
embed_fields.append({
|
||||
"name": str(k),
|
||||
"value": str(v),
|
||||
"inline": True
|
||||
})
|
||||
|
||||
# Очищаем HTML теги для Discord
|
||||
clean_desc = (
|
||||
item["text"]
|
||||
.replace("<b>", "**").replace("</b>", "**")
|
||||
.replace("<code>", "`").replace("</code>", "`")
|
||||
.replace("<pre>", "```").replace("</pre>", "```")
|
||||
)
|
||||
|
||||
embed = {
|
||||
"title": item.get("title", "Оповещение PyTaskManager"),
|
||||
"description": clean_desc,
|
||||
"color": embed_color,
|
||||
"fields": embed_fields,
|
||||
"footer": {"text": "PyTaskManager v2.5"}
|
||||
}
|
||||
|
||||
payload: Dict[str, Any] = {
|
||||
"username": self._dc_cfg.username or "PyTaskManager",
|
||||
"embeds": [embed]
|
||||
}
|
||||
if self._dc_cfg.avatar_url:
|
||||
payload["avatar_url"] = self._dc_cfg.avatar_url
|
||||
|
||||
try:
|
||||
resp = requests.post(self._dc_cfg.webhook_url, json=payload, timeout=8)
|
||||
if not resp.ok:
|
||||
log_warn(f"Ошибка отправки Discord Webhook: HTTP {resp.status_code} - {resp.text}")
|
||||
except requests.RequestException as e:
|
||||
log_err(f"Ошибка отправки Discord: {e}")
|
||||
|
||||
def shutdown(self):
|
||||
self._shutdown_event.set()
|
||||
Reference in New Issue
Block a user