Spaces:
Sleeping
Sleeping
Create core/alerters.py
Browse files- core/alerters.py +41 -0
core/alerters.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# core/alerters.py
|
| 2 |
+
import datetime
|
| 3 |
+
import requests
|
| 4 |
+
import aiohttp
|
| 5 |
+
|
| 6 |
+
class BaseAlerter:
|
| 7 |
+
def send(self, message: str):
|
| 8 |
+
raise NotImplementedError("send() must be implemented.")
|
| 9 |
+
|
| 10 |
+
class ConsoleAlerter(BaseAlerter):
|
| 11 |
+
def send(self, message: str):
|
| 12 |
+
timestamp = datetime.datetime.now().isoformat()
|
| 13 |
+
print(f"[Console Alert][{timestamp}] {message}")
|
| 14 |
+
|
| 15 |
+
class FileAlerter(BaseAlerter):
|
| 16 |
+
def __init__(self, filepath="failsafe_errors.log"):
|
| 17 |
+
self.filepath = filepath
|
| 18 |
+
|
| 19 |
+
def send(self, message: str):
|
| 20 |
+
timestamp = datetime.datetime.now().isoformat()
|
| 21 |
+
with open(self.filepath, "a") as f:
|
| 22 |
+
f.write(f"[File Alert][{timestamp}] {message}\n")
|
| 23 |
+
|
| 24 |
+
class WebhookAlerter(BaseAlerter):
|
| 25 |
+
def __init__(self, url: str):
|
| 26 |
+
self.url = url
|
| 27 |
+
|
| 28 |
+
def send(self, message: str):
|
| 29 |
+
# Синхронный webhook
|
| 30 |
+
try:
|
| 31 |
+
requests.post(self.url, json={"alert": message})
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print("[WebhookAlert Failed]", e)
|
| 34 |
+
|
| 35 |
+
class AsyncWebhookAlerter(BaseAlerter):
|
| 36 |
+
def __init__(self, url: str):
|
| 37 |
+
self.url = url
|
| 38 |
+
|
| 39 |
+
async def send(self, message: str):
|
| 40 |
+
async with aiohttp.ClientSession() as session:
|
| 41 |
+
await session.post(self.url, json={"alert": message})
|