python Copy code
import json
from typing import List, Optional, Dict, Any
from loguru import logger
import requests
import httpx
import asyncio
# Default Adaptive Card content
DEFAULT_CARD = {
"type": "AdaptiveCard",
"version": "1.4",
"body": [
{
"type": "TextBlock",
"text": "Hello from Python!",
"weight": "Bolder",
"size": "Medium"
},
{
"type": "TextBlock",
"text": "This is a default adaptive card sent via webhook.",
"wrap": True
}
],
"actions": [
{
"type": "Action.OpenUrl",
"title": "Learn more",
"url": "https://adaptivecards.io"
}
]
}
def build_adaptive_card(
title: str = "Hello from Python!",
message: str = "This is a default adaptive card sent via webhook.",
actions: Optional[List[Dict[str, Any]]] = None,
additional_body: Optional[List[Dict[str, Any]]] = None,
color: str = "#0078D7",
image_url: Optional[str] = None,
version: str = "1.4"
) -> Dict[str, Any]:
"""
Build an adaptive card payload.
"""
logger.debug("Building adaptive card with title: '{}', message: '{}'", title, message)
body = [
{
"type": "TextBlock",
"text": title,
"weight": "Bolder",
"size": "Medium",
"color": "Accent"
},
{
"type": "TextBlock",
"text": message,
"wrap": True
}
]
if image_url:
body.append({
"type": "Image",
"url": image_url,
"size": "Medium"
})
if additional_body:
body.extend(additional_body)
card = {
"type": "AdaptiveCard",
"version": version,
"body": body,
"actions": actions if actions is not None else [
{
"type": "Action.OpenUrl",
"title": "Learn more",
"url": "https://adaptivecards.io"
}
]
}
return card
def send_adaptive_card_sync(
webhook_url: str,
card_payload: Optional[Dict[str, Any]] = None,
timeout: int = 10,
raise_for_status: bool = True
) -> requests.Response:
"""
Send an adaptive card to the given webhook synchronously.
"""
if card_payload is None:
card_payload = DEFAULT_CARD
payload = {
"type": "message",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": card_payload
}
]
}
logger.info("Sending adaptive card synchronously to webhook: {}", webhook_url)
try:
response = requests.post(webhook_url, json=payload, timeout=timeout)
logger.debug("Received response: {}", response.text)
if raise_for_status:
response.raise_for_status()
logger.success("Adaptive card sent successfully.")
return response
except Exception as e:
logger.error("Failed to send adaptive card: {}", e)
raise
async def send_adaptive_card_async(
webhook_url: str,
card_payload: Optional[Dict[str, Any]] = None,
timeout: int = 10,
raise_for_status: bool = True
) -> httpx.Response:
"""
Send an adaptive card to the given webhook asynchronously.
"""
if card_payload is None:
card_payload = DEFAULT_CARD
payload = {
"type": "message",
"attachments": [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"content": card_payload
}
]
}
logger.info("Sending adaptive card asynchronously to webhook: {}", webhook_url)
async with httpx.AsyncClient(timeout=timeout) as client:
try:
response = await client.post(webhook_url, json=payload)
logger.debug("Received response: {}", response.text)
if raise_for_status:
response.raise_for_status()
logger.success("Adaptive card sent successfully (async).")
return response
except Exception as e:
logger.error("Failed to send adaptive card (async): {}", e)
raise
# Example usage
if __name__ == "__main__":
import os
# Set your webhook URL here
WEBHOOK_URL = os.getenv("TEAMS_WEBHOOK_URL", "https://your.webhook.url")
# Build a custom card
card = build_adaptive_card(
title="Build Notification",
message="Your build has completed successfully.",
image_url="https://adaptivecards.io/content/cats/1.png",
actions=[
{
"type": "Action.OpenUrl",
"title": "View Build",
"url": "https://dev.azure.com/"
}
]
)
# Synchronous send
try:
send_adaptive_card_sync(WEBHOOK_URL, card)
except Exception as e:
logger.error("Sync send failed: {}", e)
# Asynchronous send
async def main():
try:
await send_adaptive_card_async(WEBHOOK_URL, card)
except Exception as e:
logger.error("Async send failed: {}", e)
asyncio.run(main())