Telegram BotAI Image Generator APIImage to Video APIFLUX 2 FlashKling 2.6Vibe Coding

Build a Telegram AI Image Bot in 139 Lines of TypeScript: $0.0058 an Image, and 1 Command Costs 69x More

A stranger who finds your Telegram bot can spend $0.4025 of your money with 1 word. /animate turns an image into a 5-second Kling 2.6 clip, and that clip costs as much as 69 FLUX 2 Flash images. Here are 139 lines of TypeScript that draw for $0.0058, edit photos and animate them, with an allowlist and a daily cap built in.

2026-11-18·9 min read

What the bot does

Three things, each on a different model, all through one API key:

1. A text message becomes an image. “a ceramic mug on a rainy windowsill, film photo” goes to FLUX 2 Flash at 1024×768 and comes back as a photo in the chat.

2. A photo with a caption becomes an edit. Send a picture captioned “make the background a sunny beach” and FLUX 2 Edit returns the changed image.

3. /animate becomes a clip. Reply /animate to any image the bot made, optionally with a motion (“/animate steam rises from the cup, slow push-in”), and Kling 2.6 Pro turns it into a 5-second video.

No framework, no server and no database: Node 20 has fetch, FormData and Blob built in, and Telegram’s long polling means the bot works from a laptop with no public URL.

What every command costs

Prices come from MegaBrain’s model pages. The price is charged when the job enters the queue, and a job the model fails is refunded to your balance.

CommandModelSettingsCost
Text messageFLUX 2 Flashlandscape_4_3 (1024×768, 1 started megapixel), jpeg$0.0058
Photo + captionFLUX 2 Editinput picked at or under 1 megapixel, output follows the input$0.0276 (1 MP in + 1 MP out at $0.0138)
/animateKling 2.6 Pro, image to videoduration "5", generate_audio false$0.4025
/animate, audio left onKling 2.6 Pro, image to videoduration "5", generate_audio true (the default)$0.805

1 clip costs as much as 69 images. A team of 5 that makes 20 images and 1 clip each a day spends $17.40 a month on 3,000 images and $60.38 on 150 clips: the clips are 78% of the bill. Put your limits on /animate, not on the images.

The code

One file, bot.mts. It follows the queue pattern from the media API docs: POST the model’s own fields to /queue/<model id>, poll status_url until COMPLETED or FAILED, then read the result from response_url.

// bot.mts: a Telegram bot that draws, edits and animates through the MegaBrain API.
// Text -> FLUX 2 Flash image. Photo + caption -> FLUX 2 Edit. Reply /animate -> Kling 2.6 clip.
// Run: npx tsx bot.mts   (Node 20+, no dependencies)

const TG = "https://api.telegram.org/bot" + process.env.TELEGRAM_BOT_TOKEN;
const MB = "https://getmegabrain.com/api/gateway/v1";
const AUTH = { Authorization: "Bearer " + process.env.MEGABRAIN_API_KEY };
const ALLOWED = (process.env.ALLOWED_USER_IDS ?? "").split(",").filter(Boolean);
const DAILY_CAP_USD = Number(process.env.DAILY_CAP_USD ?? "1");

const spent = new Map<string, number>(); // "userId:YYYY-MM-DD" -> dollars
const imageOf = new Map<number, string>(); // bot message_id -> image URL, for /animate

async function tg(method: string, body: Record<string, unknown> | FormData) {
  const isForm = body instanceof FormData;
  const r = await fetch(TG + "/" + method, {
    method: "POST",
    headers: isForm ? undefined : { "Content-Type": "application/json" },
    body: isForm ? body : JSON.stringify(body),
  });
  const json = await r.json();
  if (!json.ok) throw new Error(method + ": " + json.description);
  return json.result;
}

// Submit a job to the MegaBrain queue, wait for it, return the model's output.
async function generate(model: string, input: Record<string, unknown>, userId: string) {
  const key = userId + ":" + new Date().toISOString().slice(0, 10);
  if ((spent.get(key) ?? 0) >= DAILY_CAP_USD) throw new Error("Daily limit reached.");

  const r = await fetch(MB + "/queue/" + model, {
    method: "POST",
    headers: { ...AUTH, "Content-Type": "application/json" },
    body: JSON.stringify(input),
  });
  // 400 = unknown field, 402 = balance too low, 422 = input rejected (not charged)
  if (!r.ok) throw new Error(model + ": HTTP " + r.status + " " + (await r.text()));
  const job = await r.json();
  spent.set(key, (spent.get(key) ?? 0) + (job.cost_usd ?? 0));

  for (;;) {
    await new Promise(res => setTimeout(res, 3000));
    const { status } = await (await fetch(job.status_url, { headers: AUTH })).json();
    if (status === "COMPLETED") break;
    if (status === "FAILED") throw new Error("Generation failed; the cost was refunded.");
  }
  return (await fetch(job.response_url, { headers: AUTH })).json();
}

// Download a finished file and upload it to the chat (multipart: 10 MB photos, 50 MB video).
async function sendFile(chatId: number, kind: "photo" | "video", url: string, caption: string) {
  const blob = await (await fetch(url)).blob();
  const form = new FormData();
  form.append("chat_id", String(chatId));
  form.append("caption", caption.slice(0, 1024));
  form.append(kind, blob, kind === "photo" ? "image.jpg" : "clip.mp4");
  return tg(kind === "photo" ? "sendPhoto" : "sendVideo", form);
}

// Pick the largest copy of a Telegram photo that stays at or under 1 megapixel,
// download it with the bot token on our side, and pass it to the model as a data: URL.
async function photoAsDataUrl(sizes: { file_id: string; width: number; height: number }[]) {
  const fit = sizes.filter(s => s.width * s.height <= 1_000_000);
  const best = (fit.length ? fit : sizes.slice(0, 1)).at(-1)!;
  const file = await tg("getFile", { file_id: best.file_id });
  const bytes = await (
    await fetch("https://api.telegram.org/file/bot" + process.env.TELEGRAM_BOT_TOKEN + "/" + file.file_path)
  ).arrayBuffer();
  return "data:image/jpeg;base64," + Buffer.from(bytes).toString("base64");
}

async function handle(msg: any) {
  const chatId: number = msg.chat.id;
  const userId = String(msg.from?.id ?? "");
  if (ALLOWED.length && !ALLOWED.includes(userId)) return; // keep strangers off your balance
  const text: string = msg.text ?? msg.caption ?? "";

  if (text.startsWith("/start")) {
    await tg("sendMessage", {
      chat_id: chatId,
      text: "Send a description to get an image. Send a photo with a caption to edit it. Reply /animate to one of my images for a 5-second clip.",
    });
    return;
  }

  if (text.startsWith("/animate")) {
    const source = msg.reply_to_message && imageOf.get(msg.reply_to_message.message_id);
    if (!source) {
      await tg("sendMessage", { chat_id: chatId, text: "Reply /animate to an image I made." });
      return;
    }
    await tg("sendChatAction", { chat_id: chatId, action: "upload_video" });
    const motion = text.replace("/animate", "").trim() || "slow camera push-in, gentle natural motion";
    const out = await generate(
      "kling-video/v2.6/pro/image-to-video",
      { prompt: motion, start_image_url: source, duration: "5", generate_audio: false },
      userId,
    );
    await sendFile(chatId, "video", out.video.url, "Kling 2.6 Pro, 5 s: $0.4025");
    return;
  }

  if (!text) return;
  await tg("sendChatAction", { chat_id: chatId, action: "upload_photo" });

  const out = msg.photo
    ? await generate(
        "flux-2/edit",
        { prompt: text, image_urls: [await photoAsDataUrl(msg.photo)], output_format: "jpeg" },
        userId,
      )
    : await generate(
        "flux-2/flash",
        { prompt: text, image_size: "landscape_4_3", output_format: "jpeg" },
        userId,
      );

  const url: string = out.images[0].url;
  const sent = await sendFile(chatId, "photo", url, msg.photo ? "FLUX 2 Edit" : "FLUX 2 Flash: $0.0058");
  imageOf.set(sent.message_id, url);
}

// Long polling: no server, no webhook, no public URL.
let offset = 0;
for (;;) {
  try {
    const updates = await tg("getUpdates", { offset, timeout: 50, allowed_updates: ["message"] });
    for (const u of updates) {
      offset = u.update_id + 1;
      if (!u.message) continue;
      handle(u.message).catch(err =>
        tg("sendMessage", { chat_id: u.message.chat.id, text: String(err.message ?? err) }).catch(() => {}),
      );
    }
  } catch (err) {
    console.error(err);
    await new Promise(res => setTimeout(res, 5000));
  }
}

Run it

Create a bot with @BotFather in Telegram and copy its token. Your MegaBrain key is on the API key page of your account. The .mts extension tells Node the file is an ES module, which the top-level polling loop needs.

mkdir tg-image-bot && cd tg-image-bot
# save the code above as bot.mts
export TELEGRAM_BOT_TOKEN="token from @BotFather"
export MEGABRAIN_API_KEY="your MegaBrain key"
export ALLOWED_USER_IDS="123456789"   # your Telegram user id; comma-separate more
export DAILY_CAP_USD="1"
npx tsx bot.mts

To find your Telegram user id, start the bot with ALLOWED_USER_IDS empty, send it a message and log msg.from.id once, then set the variable and restart. On Node 22.6 or newer you can also skip tsx: node --experimental-strip-types bot.mts.

5 decisions in the code that save money or trouble

1. The allowlist comes first

A Telegram bot is public: anyone who guesses its @name can message it. Without ALLOWED_USER_IDS the bot works for everyone, on your balance. The check is the first line of handle(), before any model is called.

2. The daily cap reads the real price

Every queue submit returns cost_usd, so the bot adds the actual price to a per-user total and refuses new jobs once it reaches DAILY_CAP_USD. The check runs before each job, so the last one can cross the line: with a $1 cap a user gets 173 images or 3 clips ($1.2075) a day. The Map lives in memory and resets on restart; write it to a file or Redis if that matters.

3. Photos go to the model as data: URLs

Telegram’s file links have the form https://api.telegram.org/file/bot<token>/…, so handing one to any outside service hands over your bot token. The bot downloads the photo itself (Telegram lets bots download files up to 20 MB) and sends it as a base64 data: URL, which FLUX 2 Edit accepts in image_urls.

4. The input photo is picked at 1 megapixel

FLUX 2 Edit bills every started megapixel of the output and of each input image, and the output follows the input when image_size is left out. Telegram sends several sizes of every photo in msg.photo, so the bot takes the largest one at or under 1,000,000 pixels. That keeps an edit at 2 megapixels, $0.0276. Why sizes just over a million pixels double the bill is in our FLUX 2 prompting guide.

5. generate_audio: false on every clip

Kling 2.6 Pro defaults to generating sound, which doubles the price to $0.161 a second. A bot that makes clips for posts and stories rarely needs model-made sound. Turn sound on for a /animate_sound command if your users ask for it, and charge it to the cap like everything else.

Telegram limits that shape the code

LimitValueWhat the bot does
Photo upload (multipart)10 MBAsks FLUX for jpeg, not the default png
Photo sent by URL5 MBUploads the file instead of passing the URL
Video upload50 MBA 5-second clip fits easily
File download by a bot20 MBPicks a photo size at or under 1 megapixel
Caption1,024 charactersTrims captions with slice(0, 1024)
Chat actionshows for up to 5 secondsSends upload_photo or upload_video once

The errors your users will see, and what they mean

The bot sends every error back to the chat as text, so you can debug from your phone. The media API uses 4 answers worth knowing:

AnswerMeaningCharged?
HTTP 400A field the model does not take, often a typo in a field nameNo
HTTP 402Your balance is too low for this jobNo
HTTP 422The model rejected the input on submitNo
Status FAILEDThe model failed the job after it was queuedRefunded to your balance

A 402 in a shared bot usually means the cap is higher than your top-ups. Lower DAILY_CAP_USD before you add funds again, or every user drains the new balance at the old rate.

Build it with your coding agent instead

If you would rather have an agent write it, paste this into Cursor, Claude Code or Codex. It describes the same bot, plus /help and a /spent command.

Build a Telegram bot in one TypeScript file, bot.mts, with no dependencies
(Node 20+, global fetch and FormData), using long polling (getUpdates, timeout 50).

Media API: base URL https://getmegabrain.com/api/gateway/v1, header
"Authorization: Bearer $MEGABRAIN_API_KEY". POST /queue/<model id> with the model's
fields returns request_id, status_url, response_url and cost_usd. Poll status_url
every 3 seconds until COMPLETED or FAILED, then GET response_url.
Docs: https://getmegabrain.com/docs/media

1. Text message -> model "flux-2/flash", body {prompt, image_size: "landscape_4_3",
   output_format: "jpeg"}. Output images[0].url. Download it and sendPhoto as multipart.
2. Photo with caption -> model "flux-2/edit", body {prompt: caption, image_urls: [data URL],
   output_format: "jpeg"}. Pick the largest PhotoSize with width*height <= 1,000,000,
   download it with getFile, and send it as a base64 data: URL. Never send the
   Telegram file URL (it contains the bot token).
3. Reply "/animate <motion>" to an image the bot sent -> model
   "kling-video/v2.6/pro/image-to-video", body {prompt, start_image_url: that image URL,
   duration: "5", generate_audio: false}. Output video.url. Download and sendVideo.

Guardrails: ignore users not in ALLOWED_USER_IDS; keep a per-user daily total of
cost_usd and refuse new jobs past DAILY_CAP_USD; send errors (HTTP 400, 402, 422,
FAILED) back to the chat as text. Then add /help and a /spent command.

To run Claude Code or Codex itself on MegaBrain models, follow the Claude Code setup guide or the Codex setup guide. If you want an assistant that already lives in Telegram, with scheduled jobs and skills, instead of a bot you maintain, see the OpenClaw guide or the Hermes Agent guide; both can call the same media API from a skill.

What this means if you build with AI media

Price video and images as different products. On a per-command basis the gap is 69x. If you resell the bot, a flat fee per message loses money on /animate; charge per clip or give each user a number of clips.

Start on the cheap model, upgrade one command. Swap “flux-2/flash” for “flux-2” ($0.0138 at 1024×768) when you need more detail, or “nano-banana-pro” for infographics and text inside the image, and “kling-video/v2.6/pro/image-to-video” for Kling 3.0 when you need 3 to 15 seconds. Only the model id and its fields change; the queue code stays the same.

Keep the guardrails when you scale. Long polling handles a team or a community. For thousands of users, move to a webhook and a queue worker, persist the spend totals, and keep the allowlist or replace it with paid access.

Try it on MegaBrain

FLUX 2 Flash costs $0.0058 per megapixel and Kling 2.6 Pro image to video $0.0805 per second without sound. Each page has a playground and the request code; one key and one pay-as-you-go balance also run FLUX 2, Nano Banana, Seedream, Kling 3.0 and the text models.

Sources

Pages opened November 18, 2026. Prices and parameters come from MegaBrain’s model pages and API; Telegram limits from the Bot API reference. Monthly totals and the 69x ratio are our arithmetic on those prices. We did not render example images for this post.

Full disclosure: MegaBrain sells pay-as-you-go API access to image, video and text models, including FLUX 2 Flash, FLUX 2 Edit and Kling 2.6 Pro. MegaBrain is not affiliated with Black Forest Labs, Kuaishou or Telegram.

MegaBrain for Mac · an AI coworker

Give MegaBrain the task, not the steps.

It works on your files, writes documents, spreadsheets and decks, connects to your team’s tools and asks before anything risky. Free to start.

Newsletter

Stay in the loop

Get our latest AI research and guides. No spam, unsubscribe anytime.