All writing
January 15, 20264 min read

Build a Telegram Translator Bot with Python

A step-by-step project covering BotFather, a Python bot, translation APIs, deployment, and useful media blocks.

In this walkthrough, we will create a small Telegram bot that translates a message when someone replies with /translate. The project demonstrates a practical bot flow; keep your bot token private and configure it through an environment variable.

Laptop and phone on a desk
Plan the bot before writing code

1. Create a Telegram bot

Open Telegram and message BotFather. Run /newbot, choose a display name, then choose a username ending in bot. Store the token somewhere private; anyone with it can control your bot.

Prepare a Python project

Create a folder, a virtual environment, and install the Telegram bot library. Keep secrets out of source control.

python -m venv .venv
source .venv/bin/activate
pip install python-telegram-bot httpx
export TELEGRAM_BOT_TOKEN='paste-your-token-in-your-shell'

Add a requirements file

Pin or record your dependencies in requirements.txt so the same environment can be recreated later.

2. Receive a message and translate it

The bot needs a handler that receives a reply, extracts the replied-to text, calls a translation provider, and sends the translated result. This compact example leaves the provider endpoint behind a function so you can choose a service and check its terms.

import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

async def translate_text(text: str, target: str = "en") -> str:
    # Call your chosen translation API here.
    return f"[{target}] {text}"

async def translate_reply(update: Update, context: ContextTypes.DEFAULT_TYPE):
    message = update.effective_message
    if not message:
        return
    if not message.reply_to_message:
        await message.reply_text("Reply to a message with /translate")
        return
    source = message.reply_to_message.text or message.reply_to_message.caption
    if not source:
        await message.reply_text("That message has no translatable text.")
        return
    result = await translate_text(source, target="en")
    await message.reply_text(result)

app = Application.builder().token(os.environ["TELEGRAM_BOT_TOKEN"]).build()
app.add_handler(CommandHandler("translate", translate_reply))
app.run_polling()

A bot token is a credential. Never paste a real token into a public post, screenshot, or committed code sample.

Connect a real translation provider

Replace the placeholder with an async HTTP request to your chosen translation API. Read the provider's privacy and rate-limit terms, set request timeouts, and handle API errors without exposing credentials to chat users.

A developer workspace with a laptop
Build and test one step at a time

3. Test locally, then deploy

Try the important cases

  • Run /translate without replying and confirm the bot explains how to use it.

  • Reply to a text message and verify the translated response.

  • Try a photo caption, an empty message, and a provider timeout.

Choose polling or webhooks

Polling is convenient while developing. For a hosted bot, configure a webhook behind HTTPS, keep the process supervised, and rotate the token if it is ever exposed.

translation-bot-quick-reference.pdfapplication/pdf
Download
Python.gitignoretext/plain
Download

Loading preview…

bot-project-resource.pdf

5. Add language selection

A useful next improvement is letting each chat choose a target language. Store the selection by chat ID, validate the requested language against your translation provider, and explain the current target in a /language command.

from telegram.ext import CommandHandler

async def set_language(update, context):
    if not context.args:
        await update.effective_message.reply_text("Usage: /language en")
        return
    target = context.args[0].lower()
    if target not in {"en", "es", "fr", "de"}:
        await update.effective_message.reply_text("Choose en, es, fr, or de.")
        return
    context.chat_data["target_language"] = target
    await update.effective_message.reply_text(f"Target language set to {target}.")

app.add_handler(CommandHandler("language", set_language))

6. Add resilience and good error messages

Translation providers can rate-limit requests or become temporarily unavailable. Use timeouts, retry only transient errors with a small backoff, and avoid sending internal exception details or provider credentials to Telegram users.

7. Protect user privacy

Messages sent to a translation API leave Telegram and reach another service. Tell users what is processed, avoid storing message text unless you need it, and follow the privacy and retention rules of both Telegram and your chosen provider.

8. Deploy with webhooks

For a public bot, run behind HTTPS and configure Telegram's webhook endpoint. Verify Telegram's secret token header, keep the bot process monitored, and rotate credentials immediately if they leak.

  1. Set TELEGRAM_BOT_TOKEN in the host's secret manager.

  2. Configure the webhook URL and a random webhook secret.

  3. Check logs and health status without logging message contents or secrets.

Troubleshooting checklist

  • If the bot does not respond, verify its token, process status, and webhook or polling configuration.

  • If translation fails, check provider quotas, API status, request timeouts, and supported language codes.

  • If updates are duplicated, make handling idempotent and inspect webhook delivery status.

Further exercises

Add automatic language detection, per-user preferences, caching for repeated phrases, and a /help command. Then write a few focused tests around empty messages, API timeouts, and language validation before inviting others to use the bot.

4. Keep improving the bot

Add language selection, caching, and clear failure messages as follow-up exercises. This sample keeps the provider call explicit so readers can extend it safely.