|
| 1 | +from datetime import datetime |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +import requests |
| 5 | +from pydantic import BaseModel |
| 6 | + |
| 7 | +from elementary.messages.formats.adaptive_cards import format_adaptive_card |
| 8 | +from elementary.messages.message_body import MessageBody |
| 9 | +from elementary.messages.messaging_integrations.base_messaging_integration import ( |
| 10 | + BaseMessagingIntegration, |
| 11 | + MessageSendResult, |
| 12 | +) |
| 13 | +from elementary.messages.messaging_integrations.exceptions import ( |
| 14 | + MessageIntegrationReplyNotSupportedError, |
| 15 | + MessagingIntegrationError, |
| 16 | +) |
| 17 | +from elementary.utils.log import get_logger |
| 18 | + |
| 19 | +logger = get_logger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +class ChannelWebhook(BaseModel): |
| 23 | + webhook: str |
| 24 | + channel: Optional[str] = None |
| 25 | + |
| 26 | + |
| 27 | +def send_adaptive_card(webhook_url: str, card: dict) -> requests.Response: |
| 28 | + """Sends an Adaptive Card to the specified webhook URL.""" |
| 29 | + payload = { |
| 30 | + "type": "message", |
| 31 | + "attachments": [ |
| 32 | + { |
| 33 | + "contentType": "application/vnd.microsoft.card.adaptive", |
| 34 | + "contentUrl": None, |
| 35 | + "content": card, |
| 36 | + } |
| 37 | + ], |
| 38 | + } |
| 39 | + |
| 40 | + response = requests.post( |
| 41 | + webhook_url, |
| 42 | + json=payload, |
| 43 | + headers={"Content-Type": "application/json"}, |
| 44 | + ) |
| 45 | + response.raise_for_status() |
| 46 | + if response.status_code == 202: |
| 47 | + logger.debug("Got 202 response from Teams webhook, assuming success") |
| 48 | + return response |
| 49 | + |
| 50 | + |
| 51 | +class TeamsWebhookMessagingIntegration( |
| 52 | + BaseMessagingIntegration[ChannelWebhook, ChannelWebhook] |
| 53 | +): |
| 54 | + def send_message( |
| 55 | + self, |
| 56 | + destination: ChannelWebhook, |
| 57 | + body: MessageBody, |
| 58 | + ) -> MessageSendResult[ChannelWebhook]: |
| 59 | + card = format_adaptive_card(body) |
| 60 | + try: |
| 61 | + send_adaptive_card(destination.webhook, card) |
| 62 | + return MessageSendResult( |
| 63 | + message_context=destination, |
| 64 | + timestamp=datetime.utcnow(), |
| 65 | + ) |
| 66 | + except requests.RequestException as e: |
| 67 | + raise MessagingIntegrationError( |
| 68 | + "Failed to send message to Teams webhook" |
| 69 | + ) from e |
| 70 | + |
| 71 | + def supports_reply(self) -> bool: |
| 72 | + return False |
| 73 | + |
| 74 | + def reply_to_message( |
| 75 | + self, |
| 76 | + destination: ChannelWebhook, |
| 77 | + message_context: ChannelWebhook, |
| 78 | + body: MessageBody, |
| 79 | + ) -> MessageSendResult[ChannelWebhook]: |
| 80 | + raise MessageIntegrationReplyNotSupportedError( |
| 81 | + "Teams webhook message integration does not support replying to messages" |
| 82 | + ) |
0 commit comments