PyMSTeams
PyMSTeams is a Python library designed to format messages and post them to Microsoft Teams via webhooks. It simplifies the creation of rich Connector Cards with text, sections, facts, images, and actions. The current version is 0.2.5, and it has an active but irregular release cadence, with updates typically addressing minor bugs, dependency bumps, or new features.
Warnings
- breaking Sending messages exceeding the Microsoft Teams API size limit (typically 28KB per card) will now raise a `TeamsWebhookException`.
- gotcha The `send()` method's success validation was relaxed in recent versions. Previously, it strictly checked for HTTP 200 OK. Now, it validates on any 2xx HTTP status code (e.g., 202 Accepted).
- breaking Versions 0.2.5 and higher of `pymsteams` explicitly require Python 3.9 or newer.
Install
-
pip install pymsteams
Imports
- Teams
import pymsteams connector = pymsteams.Teams(webhook_url)
Quickstart
import pymsteams
import os
# Get your Microsoft Teams webhook URL from an environment variable
# Example: https://outlook.office.com/webhook/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx@xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/IncomingWebhook/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
webhook_url = os.environ.get('TEAMS_WEBHOOK_URL', '')
if not webhook_url:
print("Error: TEAMS_WEBHOOK_URL environment variable not set.")
else:
myTeamsMessage = pymsteams.Teams(webhook_url)
myTeamsMessage.text("Hello, Teams! This is a test message from PyMSTeams.")
myTeamsMessage.title("PyMSTeams Quickstart Alert")
myTeamsMessage.addSection(
pymsteams.cardsection()
.addFact("Status", "Success")
.addFact("Environment", "Production")
.addFact("Timestamp", "2024-04-09 10:30:00")
)
try:
myTeamsMessage.send()
print("Message sent successfully!")
except Exception as e:
print(f"Failed to send message: {e}")