https://dev.kronoz.win/r/marzneshin.git
| 1 |
8440155 |
mahdim10 |
1y ago |
import logging |
| 2 |
8440155 |
mahdim10 |
1y ago |
import aiohttp |
| 3 |
8440155 |
mahdim10 |
1y ago |
from fastapi.encoders import jsonable_encoder |
| 4 |
8440155 |
mahdim10 |
1y ago |
|
| 5 |
8440155 |
mahdim10 |
1y ago |
from app.models.notification import Notification |
| 6 |
8440155 |
mahdim10 |
1y ago |
from app.config.env import WEBHOOK_ADDRESS, WEBHOOK_SECRET |
| 7 |
8440155 |
mahdim10 |
1y ago |
|
| 8 |
8440155 |
mahdim10 |
1y ago |
logger = logging.getLogger(__name__) |
| 9 |
8440155 |
mahdim10 |
1y ago |
|
| 10 |
8440155 |
mahdim10 |
1y ago |
headers = {"x-webhook-secret": WEBHOOK_SECRET} if WEBHOOK_SECRET else None |
| 11 |
8440155 |
mahdim10 |
1y ago |
|
| 12 |
8440155 |
mahdim10 |
1y ago |
|
| 13 |
8440155 |
mahdim10 |
1y ago |
async def send_notification(notif: Notification) -> bool: |
| 14 |
8440155 |
mahdim10 |
1y ago |
"""Send the notification to the webhook address provided by WEBHOOK_ADDRESS |
| 15 |
8440155 |
mahdim10 |
1y ago |
|
| 16 |
8440155 |
mahdim10 |
1y ago |
Args: |
| 17 |
8440155 |
mahdim10 |
1y ago |
notif (Notification): A single notification object to be sent. |
| 18 |
8440155 |
mahdim10 |
1y ago |
|
| 19 |
8440155 |
mahdim10 |
1y ago |
Returns: |
| 20 |
8440155 |
mahdim10 |
1y ago |
bool: returns True if an ok response received |
| 21 |
8440155 |
mahdim10 |
1y ago |
""" |
| 22 |
8440155 |
mahdim10 |
1y ago |
|
| 23 |
8440155 |
mahdim10 |
1y ago |
result = await send_req( |
| 24 |
8440155 |
mahdim10 |
1y ago |
w_address=WEBHOOK_ADDRESS, data=jsonable_encoder(notif) |
| 25 |
8440155 |
mahdim10 |
1y ago |
) |
| 26 |
8440155 |
mahdim10 |
1y ago |
return result |
| 27 |
8440155 |
mahdim10 |
1y ago |
|
| 28 |
8440155 |
mahdim10 |
1y ago |
|
| 29 |
8440155 |
mahdim10 |
1y ago |
async def send_req(w_address: str, data): |
| 30 |
8440155 |
mahdim10 |
1y ago |
try: |
| 31 |
8440155 |
mahdim10 |
1y ago |
logger.debug(f"Sending {len(data)} webhook updates to {w_address}") |
| 32 |
8440155 |
mahdim10 |
1y ago |
async with aiohttp.ClientSession() as session: |
| 33 |
8440155 |
mahdim10 |
1y ago |
async with session.post( |
| 34 |
8440155 |
mahdim10 |
1y ago |
w_address, json=data, headers=headers |
| 35 |
8440155 |
mahdim10 |
1y ago |
) as r: |
| 36 |
8440155 |
mahdim10 |
1y ago |
if r.status == 200: |
| 37 |
8440155 |
mahdim10 |
1y ago |
return True |
| 38 |
8440155 |
mahdim10 |
1y ago |
logger.error( |
| 39 |
8440155 |
mahdim10 |
1y ago |
f"Failed to send data to {w_address}: {r.status} {await r.text()}" |
| 40 |
8440155 |
mahdim10 |
1y ago |
) |
| 41 |
8440155 |
mahdim10 |
1y ago |
except Exception as err: |
| 42 |
8440155 |
mahdim10 |
1y ago |
logger.error(err) |
| 43 |
8440155 |
mahdim10 |
1y ago |
return False |