webhook.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import json
  2. import logging
  3. import requests
  4. from open_webui.config import WEBUI_FAVICON_URL, WEBUI_NAME
  5. from open_webui.env import SRC_LOG_LEVELS, VERSION
  6. log = logging.getLogger(__name__)
  7. log.setLevel(SRC_LOG_LEVELS["WEBHOOK"])
  8. def post_webhook(url: str, message: str, event_data: dict) -> bool:
  9. try:
  10. payload = {}
  11. # Slack and Google Chat Webhooks
  12. if "https://hooks.slack.com" in url or "https://chat.googleapis.com" in url:
  13. payload["text"] = message
  14. # Discord Webhooks
  15. elif "https://discord.com/api/webhooks" in url:
  16. payload["content"] = message
  17. # Microsoft Teams Webhooks
  18. elif "webhook.office.com" in url:
  19. action = event_data.get("action", "undefined")
  20. facts = [
  21. {"name": name, "value": value}
  22. for name, value in json.loads(event_data.get("user", {})).items()
  23. ]
  24. payload = {
  25. "@type": "MessageCard",
  26. "@context": "http://schema.org/extensions",
  27. "themeColor": "0076D7",
  28. "summary": message,
  29. "sections": [
  30. {
  31. "activityTitle": message,
  32. "activitySubtitle": f"{WEBUI_NAME} ({VERSION}) - {action}",
  33. "activityImage": WEBUI_FAVICON_URL,
  34. "facts": facts,
  35. "markdown": True,
  36. }
  37. ],
  38. }
  39. # Default Payload
  40. else:
  41. payload = {**event_data}
  42. log.debug(f"payload: {payload}")
  43. r = requests.post(url, json=payload)
  44. r.raise_for_status()
  45. log.debug(f"r.text: {r.text}")
  46. return True
  47. except Exception as e:
  48. log.exception(e)
  49. return False