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