A comprehensive Python library for Microsoft Teams bot development
Project description
Teams Bot Utils
A comprehensive Python library for Microsoft Teams bot development, providing utilities for message processing, image handling, telemetry tracking, and HTTP client management with connection pooling.
🚀 Features
- Message Analysis: Analyze Teams messages for text, images, and file attachments
- Image Processing: Download and encode images from Teams attachments
- Telemetry Integration: Track bot usage and user interactions with Mixpanel
- HTTP Client Management: Efficient connection pooling for external API calls
- Activity Extensions: Enhanced functionality for Bot Framework activities
- Async Support: Full async/await support for optimal performance
📦 Installation
pip install teams-bot-utils
🔧 Requirements
- Python 3.8+
- botbuilder-core>=4.14.0
- httpx>=0.24.0
- mixpanel>=2.2.0
- pydantic>=1.8.0
🎯 Quick Start
Message Content Analysis
from teams_bot_utils.extensions import extend_activity_class
from botbuilder.schema import Activity
# Extend the Activity class with helper methods
extend_activity_class()
# Analyze message contents
activity = Activity(text="Hello world", attachments=[...])
has_text, file_count, image_count, extensions = activity.check_message_contents()
print(f"Has text: {has_text}")
print(f"Files: {file_count}, Images: {image_count}")
print(f"File extensions: {extensions}")
Image Processing
from teams_bot_utils.images.processing import process_image_attachment, extract_image_from_activity
# Process a single image attachment
base64_image = await process_image_attachment(attachment)
# Extract first image from activity
image_data = await extract_image_from_activity(activity.attachments)
if image_data:
print(f"Found image: {len(image_data)} bytes")
Telemetry Tracking
from teams_bot_utils.telemetry.mixpanel_telemetry import BotTelemetry
# Initialize telemetry
telemetry = BotTelemetry(token="your_mixpanel_token")
# Track user interactions
telemetry.track_message_received(
user_id="user123",
session_id="session456",
has_text=True,
has_image=False,
text_length=50
)
telemetry.track_response_sent(
user_id="user123",
session_id="session456",
response_time_ms=250,
success=True
)
# Advanced tracking with activity context
telemetry.identify_and_track(
event="Custom Event",
activity=teams_activity,
properties={"custom_property": "value"}
)
HTTP Client with Connection Pooling
from teams_bot_utils.utils.http_client import HttpClient
# Create HTTP client with connection pooling
client = HttpClient(
base_url="https://api.example.com",
headers={"Authorization": "Bearer token"},
timeout=30.0
)
# Make requests
response = await client.get("/endpoint", params={"key": "value"})
data = await client.post("/submit", json_data={"data": "value"})
# Clean up (optional - clients auto-manage connections)
from teams_bot_utils.utils.http_client import close_all_clients
await close_all_clients()
📚 Detailed Usage
Message Content Analysis
The library extends the Bot Framework's Activity class with enhanced message analysis:
from teams_bot_utils.extensions import extend_activity_class
# Call once at startup
extend_activity_class()
async def on_message_activity(self, turn_context):
activity = turn_context.activity
# Analyze message contents
has_text, file_count, image_count, extensions = activity.check_message_contents()
if has_text:
print(f"Message: {activity.text}")
if image_count > 0:
print(f"Found {image_count} images")
# Process images
image_data = await extract_image_from_activity(activity.attachments)
if file_count > 0:
print(f"Found {file_count} files with extensions: {extensions}")
Advanced Image Processing
Handle various Teams attachment types:
from teams_bot_utils.images.processing import (
process_image_attachment,
download_and_encode_image,
extract_image_from_activity
)
# Process specific attachment types
for attachment in activity.attachments:
if attachment.content_type == "application/vnd.microsoft.teams.file.download.info":
# Teams file download
base64_data = await process_image_attachment(attachment)
elif attachment.content_type.startswith("image/"):
# Direct image attachment
base64_data = await process_image_attachment(attachment)
# Download from URL
image_data = await download_and_encode_image("https://example.com/image.png")
Comprehensive Telemetry
Track detailed bot analytics:
from teams_bot_utils.telemetry.mixpanel_telemetry import BotTelemetry
telemetry = BotTelemetry(
token="your_mixpanel_token",
api_secret="your_api_secret" # Optional, for identity merging
)
# Track bot installation
telemetry.track_bot_installed(
team_id="team123",
user_id="user456",
channel_id="channel789"
)
# Track commands
telemetry.track_command_used(
user_id="user123",
command_name="help",
success=True
)
# Set user profiles
telemetry.set_user_profile("user123", {
"name": "John Doe",
"email": "john@company.com",
"team": "Engineering"
})
# Identity merging
telemetry.merge_user_identities("user123", "alt_id456")
Connection Pool Management
Efficiently manage HTTP connections:
from teams_bot_utils.utils.connection_pool import get_http_client
# Get shared client
client = await get_http_client(
base_url="https://api.service.com",
headers={"API-Key": "secret"},
timeout=30.0,
client_id="my_service",
max_connections=100,
max_keepalive_connections=20
)
# Use client
response = await client.get("/data")
# Cleanup when shutting down
from teams_bot_utils.utils.connection_pool import close_all_clients
await close_all_clients()
HTTP Client Class
For more structured API interactions:
from teams_bot_utils.utils.http_client import HttpClient
class MyAPIClient(HttpClient):
def __init__(self, api_key: str):
super().__init__(
base_url="https://api.myservice.com",
headers={"Authorization": f"Bearer {api_key}"},
timeout=30.0,
pool_key="my_api"
)
async def get_user_data(self, user_id: str):
return await self.get(f"/users/{user_id}")
async def create_record(self, data: dict):
return await self.post("/records", json_data=data)
# Usage
api = MyAPIClient("your_api_key")
user_data = await api.get_user_data("123")
result = await api.create_record({"name": "test"})
🔧 Configuration
Environment Variables
Set these environment variables for optimal configuration:
# Mixpanel Configuration
MIXPANEL_TOKEN=your_mixpanel_project_token
MIXPANEL_API_SECRET=your_mixpanel_api_secret
# HTTP Client Settings
HTTP_TIMEOUT=30
MAX_CONNECTIONS=100
MAX_KEEPALIVE_CONNECTIONS=20
Logging
Configure logging to see detailed operation information:
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Library modules use standard Python logging
logger = logging.getLogger('teams_bot_utils')
🏗️ Architecture
Module Structure
teams_bot_utils/
├── extensions.py # Activity class extensions
├── images/
│ └── processing.py # Image processing utilities
├── telemetry/
│ └── mixpanel_telemetry.py # Mixpanel integration
└── utils/
├── connection_pool.py # Shared HTTP client pool
└── http_client.py # HTTP client class
Key Components
- Activity Extensions: Adds helper methods to Bot Framework activities
- Image Processing: Handles Teams image attachments and encoding
- Telemetry: Comprehensive event tracking with user identification
- HTTP Utilities: Connection pooling and structured API clients
🚀 Performance Features
- Connection Pooling: Reuse HTTP connections for better performance
- Async Operations: Full async/await support throughout
- Efficient Image Processing: Streaming download and encoding
- Lazy Initialization: Clients created only when needed
- Automatic Cleanup: Built-in resource management
🔍 Error Handling
The library includes comprehensive error handling:
try:
image_data = await download_and_encode_image(url)
if not image_data:
print("Failed to download image")
except Exception as e:
print(f"Error processing image: {e}")
# Telemetry errors are logged but don't interrupt execution
success = telemetry.track("event", "user", {"data": "value"})
if not success:
print("Telemetry tracking failed")
🧪 Testing
# Install development dependencies
pip install teams-bot-utils[dev]
# Run tests
pytest
# Run with coverage
pytest --cov=teams_bot_utils
# Type checking
mypy teams_bot_utils/
# Code formatting
black teams_bot_utils/
📈 Monitoring and Analytics
Mixpanel Events
The library automatically tracks these events:
Bot Installed: When bot is added to a teamMessage Received: When users send messagesResponse Sent: When bot respondsCommand Used: When specific commands are executed
User Properties
Automatically collected user properties:
teams_id: Microsoft Teams user IDaad_id: Azure Active Directory IDemail: User email addressname: Display nameconversation_id: Teams conversation IDplatform: Always "MS Teams"$last_seen: Last activity timestamp
🤝 Contributing
Contributions are welcome! Please feel free to submit issues, feature requests, or pull requests.
Development Setup
# Clone the repository
git clone <repository-url>
cd teams-bot-utils
# Install in development mode
pip install -e ".[dev]"
# Install pre-commit hooks
pre-commit install
# Run tests
pytest
📝 License
This project is licensed under the MIT License - see the LICENSE file for details.
🔗 Links
- GitHub: https://github.com/shubham7995/teams-bot-utils
- PyPI: https://pypi.org/project/teams-bot-utils/
- Issues: https://github.com/shubham7995/teams-bot-utils/issues
- Documentation: https://github.com/shubham7995/teams-bot-utils#readme
📞 Support
- Email: shubham.shinde@ecolab.com
- GitHub Issues: For bug reports and feature requests
🏷️ Keywords
microsoft teams, bot framework, telemetry, image processing, http client, connection pooling, mixpanel, async, bot development, teams bot
Built with ❤️ for the Microsoft Teams bot development community
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file teams_bot_utils-1.0.0.tar.gz.
File metadata
- Download URL: teams_bot_utils-1.0.0.tar.gz
- Upload date:
- Size: 19.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ebd7bc3cb5ca364600215ddc597e9b5d9001fdc0f4c40dfd03e30f21e514d5fa
|
|
| MD5 |
6c928210a860e3926d15bbac7ab8a18e
|
|
| BLAKE2b-256 |
8149b62c2a5a00b1bfa9f95584e29a8034291abc8eae909d905868b3ec36b156
|
File details
Details for the file teams_bot_utils-1.0.0-py3-none-any.whl.
File metadata
- Download URL: teams_bot_utils-1.0.0-py3-none-any.whl
- Upload date:
- Size: 17.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
898eb74bfa9edfa51bb105acb1dd8b2a64266a7b495fd1f3603c35820ad855b7
|
|
| MD5 |
8574cfb4c9b7d23103d53b1757eb43f7
|
|
| BLAKE2b-256 |
e2235b0852ba411d098903f435ffc3c66067adb0d32cf713b1f0d79a3f25cd6d
|