Building an Advanced Telegram Bot with Pyrogram: A Step-by-Step Guide for Beginners

Building an Advanced Telegram Bot with Pyrogram: A Step-by-Step Guide for Beginners

Introduction

Telegram bots have gained immense popularity due to their versatility and utility in automating tasks and providing interactive experiences for users. In this blog post, we will explore how to build an advanced Telegram bot using Pyrogram, a powerful Python library for interacting with the Telegram Bot API.

Prerequisites

Before we dive into building our bot, make sure you have the following prerequisites:

  • Basic knowledge of Python programming language.
  • A Telegram account to interact with the Telegram Bot API.

Getting Started with Pyrogram

Let's create a new bot on Telegram using the BotFather and obtain the API token. Head over to the Telegram app and search for the "BotFather" bot. Initiate a chat with the BotFather and use the "/newbot" command to create a new bot. Follow the instructions, and BotFather will provide you with a unique API token for your bot.

# Install Pyrogram using pip
pip install pyrogram

Now, let's initialize our bot using Pyrogram:

from pyrogram import Client

# Replace 'your_bot_token' with the token provided by BotFather
api_id = 123456   # Replace with your own api_id
api_hash = "your_api_hash"  # Replace with your own api_hash

app = Client("my_bot", api_id=api_id, api_hash=api_hash, bot_token="your_bot_token")

Basic Bot Setup

Now that we have our bot initialized, let's set up the basic command handlers for our bot. These handlers will respond to user commands such as "/start" and "/help."

# Start command handler
@app.on_message(filters.command("start"))
def start_command_handler(client, message):
    message.reply_text("Hello, I am your bot! Type /help for available commands.")

# Help command handler
@app.on_message(filters.command("help"))
def help_command_handler(client, message):
    response = "Available commands:\n"
    response += "/start - Start the bot\n"
    response += "/help - Show available commands\n"
    response += "/send_message - Send a custom message\n"
    message.reply_text(response)

Sending Messages

Our bot can now respond to commands, but let's make it more interactive by adding the ability to send different types of messages, including text, images, videos, and documents.

# Method to send a message
def send_message(chat_id, text):
    app.send_message(chat_id, text)

# Send a photo
def send_photo(chat_id, photo_path, caption=None):
    app.send_photo(chat_id, photo_path, caption=caption)

# Send a video
def send_video(chat_id, video_path, caption=None):
    app.send_video(chat_id, video_path, caption=caption)

# Send a document
def send_document(chat_id, document_path, caption=None):
    app.send_document(chat_id, document_path, caption=caption)

# Custom message command handler
@app.on_message(filters.command("send_message"))
def send_message_command_handler(client, message):
    send_message(message.chat.id, "Hello, I am sending you a custom message!")

# Photo command handler
@app.on_message(filters.command("send_photo"))
def send_photo_command_handler(client, message):
    photo_path = "path/to/your/photo/file.jpg"  # Replace with the actual path to your photo
    send_photo(message.chat.id, photo_path, caption="Check out this beautiful photo!")

# Video command handler
@app.on_message(filters.command("send_video"))
def send_video_command_handler(client, message):
    video_path = "path/to/your/video/file.mp4"  # Replace with the actual path to your video
    send_video(message.chat.id, video_path, caption="Watch this amazing video!")

# Document command handler
@app.on_message(filters.command("send_document"))
def send_document_command_handler(client, message):
    document_path = "path/to/your/document/file.pdf"  # Replace with the actual path to your document
    send_document(message.chat.id, document_path, caption="Check out this document!")

Receiving Files

Our bot can now send various messages, but what if users want to send files to our bot? Let's handle incoming documents, videos, and photos and download and save them on our server.

# Command handler for receiving files
@app.on_message(filters.document | filters.video | filters.photo)
def receive_file_handler(client, message):
    if message.document:
        media = message.document
    elif message.video:
        media = message.video
    elif message.photo:
        media = message.photo[-1]  # Get the last photo from the list (largest resolution)
    else:
        # Ignore other media types like audio, stickers, etc.
        return

    file_name = media.file_name

    # Download the file using the download_media method
    file_path = client.download_media(
        message,
        file_name=file_name,
        file_dir="path/to/your/download/folder"
    )

    message.reply_text(f"File '{file_name}' has been downloaded and saved.")

Handling FloodWait

Sometimes, when the bot exceeds the rate limit for sending messages, Telegram servers may respond with a FloodWait exception. We need to handle this to prevent our bot from being restricted.

# Function to send a message with FloodWait handling
def send_message_with_floodwait(chat_id, text):
    try:
        app.send_message(chat_id, text)
    except Exception as e:
        if "FloodWait" in str(e):
            wait_time = int(str(e).split()[-1])
            print(f"Encountered FloodWait. Waiting for {wait_time} seconds...")
            time.sleep(wait_time)
            send_message_with_floodwait(chat_id, text)
        else:
            print("Error:", e)

Adding Inline Keyboard Markup

Lastly, let's make our bot even more interactive by adding an inline keyboard with options for users.

# Inline query handler
@app.on_inline_query()
def inline_query_handler(client, query: InlineQuery):
    results = [
        {
            "type": "article",
            "id": "1",
            "title": "My Article",
            "input_message_content": {
                "message_text": "This is my article.",
                "parse_mode": "Markdown",
            },
            "reply_markup": InlineKeyboardMarkup(
                [
                    [InlineKeyboardButton("Button 1", callback_data="button1")],
                    [InlineKeyboardButton("Button 2", callback_data="button2")],
                ]
            ),
        }
        # Add more InlineQueryResultArticle objects with different InlineKeyboardMarkup as needed
    ]
    client.answer_inline_query(query.id, results=results, cache_time=1)

Conclusion

Congratulations! You have now built an advanced Telegram bot using Pyrogram with multiple features. You've learned how to send messages of different types, receive and download files, handle FloodWait exceptions, and even add interactive inline keyboards. Continue experimenting with Pyrogram's capabilities to create even more powerful and interactive bots!

Post a Comment

0 Comments