webhook.py 1.6 KB

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