open-webui/backend/utils/webhook.py

55 lines
1.7 KiB
Python
Raw Permalink Normal View History

import json
2024-03-21 02:35:02 +01:00
import requests
import logging
from config import SRC_LOG_LEVELS, VERSION, WEBUI_FAVICON_URL, WEBUI_NAME
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["WEBHOOK"])
2024-03-21 02:35:02 +01:00
2024-03-31 10:13:39 +02:00
2024-03-21 02:47:13 +01:00
def post_webhook(url: str, message: str, event_data: dict) -> bool:
2024-03-21 02:35:02 +01:00
try:
2024-03-21 02:47:13 +01:00
payload = {}
# Slack and Google Chat Webhooks
if "https://hooks.slack.com" in url or "https://chat.googleapis.com" in url:
2024-03-21 02:47:13 +01:00
payload["text"] = message
# Discord Webhooks
2024-03-21 02:47:13 +01:00
elif "https://discord.com/api/webhooks" in url:
payload["content"] = message
# Microsoft Teams Webhooks
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,
"activitySubtitle": f"{WEBUI_NAME} ({VERSION}) - {action}",
"activityImage": WEBUI_FAVICON_URL,
"facts": facts,
"markdown": True,
}
],
}
# Default Payload
2024-03-21 02:47:13 +01:00
else:
payload = {**event_data}
log.debug(f"payload: {payload}")
2024-03-21 02:47:13 +01:00
r = requests.post(url, json=payload)
2024-03-21 02:35:02 +01:00
r.raise_for_status()
log.debug(f"r.text: {r.text}")
2024-03-21 02:35:02 +01:00
return True
except Exception as e:
log.exception(e)
2024-03-31 10:13:39 +02:00
return False