Skip to main content

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

  1. Activity Extensions: Adds helper methods to Bot Framework activities
  2. Image Processing: Handles Teams image attachments and encoding
  3. Telemetry: Comprehensive event tracking with user identification
  4. 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 team
  • Message Received: When users send messages
  • Response Sent: When bot responds
  • Command Used: When specific commands are executed

User Properties

Automatically collected user properties:

  • teams_id: Microsoft Teams user ID
  • aad_id: Azure Active Directory ID
  • email: User email address
  • name: Display name
  • conversation_id: Teams conversation ID
  • platform: 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

📞 Support

🏷️ 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

teams_bot_utils-1.0.1.tar.gz (19.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

teams_bot_utils-1.0.1-py3-none-any.whl (17.0 kB view details)

Uploaded Python 3

File details

Details for the file teams_bot_utils-1.0.1.tar.gz.

File metadata

  • Download URL: teams_bot_utils-1.0.1.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

Hashes for teams_bot_utils-1.0.1.tar.gz
Algorithm Hash digest
SHA256 4d51c480c806a3c941c4b43c752cf94327b6606622679cff5b16848bfdbc1844
MD5 c7880bb3973f9cf6022b5aeab4a27609
BLAKE2b-256 b87ea4a981b31ca1972b2887ec3bfb04aa5fe788d3864a5bcae27ae94a7ec3a7

See more details on using hashes here.

File details

Details for the file teams_bot_utils-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for teams_bot_utils-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a44797cd288bcf545bcd8a782461dd33e3fd20c12aac8726defa2d4406a0e118
MD5 e597fda33263dc133a13841e51191322
BLAKE2b-256 257c1a594b3487c8ee15cbf9117b6954d53c53486451637aa0c22ea25df7dd12

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page