DEV Community

Apollo
Apollo

Posted on

The fastest way to build a Telegram Bot natively

The Fastest Way to Build a Telegram Bot Natively

Building a Telegram bot natively is a powerful way to automate interactions, provide services, or integrate Telegram with other systems. This tutorial will guide you through the fastest and most efficient method to create a Telegram bot using Python and the python-telegram-bot library. We'll cover setup, basic commands, handling updates, and deploying your bot.

Prerequisites

Before we start, ensure you have the following:

  1. Python 3.7+ installed.
  2. pip for managing Python packages.
  3. A Telegram account and the BotFather to create your bot.

Step 1: Create Your Telegram Bot

  1. Open Telegram and search for BotFather.
  2. Start a chat with BotFather and use the /newbot command.
  3. Follow the instructions to name your bot and receive your API token. This token is crucial for interacting with Telegram's API.

Step 2: Setup Your Development Environment

Install the python-telegram-bot library, which simplifies interacting with Telegram's API:

pip install python-telegram-bot
Enter fullscreen mode Exit fullscreen mode

Step 3: Writing Your First Bot

Start by creating a Python script for your bot. Here's a basic example that responds to /start and /help commands:

from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hello! I am your bot.')

def help_command(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Help! I need somebody.')

def main() -> None:
    # Replace 'YOUR_TOKEN' with your bot's token
    updater = Updater("YOUR_TOKEN")

    dispatcher = updater.dispatcher

    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(CommandHandler("help", help_command))

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C
    updater.idle()

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Updater: This is the main class that updates a dispatcher with new updates from Telegram.
  • Dispatcher: It dispatches the updates to the appropriate handler.
  • CommandHandler: This is used to handle commands like /start and /help.

Step 4: Handling Conversations

Telegram bots can handle more than just commands. Let's implement a simple conversation handler:

from telegram import ReplyKeyboardMarkup
from telegram.ext import ConversationHandler, MessageHandler, Filters

CHOOSING, TYPING_REPLY = range(2)

def start(update: Update, context: CallbackContext) -> int:
    reply_keyboard = [['Age', 'Favorite color']]
    update.message.reply_text(
        'Hi! I will hold a conversation with you. Choose one:',
        reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True),
    )
    return CHOOSING

def regular_choice(update: Update, context: CallbackContext) -> int:
    context.user_data['choice'] = update.message.text
    update.message.reply_text(f'Your {update.message.text.lower()}?')
    return TYPING_REPLY

def received_information(update: Update, context: CallbackContext) -> int:
    user_data = context.user_data
    text = update.message.text
    category = user_data['choice']
    del user_data['choice']
    update.message.reply_text(f"By {category} you mean {text}")
    return CHOOSING

def main() -> None:
    updater = Updater("YOUR_TOKEN")

    dispatcher = updater.dispatcher

    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            CHOOSING: [
                MessageHandler(Filters.regex('^(Age|Favorite color)$'), regular_choice)
            ],
            TYPING_REPLY: [
                MessageHandler(Filters.text & ~Filters.command, received_information),
            ],
        },
        fallbacks=[],
    )

    dispatcher.add_handler(conv_handler)

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • ConversationHandler: Manages the conversation flow between the bot and the user.
  • ReplyKeyboardMarkup: Provides a custom keyboard for user inputs.

Step 5: Deploying Your Bot

To keep your bot running continuously, you can deploy it on a cloud service like Heroku or AWS. Here's a basic guide for Heroku:

  1. Install the Heroku CLI and login.
  2. Create a Procfile in your project directory: web: python bot.py
  3. Initialize a Git repository and commit your files.
  4. Create a Heroku app and push your code: heroku create
  5. Set your bot token: heroku config:set TOKEN='YOUR_TOKEN'
  6. Push to Heroku: git push heroku master

Conclusion

Following these steps, you can quickly develop and deploy a Telegram bot using Python. The python-telegram-bot library provides a robust framework for more complex interactions and functionalities. Experiment with different handlers and techniques to expand your bot's capabilities. Happy coding!


🚀 Stop Writing Boilerplate Prompts

If you want to skip the setup and code 10x faster with complete AI architecture patterns, grab my Senior React Developer AI Cookbook ($19). It includes Server Action prompt libraries, UI component generation loops, and hydration debugging strategies.

Browse all 10+ developer products at the Apollo AI Store | Or snipe Solana tokens free via @ApolloSniper_Bot.

Top comments (0)