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 tasks, interacting with users, and integrating services. While libraries like python-telegram-bot simplify development, building a Telegram bot natively using Telegram's Bot API ensures maximum control and performance. In this tutorial, we'll walk through the fastest way to build a Telegram bot natively using Python and HTTP requests.


Prerequisites

Before diving in, ensure you have:

  1. A Telegram account to create and manage bots.
  2. Python installed (preferably β‰₯ 3.8).
  3. Basic knowledge of HTTP requests and JSON.
  4. A Bot Token from BotFather.

Step 1: Get Your Bot Token

  1. Open Telegram and search for BotFather.
  2. Use /newbot to create a new bot.
  3. Follow the prompts to set the bot's name and username.
  4. Save the Bot Tokenβ€”this is your API key.

Step 2: Set Up Your Python Environment

Create a virtual environment and install the required libraries:

python -m venv telegram-bot-env
source telegram-bot-env/bin/activate
pip install requests
Enter fullscreen mode Exit fullscreen mode

The requests library simplifies HTTP requests in Python.


Step 3: Understand Telegram's Bot API Basics

Telegram's Bot API is HTTP-based. All interactions occur via GET or POST requests to endpoints like:

  • https://api.telegram.org/bot<token>/METHOD_NAME

For example, to send a message, use sendMessage.


Step 4: Write the Native Bot

We'll build a simple bot that echoes user messages.

1. Import Libraries and Define Constants

import requests

API_URL = "https://api.telegram.org/bot"
TOKEN = "YOUR_BOT_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Replace YOUR_BOT_TOKEN with your actual bot token.

2. Fetch Updates Using getUpdates

To receive messages, poll the getUpdates method. Implement a function to fetch updates:

def get_updates(offset=None):
    url = f"{API_URL}{TOKEN}/getUpdates"
    params = {"offset": offset, "timeout": 10} if offset else {"timeout": 10}
    response = requests.get(url, params=params)
    return response.json()["result"]
Enter fullscreen mode Exit fullscreen mode
  • offset: Ensures you only receive new updates.
  • timeout: Long-polling for real-time updates.

3. Process Updates and Echo Messages

Loop through updates and reply to each message:

def process_updates(updates):
    for update in updates:
        chat_id = update["message"]["chat"]["id"]
        text = update["message"]["text"]
        send_message(chat_id, text)

def send_message(chat_id, text):
    url = f"{API_URL}{TOKEN}/sendMessage"
    payload = {"chat_id": chat_id, "text": text}
    requests.post(url, json=payload)
Enter fullscreen mode Exit fullscreen mode

4. Main Loop

Combine everything into a main loop:

def main():
    offset = None
    while True:
        updates = get_updates(offset)
        if updates:
            process_updates(updates)
            offset = updates[-1]["update_id"] + 1

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

This loop continuously fetches and processes updates.


Step 5: Add Advanced Features

Once you've mastered the basics, enhance your bot with advanced features:

1. Handle Commands

Parse /start or /help commands:

def process_updates(updates):
    for update in updates:
        chat_id = update["message"]["chat"]["id"]
        text = update["message"]["text"]

        if text == "/start":
            send_message(chat_id, "Welcome! Send me a message.")
        elif text == "/help":
            send_message(chat_id, "I'm an echo bot. I repeat what you say.")
        else:
            send_message(chat_id, text)
Enter fullscreen mode Exit fullscreen mode

2. Use Inline Keyboards

Inline keyboards make your bot interactive. Use sendMessage with a reply_markup parameter:

def send_keyboard(chat_id):
    url = f"{API_URL}{TOKEN}/sendMessage"
    keyboard = {
        "inline_keyboard": [[{"text": "Button 1", "callback_data": "data_1"}]]
    }
    payload = {"chat_id": chat_id, "text": "Choose:", "reply_markup": json.dumps(keyboard)}
    requests.post(url, json=payload)
Enter fullscreen mode Exit fullscreen mode

3. Handle Callback Queries

When users press inline buttons, handle callback_query updates:

def process_updates(updates):
    for update in updates:
        if "callback_query" in update:
            callback_data = update["callback_query"]["data"]
            chat_id = update["callback_query"]["message"]["chat"]["id"]
            send_message(chat_id, f"You pressed: {callback_data}")
Enter fullscreen mode Exit fullscreen mode

Step 6: Optimize for Scalability

Polling works fine for small bots, but for larger-scale applications, consider:

1. Webhooks

Webhooks provide real-time updates by having Telegram POST data to your server. Set a webhook URL:

def set_webhook(url):
    set_url = f"{API_URL}{TOKEN}/setWebhook"
    payload = {"url": url}
    requests.post(set_url, json=payload)
Enter fullscreen mode Exit fullscreen mode

2. Asynchronous Processing

Use asyncio and aiohttp for asynchronous HTTP requests:

import aiohttp
import asyncio

async def send_message(chat_id, text):
    url = f"{API_URL}{TOKEN}/sendMessage"
    payload = {"chat_id": chat_id, "text": text}
    async with aiohttp.ClientSession() as session:
        await session.post(url, json=payload)
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Building a Telegram bot natively may seem daunting, but it offers unparalleled flexibility and performance. By leveraging HTTP requests, Python, and Telegram's Bot API, you can create bots tailored to your exact needs.

Experiment with advanced features like webhooks, asynchronous processing, and inline keyboards 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)