webhook.py 1.56 KB
Newer Older
changchiyou's avatar
changchiyou committed
1
import json
Timothy J. Baek's avatar
Timothy J. Baek committed
2
import requests
3
from config import VERSION, WEBUI_FAVICON_URL, WEBUI_NAME
Timothy J. Baek's avatar
Timothy J. Baek committed
4

Timothy J. Baek's avatar
Timothy J. Baek committed
5
def post_webhook(url: str, message: str, event_data: dict) -> bool:
Timothy J. Baek's avatar
Timothy J. Baek committed
6
    try:
Timothy J. Baek's avatar
Timothy J. Baek committed
7
8
        payload = {}

9
10
        # Slack and Google Chat Webhooks
        if "https://hooks.slack.com" in url or "https://chat.googleapis.com" in url:
Timothy J. Baek's avatar
Timothy J. Baek committed
11
            payload["text"] = message
12
        # Discord Webhooks
Timothy J. Baek's avatar
Timothy J. Baek committed
13
14
        elif "https://discord.com/api/webhooks" in url:
            payload["content"] = message
15
        # Microsoft Teams Webhooks
changchiyou's avatar
changchiyou committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
        elif "webhook.office.com" in url:
            action = event_data.get("action", "undefined")
            facts = [
                {"name": name, "value": value}
                for name, value in json.loads(event_data.get("user", {})).items()
            ]
            payload = {
                "@type": "MessageCard",
                "@context": "http://schema.org/extensions",
                "themeColor": "0076D7",
                "summary": message,
                "sections": [
                    {
                        "activityTitle": message,
30
31
                        "activitySubtitle": f"{WEBUI_NAME} ({VERSION}) - {action}",
                        "activityImage": WEBUI_FAVICON_URL,
changchiyou's avatar
changchiyou committed
32
33
34
35
36
                        "facts": facts,
                        "markdown": True,
                    }
                ],
            }
37
        # Default Payload
Timothy J. Baek's avatar
Timothy J. Baek committed
38
39
40
41
        else:
            payload = {**event_data}

        r = requests.post(url, json=payload)
Timothy J. Baek's avatar
Timothy J. Baek committed
42
43
44
45
        r.raise_for_status()
        return True
    except Exception as e:
        print(e)
46
        return False