webhook.py 1.7 KB

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