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

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

10
11
        # 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
12
            payload["text"] = message
13
        # Discord Webhooks
Timothy J. Baek's avatar
Timothy J. Baek committed
14
15
        elif "https://discord.com/api/webhooks" in url:
            payload["content"] = message
16
        # Microsoft Teams Webhooks
changchiyou's avatar
changchiyou committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
        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,
31
32
                        "activitySubtitle": f"{WEBUI_NAME} ({VERSION}) - {action}",
                        "activityImage": WEBUI_FAVICON_URL,
changchiyou's avatar
changchiyou committed
33
34
35
36
37
                        "facts": facts,
                        "markdown": True,
                    }
                ],
            }
38
        # Default Payload
Timothy J. Baek's avatar
Timothy J. Baek committed
39
40
41
42
        else:
            payload = {**event_data}

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