Creating a Telegram Bot with python-telegram-bot (v20.6 and Above)

Creating a Telegram Bot with python-telegram-bot (v20.6 and Above)

Telegram provides a robust platform for building interactive bots, and the python-telegram-bot library makes it easier for Python developers to create and manage Telegram bots. The earlier versions of telegram-bot used a dispatcher, which has since been deprecated. In this article, I'll guide you through the process of creating a Telegram bot using python-telegram-bot version 20.6 and above, where we use async function instead of the dispatcher.

Prerequisites

Before we start, ensure that you have the following installed:

  • Python (version 3.7 or above)

  • pip (Python package installer)

Installing Dependencies

To begin, install the python-telegram-bot library using the following command:

pip install python-telegram-bot==20.6

Setting Up the Environment

Create a new Python file (e.g., main.py) and open it in your favorite code editor. This file will contain the main logic for your Telegram bot.

Configuring Your Bot

To configure your bot, you'll need a Telegram Bot Token. Follow these steps to obtain one:

  1. Open Telegram and search for the "BotFather" bot.

  2. Start a chat with BotFather and use the /newbot command to create a new bot.

  3. Follow the instructions to set a name and username for your bot.

  4. Once your bot is created, BotFather will provide you with a unique API token.

Writing Your Bot Code

Now, let's start writing the code for your bot (You can also read the official documentation here on how to get started). Below is a basic structure to get you started:

import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    ApplicationBuilder,
    CommandHandler,
    MessageHandler,
    CallbackQueryHandler,
    filters,
    ContextTypes,
)

# Set up logging to see any errors
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

# Your bot token obtained from BotFather
BOT_TOKEN = 'your_bot_token'

# Set up the bot application
application = ApplicationBuilder().token(BOT_TOKEN).build()

# Command handler for /start command
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [
        [InlineKeyboardButton("Balance", callback_data="balance")],
        [InlineKeyboardButton("Send Coins", callback_data="send_coins")],
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)

    await context.bot.send_message(
        chat_id=update.effective_chat.id,
        text="Welcome! Select an option to get started:",
        reply_markup=reply_markup,
    )

# Command handler for unknown commands
async def unknown(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(
        chat_id=update.effective_chat.id,
        text="Sorry, I didn't understand that command. Check if you have a typo.",
    )

# Callback handler for the "Balance" button
async def balance_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # Your logic to fetch and display the balance
    await context.bot.send_message(
        chat_id=update.effective_chat.id,
        text="Fetching your balance...",
    )

# Message handler for echoing user messages
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(
        chat_id=update.effective_chat.id,
        text=update.message.text,
    )

# Registering handlers
start_handler = CommandHandler('start', start)
unknown_handler = MessageHandler(filters.COMMAND, unknown)
callback_query_handler_balance = CallbackQueryHandler(balance_callback, pattern="balance")
echo_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), echo)

application.add_handler(start_handler)
application.add_handler(callback_query_handler_balance)
application.add_handler(echo_handler)

application.add_handler(unknown_handler)

# Run the bot
application.run_polling()

Replace 'your_bot_token' With the actual token obtained from BotFather. Also, notice how I added the handler for unknown in the last place. This was necessary to avoid registering other commands as "unknown." Besides, you can also choose to write the commands in a different file and import them to the main.py to have a cleaner code.

Running Your Bot

Save your main.py file and run it using the following command (incase you are using python3):

python3 main.py

Now, you should have a basic Telegram bot up and running! Users can interact with the bot by pressing the "Balance" button, and you can extend the functionality by adding more commands and callback handlers.

This example provides a solid foundation for building more complex bots with additional features. Explore the python-telegram-bot documentation for more advanced functionalities and customization options.

Congratulations on creating your Telegram bot using python-telegram-bot version 20.6 and above! Feel free to customize and expand upon this code to suit your specific use case.

Happy coding!