Skip to main content

Pydantic Models for working with the Slack API

Project description

slack-models

PyPI version Python 3.12+ License Documentation

Comprehensive Pydantic models for working with the Slack API

slack-models provides type-safe, validated data structures for Slack API integration, making it easier to build robust Slack applications with proper error handling and IDE support.

🚀 Features

  • Complete Coverage: Models for all major Slack events, objects, webhook payloads, and Block Kit elements
  • Type Safety: Full type annotations with Python 3.12+ modern type hints
  • Validation: Automatic data validation using Pydantic 2.x
  • IDE Support: Excellent autocomplete and type checking
  • Event Parsing: Convenient utilities for parsing webhook payloads
  • Standards Compliant: Strict adherence to official Slack API specifications

📦 Installation

pip install slack-models

Requirements:

  • Python 3.12+
  • pydantic >=2.11.3,<3

🔧 Quick Start

Basic Usage

from slack_models import parse_event, SlackEventCallback, MessageEvent

# Parse a webhook payload
webhook_data = {
    "type": "event_callback",
    "event": {
        "type": "message",
        "channel": "C1234567890",
        "user": "U1234567890",
        "text": "Hello, world!",
        "ts": "1234567890.123456"
    },
    "team_id": "T1234567890",
    "api_app_id": "A1234567890"
}

# Parse and validate
event = parse_event(webhook_data)
if isinstance(event, SlackEventCallback):
    if isinstance(event.event, MessageEvent):
        print(f"Message: {event.event.text}")
        print(f"Channel: {event.event.channel}")
        print(f"User: {event.event.user}")

Event Handling

from slack_models import (
    parse_event, SlackEventCallback, MessageEvent,
    ReactionAddedEvent, ChannelCreatedEvent
)

def handle_slack_event(payload: dict):
    """Handle incoming Slack events with type safety."""
    event = parse_event(payload)

    if isinstance(event, SlackEventCallback):
        if isinstance(event.event, MessageEvent):
            print(f"New message: {event.event.text}")
        elif isinstance(event.event, ReactionAddedEvent):
            print(f"Reaction added: {event.event.reaction}")
        elif isinstance(event.event, ChannelCreatedEvent):
            print(f"Channel created: {event.event.channel.name}")

Working with Models

from slack_models import User, Channel, MessageEvent

# Create and validate user data
user = User(
    id="U1234567890",
    name="john.doe",
    real_name="John Doe",
    profile={
        "email": "john.doe@example.com",
        "display_name": "John",
        "first_name": "John",
        "last_name": "Doe"
    }
)

# Access user information with full type safety
print(f"User: {user.name} ({user.real_name})")
print(f"Email: {user.profile.email}")

📚 Documentation

🎯 Supported Events

slack-models supports all major Slack event types:

Message Events

  • MessageEvent: Standard messages, bot messages, threaded messages
  • AppMentionEvent: App mentions in channels
  • MessageEdited: Message edit events

Reaction Events

  • ReactionAddedEvent: Reaction additions
  • ReactionRemovedEvent: Reaction removals

Channel Events

  • ChannelCreatedEvent: New channel creation
  • ChannelDeletedEvent: Channel deletion
  • ChannelRenameEvent: Channel name changes

Team Events

  • TeamJoinEvent: New team member joins

File Events

  • FileCreatedEvent: File uploads
  • FileDeletedEvent: File deletions

Block Kit Models

  • Blocks: SectionBlock, DividerBlock, ImageBlock, ActionsBlock, ContextBlock, InputBlock, HeaderBlock, VideoBlock, RichTextBlock, FileBlock
  • Elements: ButtonElement, StaticSelectElement, CheckboxesElement, DatePickerElement, PlainTextInputElement, and more
  • Composition Objects: TextObject, ConfirmationDialog, Option, OptionGroup

Webhook Types

  • SlackEventCallback: Standard event callbacks
  • SlackUrlVerification: URL verification challenges
  • SlackAppRateLimited: Rate limiting notifications

Error Handling

from pydantic import ValidationError
from slack_models import parse_event

try:
    event = parse_event(webhook_data)
    # Process event
except ValidationError as e:
    print(f"Invalid payload: {e}")
    # Handle validation errors
except Exception as e:
    print(f"Processing error: {e}")
    # Handle other errors

🧪 Development

Setup

# Clone the repository
git clone https://github.com/gmr/slack-models.git
cd slack-models

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install development dependencies
pip install -e '.[dev]'

# Install pre-commit hooks
pre-commit install

Testing

# Run tests
pytest

# Run tests with coverage
pytest --cov=slack_models --cov-report=html

# Run linting
ruff check .

# Run type checking
mypy src/slack_models

Documentation

# Build documentation
mkdocs build

# Serve documentation locally
mkdocs serve

🤝 Contributing

Contributions are welcome! Please see our Contributing Guide for details.

Development Workflow

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run the test suite and linting
  6. Submit a pull request

📄 License

This project is licensed under the BSD-3-Clause License. See the LICENSE file for details.

🙏 Acknowledgments

  • Built for Slack bot projects at AWeber
  • Powered by Pydantic for data validation
  • Inspired by the Slack API documentation

📞 Support


Made with ❤️ by Gavin M. Roy at AWeber

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

slack_models-1.1.0.tar.gz (54.1 kB view details)

Uploaded Source

Built Distribution

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

slack_models-1.1.0-py3-none-any.whl (14.0 kB view details)

Uploaded Python 3

File details

Details for the file slack_models-1.1.0.tar.gz.

File metadata

  • Download URL: slack_models-1.1.0.tar.gz
  • Upload date:
  • Size: 54.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for slack_models-1.1.0.tar.gz
Algorithm Hash digest
SHA256 5c5bfbc8ec723c64a00ccac4e3cf63c20775faec111fb6eb30826d75716dc839
MD5 e800ddd2e79448e7134a9fd69f1b3059
BLAKE2b-256 3b395283e6f5cabdf20fbd950633c38fb2e995ab4f088b776af8674771df6db1

See more details on using hashes here.

File details

Details for the file slack_models-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: slack_models-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 14.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for slack_models-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 82aed9ef201dbd3c944d0e345dd2cfcfecfe4dd786c3de607b35d994230d2414
MD5 91e20cd5922d6119b8c3de61686e6956
BLAKE2b-256 549a322de86329c335b0d212cf6c49222efd26947ef926693710ca5a4d0ebe23

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