Developer Guides

Building a Telegram Bot That Converts Images

· 3 min read · Developer Guides

Telegram bots are one of the fastest ways to build a useful tool. Combined with KoalaPic’s API, you can create a bot that converts images in seconds — users send a photo, choose a format, and get the result back in the chat.

What You’ll Build

A Telegram bot that: 1. Accepts image uploads (any format KoalaPic supports) 2. Asks the user what format they want 3. Converts the image via the KoalaPic API 4. Sends the converted file back

Prerequisites

Step 1: Set Up the Project

pip install python-telegram-bot requests

Step 2: Build the Bot

import os
import requests
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
    Application, CommandHandler, MessageHandler,
    CallbackQueryHandler, ContextTypes, filters,
)

KOALAPIC_KEY = os.environ["KOALAPIC_API_KEY"]
TELEGRAM_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]

FORMATS = ["jpg", "png", "webp", "avif", "pdf", "ico"]

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text(
        "Send me an image and I'll convert it to any format!"
    )

async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # Store the file ID for later
    photo = update.message.photo[-1]  # highest resolution
    context.user_data["file_id"] = photo.file_id

    # Show format selection
    keyboard = [
        [InlineKeyboardButton(fmt.upper(), callback_data=fmt)]
        for fmt in FORMATS
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text(
        "Choose output format:", reply_markup=reply_markup
    )

async def handle_format_choice(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    output_format = query.data
    file_id = context.user_data.get("file_id")

    if not file_id:
        await query.edit_message_text("Please send an image first.")
        return

    await query.edit_message_text(f"Converting to {output_format.upper()}...")

    # Download from Telegram
    file = await context.bot.get_file(file_id)
    file_bytes = await file.download_as_bytearray()

    # Convert via KoalaPic
    response = requests.post(
        "https://koalapic.com/api/v1/convert",
        headers={"Authorization": f"Bearer {KOALAPIC_KEY}"},
        files={"file": ("image.jpg", bytes(file_bytes))},
        data={"output_format": output_format},
    )

    if response.status_code == 200:
        data = response.json()
        # Download the converted file
        result = requests.get(data["download_url"])
        await query.message.reply_document(
            document=result.content,
            filename=f"converted.{output_format}",
        )
    else:
        await query.edit_message_text("Conversion failed. Please try again.")

app = Application.builder().token(TELEGRAM_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.PHOTO, handle_photo))
app.add_handler(CallbackQueryHandler(handle_format_choice))
app.run_polling()

Step 3: Run It

export KOALAPIC_API_KEY="kp_your_key"
export TELEGRAM_BOT_TOKEN="your_telegram_token"
python bot.py

Send a photo to your bot, tap a format button, and receive the converted file.

Adding Features

Once the basic bot works, consider adding:

  • Quality selection: Add a second keyboard for quality (low/medium/high)
  • Batch support: Handle multiple photos in one message
  • Usage limits: Track conversions per user per day
  • Status messages: Show progress for large files

Deployment

For production, run your bot on a VPS or container. KoalaPic already has an official Telegram bot — but building your own teaches you the API and lets you customize the experience.

Next Steps

Enjoyed this article? Share it.

Related Posts

Send Feedback

Thank you! We'll get back to you soon.

Install KoalaPic

Add to your home screen for quick access

Cookie & Storage Preferences

We use cookies and local storage to improve your experience. Essential storage is always active for core functionality. Learn more

Essential

CSRF protection, dark mode, error tracking. Always active.

Functional

Conversion presets, UI preferences, PWA install state.

Analytics

Anonymous usage statistics to improve the service.