Modern Telegram notification bot library for Python projects
Project description
Telegram Notification Bot 🤖
A modern, type-safe Python library for sending notifications through Telegram bots. Built with the latest aiogram 3.x and Pydantic 2.x for maximum reliability and developer experience.
✨ Features
- 🔒 Type Safety: Full type annotations with mypy support
- 🚀 Modern: Built on aiogram 3.x and Pydantic 2.x
- 🛡️ Robust Error Handling: Comprehensive exception handling with custom error types
- 📝 Validation: Input validation using Pydantic models
- 🎯 Multiple Formats: Send text, photos, and documents
- 🔧 Flexible Configuration: Support for various chat ID formats
- 🧪 Well Tested: Comprehensive test suite with high coverage
- 📦 Zero Dependencies: Only requires aiogram and pydantic
🚀 Installation
pip install tg-notification-bot
For development:
pip install tg-notification-bot[dev]
📖 Quick Start
Basic Usage
import asyncio
from tg_notification_bot import TelegramNotificationBot
async def main():
# Initialize with token and chat ID
bot = TelegramNotificationBot("YOUR_BOT_TOKEN", "YOUR_CHAT_ID")
# Send a simple message
await bot.send_message("Hello, World! 🌍")
# Send a photo
await bot.send_photo("path/to/photo.jpg", caption="Check this out!")
# Send a document
await bot.send_document("path/to/document.pdf", caption="Important file")
# Don't forget to close the session
await bot.close()
# Run the example
asyncio.run(main())
Using Configuration Object
import asyncio
from tg_notification_bot import TelegramNotificationBot, NotificationConfig
async def main():
# Create configuration
config = NotificationConfig(
token="YOUR_BOT_TOKEN",
chat_id="YOUR_CHAT_ID",
parse_mode="Markdown",
disable_notification=True
)
# Initialize bot with config
bot = TelegramNotificationBot(config)
await bot.send_message("*Bold text* with _italic_")
await bot.close()
asyncio.run(main())
Context Manager (Recommended)
import asyncio
from tg_notification_bot import TelegramNotificationBot
async def main():
async with TelegramNotificationBot("YOUR_BOT_TOKEN", "YOUR_CHAT_ID") as bot:
await bot.send_message("Message sent safely! ✅")
# Session automatically closed
asyncio.run(main())
🔧 Advanced Usage
Structured Data with Pydantic Models
import asyncio
from tg_notification_bot import (
TelegramNotificationBot,
MessageData,
PhotoData,
DocumentData
)
async def main():
async with TelegramNotificationBot("YOUR_BOT_TOKEN", "YOUR_CHAT_ID") as bot:
# Structured message
message = MessageData(
text="<b>Important</b> notification!",
parse_mode="HTML",
disable_notification=False
)
await bot.send_message(message)
# Structured photo
photo = PhotoData(
photo="https://example.com/image.jpg",
caption="Remote image",
parse_mode="Markdown"
)
await bot.send_photo(photo)
asyncio.run(main())
File Handling
import asyncio
from pathlib import Path
from io import BytesIO
from tg_notification_bot import TelegramNotificationBot
async def main():
async with TelegramNotificationBot("YOUR_BOT_TOKEN", "YOUR_CHAT_ID") as bot:
# Local file
await bot.send_photo(Path("image.jpg"))
# URL
await bot.send_photo("https://example.com/photo.jpg")
# File-like object
buffer = BytesIO(b"fake image data")
buffer.name = "generated.jpg"
await bot.send_photo(buffer, caption="Generated image")
asyncio.run(main())
Error Handling
import asyncio
from tg_notification_bot import (
TelegramNotificationBot,
ChatNotFoundError,
BotBlockedError,
RateLimitError,
TelegramNotificationError
)
async def main():
async with TelegramNotificationBot("YOUR_BOT_TOKEN", "YOUR_CHAT_ID") as bot:
try:
await bot.send_message("Test message")
except ChatNotFoundError as e:
print(f"Chat not found: {e.chat_id}")
except BotBlockedError as e:
print(f"Bot blocked in chat: {e.chat_id}")
except RateLimitError as e:
print(f"Rate limited. Retry after: {e.retry_after} seconds")
except TelegramNotificationError as e:
print(f"General error: {e}")
asyncio.run(main())
🔐 Configuration
Environment Variables
# .env file
TG_BOT_TOKEN=your_bot_token_here
TG_CHAT_ID=your_chat_id_here
import os
from tg_notification_bot import TelegramNotificationBot
# Load from environment
bot = TelegramNotificationBot(
token=os.getenv("TG_BOT_TOKEN"),
chat_id=os.getenv("TG_CHAT_ID")
)
Chat ID Formats
The library supports various chat ID formats:
123456789- User ID-123456789- Group chat ID-100123456789- Supergroup/channel ID@username- Public chat username
The bot automatically tries different formats if the initial one fails.
🧪 Testing
Run the test suite:
# Install development dependencies
pip install -e .[dev]
# Run tests
pytest
# Run tests with coverage
pytest --cov=tg_notification_bot --cov-report=html
# Type checking
mypy tg_notification_bot
# Linting
flake8 tg_notification_bot
black --check tg_notification_bot
isort --check-only tg_notification_bot
📝 API Reference
Classes
TelegramNotificationBot
Main bot class for sending notifications.
Constructor:
TelegramNotificationBot(config: NotificationConfig | str, chat_id: str | int = None)
Methods:
send_message(message: str | MessageData, chat_id: str | int = None) -> Nonesend_photo(photo: str | Path | IO | PhotoData, caption: str = None, chat_id: str | int = None) -> Nonesend_document(document: str | Path | IO | DocumentData, caption: str = None, chat_id: str | int = None) -> Noneclose() -> None
Configuration Models
NotificationConfig- Bot configurationMessageData- Message parametersPhotoData- Photo parametersDocumentData- Document parameters
Exceptions
TelegramNotificationError- Base exceptionChatNotFoundError- Chat not foundBotBlockedError- Bot blocked by userRateLimitError- Rate limit exceededInvalidChatIdError- Invalid chat ID format
🛠️ Development
Setup Development Environment
# Clone the repository
git clone https://github.com/yourusername/tg-notification-bot.git
cd tg-notification-bot
# 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
Code Style
This project uses:
- Black for code formatting
- isort for import sorting
- flake8 for linting
- mypy for type checking
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
pytest) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
📊 Changelog
v0.1.0 (2024-XX-XX)
- 🎉 Initial release
- ✨ Full type safety with mypy support
- 🚀 Modern aiogram 3.x and Pydantic 2.x
- 🛡️ Comprehensive error handling
- 📝 Complete test coverage
- 📚 Full documentation
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
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 tg_notification_bot-0.3.0.tar.gz.
File metadata
- Download URL: tg_notification_bot-0.3.0.tar.gz
- Upload date:
- Size: 13.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e2a12db6d6ac6571c0fd3fb1806fdd5770c45fcaf9c96420700b027b1574fc69
|
|
| MD5 |
464280147ada21a56de1c4762f08f39f
|
|
| BLAKE2b-256 |
6e606af84b5aa38c663a21bac5b56908e5bdb1e6ebb3195c043aed5980a1d9c1
|
File details
Details for the file tg_notification_bot-0.3.0-py3-none-any.whl.
File metadata
- Download URL: tg_notification_bot-0.3.0-py3-none-any.whl
- Upload date:
- Size: 8.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
afe8e4f084c605cae07f913eeafeac5f621d2b673fdc15ef961af7d035d29d6f
|
|
| MD5 |
f05b48bc2980818447d3f4ee8a5e2657
|
|
| BLAKE2b-256 |
1edc31cb02d3a80d6d6b7f169a65d7dee0ecdcead6924a12130ba97d1c9c6f98
|