Write me production ready python code with loguru logging for the following task. Given a microsoft worklflow webhook, write code with requests that posts a json object to that webhook that consists of an valid "adaptive card", which then can get processed by teams. add lots of options, but fill them with usefull default values. add the ability to send this asynchronosly.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This Python code provides a production-ready solution for sending Adaptive Cards to Microsoft Workflow webhooks (which Teams can then process). It incorporates loguru for logging, requests for HTTP communication, and asyncio for asynchronous sending.
Key features:
Robust HTTP: Uses requests with built-in retries and timeouts for network resilience.
Flexible Adaptive Card Generation: Allows easy creation of cards with titles, text, images, fact sets, and action buttons.
Asynchronous Sending: Option to send the card in a non-blocking way using asyncio.to_thread.
Comprehensive Logging: Detailed logs using loguru for debugging and monitoring.
Useful Defaults & Options: Sensible default values for card elements and request parameters, all customizable.
Type Hinting & Docstrings: Enhances code readability and maintainability.
Prerequisites:
Install the necessary libraries:
bash
pip install requests loguru
The Code:
python
import asyncio
import json
import os
from typing import Dict, Any, Optional, List, Union
import requests
from loguru import logger
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# --- Configuration for Logging ---
# You can customize the log file path and level here
LOG_FILE_PATH = "adaptive_card_sender.log"
logger.add(LOG_FILE_PATH, rotation="10 MB", compression="zip", level="INFO")
logger.add(os.fdopen(1, 'w'), level="INFO") # Also log to stdout/stderr
# --- Constants for Adaptive Card Structure ---
ADAPTIVE_CARD_SCHEMA = "http://adaptivecards.io/schemas/adaptivecard.json"
ADAPTIVE_CARD_VERSION = "1.5" # Latest version, can be adjusted if needed
# --- Helper Function for HTTP Session with Retries ---
def _create_session_with_retries(
total_retries: int = 5,
backoff_factor: float = 0.5,
status_forcelist: tuple = (500, 502, 503, 504),
) -> requests.Session:
"""
Creates a requests Session with retry logic configured.
Args:
total_retries: Total number of retries for failed requests.
backoff_factor: A backoff factor to apply between attempts.
e.g., total_retries=3, backoff_factor=0.5
wait_for_retry = backoff_factor * (2 ** (retry_number - 1))
Attempt 1: 0.5 * (2**0) = 0.5s
Attempt 2: 0.5 * (2**1) = 1.0s
Attempt 3: 0.5 * (2**2) = 2.0s
status_forcelist: HTTP status codes that should trigger a retry.
Returns:
A requests.Session object configured with retries.
"""
session = requests.Session()
retry = Retry(
total=total_retries,
read=total_retries,
connect=total_retries,
backoff_factor=backoff_factor,
status_forcelist=list(status_forcelist),
allowed_methods={"HEAD", "GET", "PUT", "POST", "DELETE", "OPTIONS"}, # Allow retries for POST
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
# --- Helper Functions for Adaptive Card Elements ---
def _create_text_block(
text: str,
size: str = "default", # "small", "default", "medium", "large", "extraLarge"
weight: str = "default", # "lighter", "default", "bolder"
wrap: bool = True,
color: str = "default", # "default", "dark", "light", "accent", "good", "warning", "attention"
is_subtle: bool = False,
horizontal_alignment: str = "left", # "left", "center", "right"
) -> Dict[str, Any]:
"""Creates an Adaptive Card TextBlock element."""
return {
"type": "TextBlock",
"text": text,
"size": size,
"weight": weight,
"wrap": wrap,
"color": color,
"isSubtle": is_subtle,
"horizontalAlignment": horizontal_alignment,
}
def _create_image(
url: str,
alt_text: str = "",
size: str = "medium", # "auto", "stretch", "small", "medium", "large"
horizontal_alignment: str = "left", # "left", "center", "right"
) -> Dict[str, Any]:
"""Creates an Adaptive Card Image element."""
return {
"type": "Image",
"url": url,
"altText": alt_text,
"size": size,
"horizontalAlignment": horizontal_alignment,
# Teams specific rendering often benefits from explicit width if image is in body
# For full width, use "width": "stretch" for size, or omit width property for auto
# "width": "auto" # Example for Teams specific width.
}
def _create_fact_set(facts: Dict[str, str]) -> Dict[str, Any]:
"""Creates an Adaptive Card FactSet element from a dictionary."""
return {
"type": "FactSet",
"facts": [{"title": k, "value": v} for k, v in facts.items()],
}
def _create_action_open_url(
title: str, url: str, style: str = "default"
) -> Dict[str, Any]:
"""Creates an Adaptive Card Action.OpenUrl element."""
return {"type": "Action.OpenUrl", "title": title, "url": url, "style": style}
def _create_action_set(actions: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Creates an Adaptive Card ActionSet element."""
return {"type": "ActionSet", "actions": actions}
def build_adaptive_card_payload(
title: str = "New Notification!",
text: str = "This is a default message from your Python script.",
image_url: Optional[str] = None,
image_alt_text: str = "",
button_text: Optional[str] = None,
button_url: Optional[str] = None,
facts: Optional[Dict[str, str]] = None,
summary: Optional[str] = None, # Text shown in Teams notification
card_version: str = ADAPTIVE_CARD_VERSION,
extra_body_elements: Optional[List[Dict[str, Any]]] = None,
extra_actions: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
"""
Constructs a JSON payload for an Adaptive Card.
Args:
title: The main title of the card (large text block).
text: The main body text of the card.
image_url: Optional URL for an image to display in the card.
image_alt_text: Alt text for the image if provided.
button_text: Optional text for an action button.
button_url: Optional URL for the action button to open.
facts: Optional dictionary of key-value pairs for a FactSet (e.g., {"Status": "Complete", "Date": "2023-10-27"}).
summary: Optional text that appears in the Teams notification toast.
If not provided, Teams might use the card's title or first text block.
card_version: The Adaptive Card schema version to use.
extra_body_elements: A list of additional raw Adaptive Card elements to add to the card's body.
Useful for advanced customization.
extra_actions: A list of additional raw Adaptive Card action elements to add to the card's actions.
Useful for advanced customization.
Returns:
A dictionary representing the Adaptive Card JSON payload.
"""
card_body: List[Dict[str, Any]] = []
card_actions: List[Dict[str, Any]] = []
# Add title and text blocks
card_body.append(_create_text_block(title, size="large", weight="bolder"))
card_body.append(_create_text_block(text, wrap=True))
# Add image if provided
if image_url:
card_body.append(_create_image(image_url, image_alt_text, size="stretch")) # Using stretch for full width in Teams
# Add facts if provided
if facts:
card_body.append(_create_fact_set(facts))
# Add action button if both text and URL are provided
if button_text and button_url:
card_actions.append(_create_action_open_url(button_text, button_url))
# Add any extra body elements
if extra_body_elements:
card_body.extend(extra_body_elements)
# Add any extra actions
if extra_actions:
card_actions.extend(extra_actions)
# Construct the base Adaptive Card structure
adaptive_card: Dict[str, Any] = {
"$schema": ADAPTIVE_CARD_SCHEMA,
"type": "AdaptiveCard",
"version": card_version,
"body": card_body,
}
if card_actions:
adaptive_card["actions"] = card_actions
# Add Teams specific properties for notification summary
if summary:
adaptive_card["msteams"] = {"summary": summary}
return adaptive_card
async def _send_adaptive_card_async_worker(
webhook_url: str,
card_payload: Dict[str, Any],
timeout: int,
session: requests.Session,
) -> Optional[requests.Response]:
"""
Worker function to send the Adaptive Card asynchronously.
Runs the blocking `requests.post` in a separate thread.
"""
try:
logger.debug(
f"Attempting to send card asynchronously to {webhook_url} with timeout {timeout}s."
)
# Use asyncio.to_thread to run blocking I/O (requests.post) in a separate thread
response = await asyncio.to_thread(
session.post, webhook_url, json=card_payload, timeout=timeout
)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
logger.info(
f"Successfully sent Adaptive Card asynchronously. Status: {response.status_code}"
)
logger.debug(f"Async response: {response.text}")
return response
except requests.exceptions.Timeout:
logger.error(
f"Request timed out while sending Adaptive Card asynchronously to {webhook_url}."
)
except requests.exceptions.ConnectionError as e:
logger.error(
f"Connection error while sending Adaptive Card asynchronously to {webhook_url}: {e}"
)
except requests.exceptions.HTTPError as e:
logger.error(
f"HTTP error {e.response.status_code} while sending Adaptive Card asynchronously to {webhook_url}: {e.response.text}"
)
except requests.exceptions.RequestException as e:
logger.error(
f"An unexpected requests error occurred while sending Adaptive Card asynchronously to {webhook_url}: {e}"
)
except Exception as e:
logger.error(
f"An unexpected error occurred in async worker while sending Adaptive Card to {webhook_url}: {e}",
exc_info=True,
)
return None
async def send_adaptive_card_to_webhook(
webhook_url: str,
title: str = "New Notification!",
text: str = "This is a default message from your Python script.",
image_url: Optional[str] = None,
image_alt_text: str = "",
button_text: Optional[str] = None,
button_url: Optional[str] = None,
facts: Optional[Dict[str, str]] = None,
summary: Optional[str] = None,
async_send: bool = False,
timeout: int = 10, # seconds
retries: int = 5,
backoff_factor: float = 0.5,
card_version: str = ADAPTIVE_CARD_VERSION,
extra_body_elements: Optional[List[Dict[str, Any]]] = None,
extra_actions: Optional[List[Dict[str, Any]]] = None,
) -> Union[Optional[requests.Response], asyncio.Task]:
"""
Sends an Adaptive Card JSON payload to a Microsoft Workflow webhook.
Args:
webhook_url: The URL of the Microsoft Workflow webhook.
title: The main title of the card.
text: The main body text of the card.
image_url: Optional URL for an image to display.
image_alt_text: Alt text for the image.
button_text: Optional text for an action button.
button_url: Optional URL for the action button to open.
facts: Optional dictionary of key-value pairs for a FactSet.
summary: Optional text for the Teams notification toast.
async_send: If True, sends the card asynchronously (non-blocking).
If False, sends synchronously (blocking).
timeout: The maximum time (in seconds) to wait for the request to complete.
retries: The number of times to retry the request on failure.
backoff_factor: The backoff factor for retries.
card_version: The Adaptive Card schema version.
extra_body_elements: A list of additional raw Adaptive Card elements for the body.
extra_actions: A list of additional raw Adaptive Card action elements.
Returns:
- If `async_send` is True: An `asyncio.Task` object. The actual
`requests.Response` (or None on failure) will be the result of this task.
- If `async_send` is False: A `requests.Response` object if successful,
or `None` if an error occurred.
"""
if not webhook_url:
logger.error("Webhook URL is required and cannot be empty.")
raise ValueError("Webhook URL cannot be empty.")
card_payload = build_adaptive_card_payload(
title=title,
text=text,
image_url=image_url,
image_alt_text=image_alt_text,
button_text=button_text,
button_url=button_url,
facts=facts,
summary=summary,
card_version=card_version,
extra_body_elements=extra_body_elements,
extra_actions=extra_actions,
)
logger.debug(f"Generated Adaptive Card Payload:\n{json.dumps(card_payload, indent=2)}")
session = _create_session_with_retries(total_retries=retries, backoff_factor=backoff_factor)
if async_send:
logger.info(f"Scheduling asynchronous send to webhook: {webhook_url}")
task = asyncio.create_task(
_send_adaptive_card_async_worker(webhook_url, card_payload, timeout, session)
)
return task
else:
logger.info(f"Sending synchronous request to webhook: {webhook_url}")
try:
response = session.post(webhook_url, json=card_payload, timeout=timeout)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
logger.info(
f"Successfully sent Adaptive Card synchronously. Status: {response.status_code}"
)
logger.debug(f"Synchronous response: {response.text}")
return response
except requests.exceptions.Timeout:
logger.error(
f"Request timed out while sending Adaptive Card synchronously to {webhook_url}."
)
except requests.exceptions.ConnectionError as e:
logger.error(
f"Connection error while sending Adaptive Card synchronously to {webhook_url}: {e}"
)
except requests.exceptions.HTTPError as e:
logger.error(
f"HTTP error {e.response.status_code} while sending Adaptive Card synchronously to {webhook_url}: {e.response.text}"
)
except requests.exceptions.RequestException as e:
logger.error(
f"An unexpected requests error occurred while sending Adaptive Card synchronously to {webhook_url}: {e}"
)
except Exception as e:
logger.error(
f"An unexpected error occurred while sending Adaptive Card to {webhook_url}: {e}",
exc_info=True,
)
return None
# --- Example Usage ---
async def main():
# Replace with your actual Microsoft Workflow Webhook URL
# IMPORTANT: Never hardcode sensitive URLs in production. Use environment variables or a config management system.
WEBHOOK_URL = os.environ.get("TEAMS_WEBHOOK_URL")
if not WEBHOOK_URL:
logger.error("TEAMS_WEBHOOK_URL environment variable not set. Please set it before running.")
logger.info("Exiting example as webhook URL is missing.")
return
logger.info("--- Starting Adaptive Card Examples ---")
# --- Example 1: Basic Synchronous Card ---
logger.info("\n--- Sending Basic Synchronous Card ---")
sync_response = await send_adaptive_card_to_webhook(
webhook_url=WEBHOOK_URL,
title="Sync Notification!",
text="This is a simple synchronous card sent directly.",
summary="A new synchronous message has arrived!"
)
if sync_response:
logger.info(f"Synchronous card sent. Response status: {sync_response.status_code}")
else:
logger.warning("Synchronous card failed to send.")
# Introduce a small delay to separate messages in Teams/webhook history
await asyncio.sleep(2)
# --- Example 2: Synchronous Card with Image and Button ---
logger.info("\n--- Sending Synchronous Card with Image and Button ---")
sync_image_button_response = await send_adaptive_card_to_webhook(
webhook_url=WEBHOOK_URL,
title="Project Update!",
text="The new feature development is 80% complete. Click below for details.",
image_url="https://adaptivecards.io/content/cats1.png",
image_alt_text="A cute cat picture",
button_text="View Project Dashboard",
button_url="https://www.microsoft.com",
facts={
"Project Lead": "Jane Doe",
"Status": "In Progress",
"Target Date": "2024-01-15"
},
summary="Project X Update: 80% complete!"
)
if sync_image_button_response:
logger.info(f"Synchronous image card sent. Response status: {sync_image_button_response.status_code}")
else:
logger.warning("Synchronous image card failed to send.")
# Introduce a small delay
await asyncio.sleep(2)
# --- Example 3: Asynchronous Card ---
logger.info("\n--- Sending Asynchronous Card ---")
async_task = await send_adaptive_card_to_webhook(
webhook_url=WEBHOOK_URL,
title="Async Job Started!",
text="A long-running background job has been initiated. You'll be notified upon completion.",
async_send=True,
timeout=5, # Shorter timeout for async example
summary="Async job initiated!"
)
# The async_task is returned immediately. We don't wait for its completion here,
# demonstrating non-blocking behavior.
logger.info(f"Asynchronous send initiated. Task: {async_task}")
logger.info("Main script continues immediately after scheduling the async task.")
# To actually *see* the result of the async task (e.g., success/failure),
# you would await it later, or have it log its own outcome.
# For this example, let's wait for it for demonstration purposes.
await async_task
# Now async_task has completed, and its result (the requests.Response or None) is available
async_response = async_task.result()
if async_response:
logger.info(f"Asynchronous task completed. Response status: {async_response.status_code}")
else:
logger.warning("Asynchronous task completed with failure.")
# Introduce a small delay
await asyncio.sleep(2)
# --- Example 4: Card with Custom Body Elements (Advanced) ---
logger.info("\n--- Sending Card with Custom Body Elements ---")
custom_card_response = await send_adaptive_card_to_webhook(
webhook_url=WEBHOOK_URL,
title="Custom Card Example",
text="This card includes a custom text block with different styling.",
summary="See custom card!",
extra_body_elements=[
_create_text_block(
"This is an important highlight!",
size="medium",
weight="bolder",
color="attention",
is_subtle=False
),
_create_text_block(
"And here's some subtle, smaller text.",
size="small",
is_subtle=True
)
]
)
if custom_card_response:
logger.info(f"Custom card sent. Response status: {custom_card_response.status_code}")
else:
logger.warning("Custom card failed to send.")
logger.info("\n--- Adaptive Card Examples Finished ---")
if __name__ == "__main__":
# To run the async examples, you need to use asyncio.run()
asyncio.run(main())
How to Use:
Save the Code: Save the code above as a Python file (e.g., send_card.py).
Get Your Webhook URL:
Go to your Teams channel.
Click ... next to the channel name.
Select Connectors.
Search for Incoming Webhook and click Add.
Click Add again.
Give it a name and optionally upload an image.
Click Create.
Copy the generated Webhook URL. It will look something like https://outlook.office.com/webhook/xxxxxxxxx....
Set Environment Variable:
It's best practice not to hardcode sensitive information. Set your webhook URL as an environment variable:
Windows (CMD):set TEAMS_WEBHOOK_URL="YOUR_WEBHOOK_URL_HERE"
Windows (PowerShell):$env:TEAMS_WEBHOOK_URL="YOUR_WEBHOOK_URL_HERE"
(Replace YOUR_WEBHOOK_URL_HERE with the URL you copied).
Run the Script:
bash
python send_card.py
You will see log messages in your console and in the adaptive_card_sender.log file, and the Adaptive Cards will appear in your Teams channel.
Explanations and Design Choices:
loguru: Chosen for its simplicity, powerful features (like auto-rotation, compression, and structured logging), and clear output. It's configured to log to both a file (adaptive_card_sender.log) and the console.
_create_session_with_retries: Encapsulates the requests.Session setup with urllib3.Retry. This is crucial for production systems to handle transient network issues or server-side throttling gracefully.
total_retries: How many times to retry.
backoff_factor: Controls the delay between retries (exponential backoff).
status_forcelist: Which HTTP status codes should trigger a retry (e.g., 5xx server errors).
_create_text_block, _create_image, _create_fact_set, _create_action_open_url, _create_action_set: These helper functions make it easy to build Adaptive Card JSON elements without remembering the exact structure every time. They also provide sensible defaults for common properties (like text size/weight, image alignment).
build_adaptive_card_payload: This is the core function for constructing the Adaptive Card. It takes high-level parameters (title, text, image, button, facts) and assembles them into the correct JSON structure, adhering to the Adaptive Card schema.
summary: This msteams property is very useful as it controls the text shown in the Teams notification/toast when the card arrives.
extra_body_elements and extra_actions: Provide an escape hatch for advanced users to inject arbitrary Adaptive Card elements directly if the predefined helpers aren't sufficient.
send_adaptive_card_to_webhook (Async and Sync):
Synchronous (async_send=False): The default behavior. It directly calls session.post and waits for the response. This is suitable for simple scripts or when you need to immediately process the result of the webhook call.
Asynchronous (async_send=True): This is where asyncio comes in. Since requests is a synchronous library, asyncio.to_thread is used to run the session.post call in a separate thread from the event loop. This makes the send_adaptive_card_to_webhook function non-blocking, allowing your main application to continue processing other tasks while the HTTP request is being handled in the background. It returns an object.
Error Handling: Extensive try...except blocks are used to catch various requests exceptions (timeout, connection errors, HTTP errors) and log them appropriately, making the code robust against network issues.
main() function: Demonstrates both synchronous and asynchronous usage with various card configurations.
Environment Variables: Using os.environ.get("TEAMS_WEBHOOK_URL") encourages best practices for managing sensitive configuration.