Skip to main content

An advanced Telegram bot library

Project description

Telegram Advanced Package Documentation

Table of Contents

  1. Installation
  2. Basic Usage
  3. Key Components
  4. Advanced Usage
  5. Error Handling

Installation

To install the Telegram Advanced package, use pip:

pip install telegram-advanced

Basic Usage

Here's a simple example of how to create a bot using the Telegram Advanced package:

import asyncio
import aiohttp
from telegram_advanced.bot import TelegramBot
from openai import AsyncOpenAI
import os

class SimpleBot(TelegramBot):
    def __init__(self, token, openai_api_key):
        super().__init__(token)
        self.base_url = f"https://api.telegram.org/bot{token}/"
        self.ai_client = AsyncOpenAI(api_key=openai_api_key)

    async def process_update(self, update: dict):
        if 'message' in update:
            message = update['message']
            chat_id = message['chat']['id']
            text = message.get('text', '')
            
            if text == '/start':
                await self.send_text(chat_id, "Hello! Ask me anything!")
            else:
                ai_response = await self.get_ai_response(text)
                await self.send_text(chat_id, ai_response)

    async def send_text(self, chat_id: int, text: str):
        async with aiohttp.ClientSession() as session:
            url = f"{self.base_url}sendMessage"
            params = {
                "chat_id": chat_id,
                "text": text
            }
            await session.get(url, params=params)

    async def get_ai_response(self, user_message: str) -> str:
        try:
            response = await self.ai_client.chat.completions.create(
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": user_message}
                ],
                model="gpt-3.5-turbo",
            )
            return response.choices[0].message.content
        except Exception as e:
            return "Sorry, I couldn't get a response."

async def main():
    telegram_token = os.getenv("TELEGRAM_TOKEN")
    openai_api_key = os.getenv("OPENAI_API_KEY")
    
    bot = SimpleBot(telegram_token, openai_api_key)
    
    await bot.run()

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

Key Components

API

The api module contains the core functionality for interacting with the Telegram API.

  • client.py: Handles API requests and responses.
  • types.py: Defines Python objects that represent Telegram entities.
  • methods.py: Implements Telegram API methods.

Example usage:

from telegram_advanced.api.client import TelegramClient

client = TelegramClient("YOUR_BOT_TOKEN")
updates = client.get_updates()

Handlers

The handlers module contains classes for handling different types of updates from Telegram.

  • message_handler.py: Handles incoming messages.
  • command_handler.py: Handles bot commands.
  • callback_handler.py: Handles callback queries from inline keyboards.
  • inline_handler.py: Handles inline queries.

Example usage:

from telegram_advanced.handlers.command_handler import CommandHandler

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I'm a bot.")

start_handler = CommandHandler("start", start)
bot.add_handler(start_handler)

Components

The components module provides utility classes for working with various Telegram features.

  • keyboards.py: Creates inline and reply keyboards.
  • media.py: Handles photo, video, and other media types.
  • passport.py: Implements Telegram Passport functionality.
  • payments.py: Handles Telegram Payments.
  • games.py: Implements Telegram Games.

Example usage:

from telegram_advanced.components.keyboards import InlineKeyboardBuilder

keyboard = InlineKeyboardBuilder()
keyboard.add_button("Click me!", callback_data="button1")
message = bot.send_message(chat_id, "Here's a button:", reply_markup=keyboard.build())

Management

The management module provides tools for managing Telegram groups, channels, and users.

  • groups.py: Manage group chats.
  • channels.py: Manage channels.
  • users.py: Manage user data and permissions.

Example usage:

from telegram_advanced.management.groups import GroupManager

group_manager = GroupManager(bot)
members = group_manager.get_chat_members(chat_id)

Features

The features module implements additional Telegram features.

  • polls.py: Create and manage polls.
  • threads.py: Handle message threads in groups.
  • reactions.py: Manage message reactions.
  • pinned_messages.py: Handle pinned messages.

Example usage:

from telegram_advanced.features.polls import PollManager

poll_manager = PollManager(bot)
poll = poll_manager.create_poll(chat_id, "What's your favorite color?", ["Red", "Blue", "Green"])

Utils

The utils module provides various utility functions and classes.

  • file_handling.py: Handle file uploads and downloads.
  • localization.py: Implement multi-language support.
  • security.py: Implement security features like rate limiting.
  • caching.py: Cache frequently used data.
  • connection_pool.py: Manage API connections efficiently.
  • batch_processing.py: Process updates in batches.
  • rate_limiter.py: Implement rate limiting for API requests.
  • pagination.py: Handle paginated results from the API.

Example usage:

from telegram_advanced.utils.file_handling import FileUploader

uploader = FileUploader(bot)
file_id = uploader.upload_photo("path/to/photo.jpg")

Analytics

The analytics module provides tools for analyzing bot usage and performance.

  • statistics.py: Collect and analyze usage statistics.
  • peer_rating.py: Implement a rating system for users or chats.

Example usage:

from telegram_advanced.analytics.statistics import UsageTracker

tracker = UsageTracker(bot)
daily_stats = tracker.get_daily_usage()

Advanced Usage

For more advanced usage, you can combine multiple components:

from telegram_advanced.bot import TelegramBot
from telegram_advanced.handlers.command_handler import CommandHandler
from telegram_advanced.components.keyboards import InlineKeyboardBuilder
from telegram_advanced.features.polls import PollManager

bot = Bot("YOUR_BOT_TOKEN")

def create_poll(update, context):
    keyboard = InlineKeyboardBuilder()
    keyboard.add_button("Create Poll", callback_data="create_poll")
    context.bot.send_message(chat_id=update.effective_chat.id, text="Click to create a poll:", reply_markup=keyboard.build())

def poll_callback(update, context):
    query = update.callback_query
    if query.data == "create_poll":
        poll_manager = PollManager(context.bot)
        poll = poll_manager.create_poll(query.message.chat_id, "What's your favorite programming language?", ["Python", "JavaScript", "Java", "C++"])
        query.answer("Poll created!")

bot.add_handler(CommandHandler("poll", create_poll))
bot.add_handler(CallbackQueryHandler(poll_callback))

bot.start_polling()

Error Handling

The package includes a custom exceptions.py module for handling Telegram-specific errors:

from telegram_advanced.exceptions import TelegramAPIError

try:
    # Some API call
    bot.send_message(chat_id, "Hello, World!")
except TelegramAPIError as e:
    print(f"An error occurred: {e}")

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

telegram_advanced-0.2.0.tar.gz (19.8 kB view details)

Uploaded Source

Built Distribution

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

telegram_advanced-0.2.0-py3-none-any.whl (26.6 kB view details)

Uploaded Python 3

File details

Details for the file telegram_advanced-0.2.0.tar.gz.

File metadata

  • Download URL: telegram_advanced-0.2.0.tar.gz
  • Upload date:
  • Size: 19.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.11.2

File hashes

Hashes for telegram_advanced-0.2.0.tar.gz
Algorithm Hash digest
SHA256 e55d73f200f46704084e4c050f023ca2acb7ce51bbac7bb3a7d6093e89685d6d
MD5 977461ce449d2739c86045158e0e470a
BLAKE2b-256 00bde2aff689cd7150a34b921fc350622486a850ec8695b46d9d9b76a85a2c31

See more details on using hashes here.

File details

Details for the file telegram_advanced-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for telegram_advanced-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bd7e3c45dd81143ee2051ece8739fad30073a3332e81fd5510493a21207feae7
MD5 abb931703e8f10926eb7a2449543fef8
BLAKE2b-256 5778f2a91a522b0a55e23da57e5e76f243cca45c25be40dc1518e75f470ada37

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