webhooks.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from typing import List, TYPE_CHECKING, Optional
  2. from dataclasses import dataclass, asdict
  3. import requests
  4. if TYPE_CHECKING:
  5. from issues.models import Issue
  6. from .models import Notification
  7. @dataclass
  8. class WebhookAttachment:
  9. title: str
  10. title_link: str
  11. text: str
  12. image_url: Optional[str] = None
  13. color: Optional[str] = None
  14. @dataclass
  15. class MSTeamsSection:
  16. """
  17. Similar to WebhookAttachment but for MS Teams
  18. https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using?tabs=cURL
  19. """
  20. activityTitle: str
  21. activitySubtitle: str
  22. @dataclass
  23. class WebhookPayload:
  24. alias: str
  25. text: str
  26. attachments: List[WebhookAttachment]
  27. sections: List[MSTeamsSection]
  28. def send_webhook(
  29. url: str,
  30. message: str,
  31. attachments: List[WebhookAttachment] = [],
  32. sections: List[MSTeamsSection] = [],
  33. ):
  34. data = WebhookPayload(
  35. alias="GlitchTip", text=message, attachments=attachments, sections=sections
  36. )
  37. response = requests.post(url, json=asdict(data))
  38. return response
  39. def send_issue_as_webhook(url, issues: List["Issue"], issue_count: int = 1):
  40. """
  41. Notification about issues via webhook.
  42. url: Webhook URL
  43. issues: This should be only the issues to send as attachment
  44. issue_count - total issues, may be greater than len(issues)
  45. """
  46. attachments: List[WebhookAttachment] = []
  47. sections: List[MSTeamsSection] = []
  48. for issue in issues:
  49. attachments.append(
  50. WebhookAttachment(
  51. title=str(issue),
  52. title_link=issue.get_detail_url(),
  53. text=issue.culprit,
  54. color=issue.get_hex_color(),
  55. )
  56. )
  57. sections.append(
  58. MSTeamsSection(
  59. activityTitle=str(issue),
  60. activitySubtitle=f"[View Issue {issue.short_id_display}]({issue.get_detail_url()})",
  61. )
  62. )
  63. message = "GlitchTip Alert"
  64. if issue_count > 1:
  65. message += f" ({issue_count} issues)"
  66. return send_webhook(url, message, attachments, sections)
  67. def send_webhook_notification(notification: "Notification", url: str):
  68. issue_count = notification.issues.count()
  69. issues = notification.issues.all()[:3] # Show no more than three
  70. send_issue_as_webhook(url, issues, issue_count)