webhook.py 1.39 KB
Newer Older
changchiyou's avatar
changchiyou committed
1
2
import json

Timothy J. Baek's avatar
Timothy J. Baek committed
3
import requests
4
from config import VERSION, WEBUI_FAVICON_URL, WEBUI_NAME
Timothy J. Baek's avatar
Timothy J. Baek committed
5
6


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

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

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