DEV Community

Apollo
Apollo

Posted on

The fastest way to build a Telegram Bot natively

The Fastest Way to Build a Telegram Bot Natively

Telegram bots are powerful tools for automating interactions, notifications, and workflows. Using Python and the official python-telegram-bot library, we can quickly build a Telegram bot that integrates with Telegram's native API. This tutorial will guide you through the fastest way to create a Telegram bot from scratch, including advanced features like command handling, inline queries, and deployment.

Prerequisites

  1. A Telegram account and the Telegram app installed.
  2. Python 3.8+ installed on your system.
  3. A Telegram Bot Token obtained from @BotFather.

Step 1: Set Up Your Development Environment

Install the python-telegram-bot library, which is the most efficient way to interact with Telegram's API:

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

Step 2: Create a Basic Bot

Start by creating a Python script (bot.py) and initialize your bot with the token provided by BotFather.

from telegram import Update, Bot
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters

# Initialize the bot with your token
TOKEN = "YOUR_BOT_TOKEN_HERE"

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

async def echo(update: Update, context):
    await update.message.reply_text(update.message.text)

# Build the application
application = ApplicationBuilder().token(TOKEN).build()

# Add handlers for commands and messages
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))

# Run the bot
application.run_polling()
Enter fullscreen mode Exit fullscreen mode

This script:

  1. Imports necessary modules from python-telegram-bot.
  2. Defines handlers for /start command and echo functionality.
  3. Uses ApplicationBuilder to initialize and run the bot.

Run your bot:

python bot.py
Enter fullscreen mode Exit fullscreen mode

Step 3: Implement Advanced Features

Handle Commands

Commands are essential for Telegram bots. Let's add a /help command:

async def help_command(update: Update, context):
    await update.message.reply_text("Available commands:\n/start - Start the bot\n/help - Show this message")

application.add_handler(CommandHandler("help", help_command))
Enter fullscreen mode Exit fullscreen mode

Inline Keyboard

Add interactive buttons using inline keyboards:

from telegram import InlineKeyboardButton, InlineKeyboardMarkup

async def button(update: Update, context):
    keyboard = [
        [InlineKeyboardButton("Option 1", callback_data="1")],
        [InlineKeyboardButton("Option 2", callback_data="2")]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text("Please choose:", reply_markup=reply_markup)

application.add_handler(CommandHandler("button", button))
Enter fullscreen mode Exit fullscreen mode

Handle Callback Queries

Process button clicks:

from telegram.ext import CallbackQueryHandler

async def callback_query(update: Update, context):
    query = update.callback_query
    await query.answer()
    await query.edit_message_text(text=f"Selected option: {query.data}")

application.add_handler(CallbackQueryHandler(callback_query))
Enter fullscreen mode Exit fullscreen mode

Inline Queries

Enable users to interact with your bot via inline queries:

from telegram import InlineQueryResultArticle, InputTextMessageContent

async def inline_query(update: Update, context):
    query = update.inline_query.query
    results = [
        InlineQueryResultArticle(
            id="1",
            title="Echo",
            input_message_content=InputTextMessageContent(query)
        )
    ]
    await update.inline_query.answer(results)

application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
Enter fullscreen mode Exit fullscreen mode

Step 4: Deploy Your Bot

Hosting on a Cloud Platform

Deploy your bot on a platform like Heroku or AWS for continuous operation.

  1. Create a requirements.txt file:
python-telegram-bot
Enter fullscreen mode Exit fullscreen mode
  1. Create a Procfile:
worker: python bot.py
Enter fullscreen mode Exit fullscreen mode
  1. Push your code to Heroku:
heroku create
git add .
git commit -m "Deploy Telegram Bot"
git push heroku master
heroku ps:scale worker=1
Enter fullscreen mode Exit fullscreen mode

Setting Up a Webhook

For better scalability, configure a webhook instead of polling:

from telegram.ext import ApplicationBuilder

TOKEN = "YOUR_BOT_TOKEN_HERE"
WEBHOOK_URL = "https://yourdomain.com/webhook"

application = ApplicationBuilder().token(TOKEN).updater(None).build()
application.run_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN, webhook_url=WEBHOOK_URL)
Enter fullscreen mode Exit fullscreen mode

Ensure your server is HTTPS-enabled.

Step 5: Scale and Optimize

  1. Database Integration: Use SQLite, PostgreSQL, or MongoDB to store user data and bot state.
  2. Logging: Implement logging for debugging and monitoring:
import logging

logging.basicConfig(level=logging.DEBUG)
Enter fullscreen mode Exit fullscreen mode
  1. Rate Limiting: Use telegram.ext.Dispatcher with rate_limit to prevent API abuse.

Conclusion

Building a Telegram bot natively with python-telegram-bot is fast, efficient, and highly scalable. By following this tutorial, you’ve created a bot with command handling, inline keyboards, callback queries, and deployment. Experiment with additional features like custom keyboards, payments, and integrations with external APIs to unlock the full potential of Telegram bots.

For more information, refer to the python-telegram-bot documentation. Happy coding!


Stop Reinventing The Wheel

If you want to skip the boilerplate and launch your app today, check out my Ultimate AI Micro-SaaS Boilerplate ($49). It includes full Stripe integration, Next.js, and an external API suite.

Or, let my AI teardown your existing funnels at Apollo Roaster.

Top comments (0)