Skip to main content

A modern, asynchronous Telegram Bot API library with advanced handler capabilities

Project description

Gpgram

A modern, asynchronous Telegram Bot API library with advanced handler capabilities, inspired by python-telegram-bot and aiogram.

Features

  • 🚀 Fully asynchronous using Python's asyncio
  • 🧩 Clean, intuitive API design for easy bot development
  • 🔄 Advanced routing system for handling updates
  • 🔍 Flexible filter system for message handling
  • 🔌 Middleware support for pre and post-processing updates
  • 🛠️ Utility functions for common tasks
  • 📝 Type hints for better IDE support
  • 🧪 Pydantic integration for data validation
  • 🔒 Error handling with custom exceptions

Installation

pip install gpgram

Quick Start

Here's a simple echo bot example:

import asyncio
import logging
import os

from gpgram import Bot, Dispatcher, Router, CommandFilter

# Configure logging
logging.basicConfig(level=logging.INFO)

# Create a router for message handlers
router = Router()

@router.message(CommandFilter('start'))
async def start_command(message, bot):
    """Handle the /start command."""
    await bot.send_message(
        chat_id=message.chat.id,
        text=f"Hello, {message.from_user.full_name}! I'm a simple bot."
    )

@router.message()
async def echo_message(message, bot):
    """Echo all messages."""
    if message.text:
        await bot.send_message(
            chat_id=message.chat.id,
            text=f"You said: {message.text}"
        )

async def main():
    # Create a bot instance
    bot = Bot(token=os.getenv('TELEGRAM_BOT_TOKEN'))

    # Create a dispatcher
    dp = Dispatcher(bot=bot)

    # Register the router
    dp.register_router(router)

    # Start polling
    await dp.run_polling()

if __name__ == '__main__':
    asyncio.run(main())

Advanced Usage

Using Filters

from gpgram import TextFilter, RegexFilter, ChatTypeFilter

# Text filter
@router.message(TextFilter("hello", ignore_case=True))
async def hello_message(message, bot):
    await bot.send_message(
        chat_id=message.chat.id,
        text="Hello to you too!"
    )

# Regex filter
@router.message(RegexFilter(r"^[0-9]+$"))
async def number_message(message, bot):
    await bot.send_message(
        chat_id=message.chat.id,
        text="That's a number!"
    )

# Chat type filter
@router.message(ChatTypeFilter("private"))
async def private_message(message, bot):
    await bot.send_message(
        chat_id=message.chat.id,
        text="This is a private chat"
    )

Using Inline Keyboards

from gpgram import InlineKeyboardBuilder

@router.message(CommandFilter('menu'))
async def menu_command(message, bot):
    # Create an inline keyboard
    keyboard = InlineKeyboardBuilder()
    keyboard.add("Option 1", callback_data="option_1")
    keyboard.add("Option 2", callback_data="option_2")
    keyboard.row()
    keyboard.add("Option 3", callback_data="option_3")

    await bot.send_message(
        chat_id=message.chat.id,
        text="Please select an option:",
        reply_markup=keyboard.build()
    )

@router.callback_query()
async def handle_callback_query(callback_query, bot):
    # Answer the callback query
    await bot.answer_callback_query(
        callback_query_id=callback_query.id,
        text=f"You clicked: {callback_query.data}"
    )

    # Send a response based on the callback data
    await bot.send_message(
        chat_id=callback_query.message.chat.id,
        text=f"You selected: {callback_query.data}"
    )

Using Middleware

from gpgram import BaseMiddleware

class LoggingMiddleware(BaseMiddleware):
    """Middleware for logging updates."""

    async def on_pre_process_update(self, update, data):
        """Log updates before processing."""
        print(f"Received update: {update.update_id}")

    async def on_post_process_update(self, update, data, handler_result):
        """Log updates after processing."""
        print(f"Processed update: {update.update_id}")

# Register the middleware
dp.register_middleware(LoggingMiddleware())

Error Handling

# Error handler
async def error_handler(exception, update):
    """Handle errors."""
    print(f"Error processing update {update.update_id}: {exception}")

# Register the error handler
dp.register_error_handler(error_handler)

Examples

Check out the examples directory for more detailed examples:

  • simple_bot.py - A simple bot with basic commands
  • advanced_bot.py - An advanced bot with inline keyboards, middleware, and error handling
  • echo_bot.py - A basic echo bot
  • inline_keyboard_bot.py - A bot demonstrating inline keyboards

Documentation

For more detailed documentation, see the docstrings in the code or visit our documentation website.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

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

gpgram-0.1.0.tar.gz (28.1 kB view details)

Uploaded Source

Built Distribution

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

gpgram-0.1.0-py3-none-any.whl (30.7 kB view details)

Uploaded Python 3

File details

Details for the file gpgram-0.1.0.tar.gz.

File metadata

  • Download URL: gpgram-0.1.0.tar.gz
  • Upload date:
  • Size: 28.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for gpgram-0.1.0.tar.gz
Algorithm Hash digest
SHA256 3532b3505aa2235992ec6bfb889fe0720730c3541649b3b96c973537e0711a67
MD5 a862921e8426ca6c284f1a955aaf948c
BLAKE2b-256 5bad0e973d5b20bc10af2812bc9873fa0e3112e03b48a2973f40d788dedd2f94

See more details on using hashes here.

File details

Details for the file gpgram-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: gpgram-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 30.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.1

File hashes

Hashes for gpgram-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 13b44cac501b81a191598c186229383944d1e876daff5bf4f94ce5b01d4a3e26
MD5 5cacac19299ec1e030c999fd25f09139
BLAKE2b-256 c38df2a9a2f01365ec43d1de15ccc18d519ea8ea69cc042d122e738577bc6303

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