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 can be incredibly rewarding, especially when leveraging Telegram's native APIs for speed and efficiency. In this tutorial, we'll explore how to build a Telegram bot natively using Python and the python-telegram-bot library. By the end, you'll have a fully functional bot capable of handling commands, sending messages, and interacting with users in real-time.


Prerequisites

Before diving in, ensure you have the following installed:

  1. Python 3.8+: The latest version of Python is recommended.
  2. pip: Python's package manager.
  3. Telegram Bot Token: Obtain this by talking to BotFather on Telegram.

Install the necessary Python package:

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

Step 1: Setting Up the Bot

First, create a new Python file (e.g., bot.py) and import the necessary modules:

from telegram import Update, ReplyKeyboardMarkup
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
Enter fullscreen mode Exit fullscreen mode

Initialize the bot using your token:

TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hello! I'm your Telegram bot.")

if __name__ == "__main__":
    application = ApplicationBuilder().token(TOKEN).build()

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

    application.run_polling()
Enter fullscreen mode Exit fullscreen mode

Here’s what’s happening:

  1. TOKEN: Replace this with your bot's token.
  2. start function: Handles the /start command.
  3. ApplicationBuilder: Initializes the bot application.
  4. CommandHandler: Maps the /start command to the start function.
  5. run_polling: Starts the bot in polling mode.

Run the script:

python bot.py
Enter fullscreen mode Exit fullscreen mode

Send /start to your bot on Telegram. It should respond with "Hello! I'm your Telegram bot."


Step 2: Handling Commands

Let’s add more commands to make the bot interactive. For example, a /help command:

async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Here are the commands you can use:\n/start - Start the bot\n/help - Get help")

if __name__ == "__main__":
    application = ApplicationBuilder().token(TOKEN).build()

    start_handler = CommandHandler("start", start)
    help_handler = CommandHandler("help", help)
    application.add_handler(start_handler)
    application.add_handler(help_handler)

    application.run_polling()
Enter fullscreen mode Exit fullscreen mode

Step 3: Responding to Messages

To handle all incoming messages (not just commands), use a MessageHandler:

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_message = update.message.text
    await update.message.reply_text(f"You said: {user_message}")

if __name__ == "__main__":
    application = ApplicationBuilder().token(TOKEN).build()

    start_handler = CommandHandler("start", start)
    help_handler = CommandHandler("help", help)
    echo_handler = MessageHandler(filters.TEXT & ~filters.COMMAND, echo)
    application.add_handler(start_handler)
    application.add_handler(help_handler)
    application.add_handler(echo_handler)

    application.run_polling()
Enter fullscreen mode Exit fullscreen mode

The filters.TEXT & ~filters.COMMAND ensures the bot responds to regular messages but not commands.


Step 4: Adding a Custom Keyboard

Telegram bots can send custom keyboards to users. Let’s add one:

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [["Option 1", "Option 2"], ["Option 3"]]
    reply_markup = ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)
    await update.message.reply_text("Choose an option:", reply_markup=reply_markup)
Enter fullscreen mode Exit fullscreen mode

This creates a custom keyboard with three options. Update the echo function to handle these options:

async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_message = update.message.text
    if user_message in ["Option 1", "Option 2", "Option 3"]:
        await update.message.reply_text(f"You selected: {user_message}")
    else:
        await update.message.reply_text(f"You said: {user_message}")
Enter fullscreen mode Exit fullscreen mode

Step 5: Handling Errors

It’s crucial to handle errors gracefully. Add an error handler:

async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print(f"Update {update} caused error {context.error}")

if __name__ == "__main__":
    application = ApplicationBuilder().token(TOKEN).build()

    start_handler = CommandHandler("start", start)
    help_handler = CommandHandler("help", help)
    echo_handler = MessageHandler(filters.TEXT & ~filters.COMMAND, echo)
    application.add_handler(start_handler)
    application.add_handler(help_handler)
    application.add_handler(echo_handler)

    application.add_error_handler(error)
    application.run_polling()
Enter fullscreen mode Exit fullscreen mode

Step 6: Deploying the Bot

To keep the bot running 24/7, deploy it to a cloud service like Heroku, AWS, or Google Cloud. Here’s a brief guide for Heroku:

  1. Install Heroku CLI: brew install heroku/brew/heroku
  2. Login: heroku login
  3. Create a new app: heroku create
  4. Push your code: git push heroku main
  5. Scale the bot: heroku ps:scale worker=1

Conclusion

Congratulations! You’ve built a native Telegram bot using Python and the python-telegram-bot library. You’ve learned how to:

  • Set up a bot
  • Handle commands and messages
  • Add a custom keyboard
  • Handle errors
  • Deploy the bot

Telegram bots are versatile and can be extended with advanced features like inline queries, callbacks, and webhooks. Explore the official documentation to take your bot to the next level. 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)