DEV Community

Cover image for 🌍 Build My Own Telegram Translator Bot with Python
Jean Estevez
Jean Estevez

Posted on

🌍 Build My Own Telegram Translator Bot with Python

βš™οΈ *This article is part of my practice and reinforcement: in this post you will see β€œwhat” I have done, also β€œwhy” and β€œhow” each part works, it is ideal for advanced and intermediate beginners.

Hey devs! πŸ‘‹ I'm Jean, and I've launched LinguaTranslateSpark: a Telegram bot that instantly translates text in 100+ languages.


πŸš€ What Is LinguaTranslateSpark?

A lightweight real-time translation bot for Telegram, built in Python. With it you can:

βœ… Translate instantly.

βœ… Change target languages.

βœ… Save preferences

βœ… Deploy in minutes

πŸ‘‰ Test now


πŸ› οΈ Why I Built This

I converse daily with friends (some of us don't speak the same language) and I thought, what better exercise or practice than a telegram bot to translate, practice and at the same time have some fun, biting code πŸ˜„


πŸ”§ Under the Hood: Code and Concepts

Dependencies and Setup
python-telegram-bot: abstracts Telegram API with handlers and callbacks.

deep-translator: lightweight client for Google Translate (without using the official API, plus googletrans flags many errors).

Async I/O with async def: avoids crashes and improves real-time experience.

context.user_data: per-user dict to remember preferences without database.

import logging
import asyncio
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    Application,
    CommandHandler,
    MessageHandler,
    filters,
    CallbackContext,
    CallbackQueryHandler
)
from deep_translator import GoogleTranslator
Enter fullscreen mode Exit fullscreen mode

We import key classes from python-telegram-bot.

ApplicationBuilder creates the bot, and the handlers are the β€œroutes” that execute functions according to commands or responses.


Translation Function

async def translate_message(update: Update, context: CallbackContext) -> None:
    user_text = update.message.text
    user_id = update.effective_user.id

    logger.debug(f'User {user_id} sent text: {user_text}')

    target_language = context.user_data.get('target_language', 'en')

    try:
        loop = asyncio.get_running_loop()
        translated_text = await loop.run_in_executor(
            None,
            lambda: GoogleTranslator(target=target_language).translate(user_text)
        )

        response = (
            f"<b>Original:</b>\n{user_text}\n\n"
            f"<b>Translation ({target_language.upper()}):</b>\n{translated_text}"
        )

        await update.message.reply_text(response, parse_mode="HTML")
        logger.info(f'Successful translation for {user_id} to {target_language}')

    except Exception as error:
        error_message = 'Translation error. Please try again.'
        await update.message.reply_text(error_message)
        logger.error(f'Translation error: {str(error)}', exc_info=True)
Enter fullscreen mode Exit fullscreen mode

Explanation:

async def declares a coroutine, which allows await (although we use synchronous library here; in real projects it is convenient to use an asynchronous client).


πŸ§ͺ Try It Out in 60 Seconds


git clone https://github.com/Jean-EstevezT/LinguaTranslateSpark
cd LinguaTranslateSpark
pip install python-telegram-bot deep-translator

  • Put your token in config.py (or environment variable).

  • Run: python bot.py

  • Chat with your bot: @LinguaTranslateSparkBot


πŸ’‘ What I Learned

Callback Queries: how to capture clicks on inline buttons.

Session State: using context.user_data without external database.

Async vs Sync: when and why to use coroutines in bots.

Error Handling: wrapping translations in try/except to control network failures or API limits.


πŸ“¦ Project Links

πŸ”— GitHub: https://github.com/Jean-EstevezT/=
πŸ€– Telegram: @LinguaTranslateSparkBot
🐦 Twitter: https://x.com/jeantvz

Top comments (0)