Telegram movie bot tutorial with grammY

A Telegram movie bot needs a BotFather token, an API key and about 100 lines of Node.js. This tutorial builds one with grammY: send /movie fight club and the bot replies with the poster, year, runtime and rating, using 2 API requests per new title. The bot shows movie information and never streams or downloads movies.

.js Telegram Updated View as Markdown

A Telegram movie search bot takes about 100 lines of Node.js: send /movie fight club and the bot replies with the poster, year, runtime and IMDb rating. The bot searches titles and shows information and ratings; it does not stream or download movies. Each new title costs 2 API requests, one search and one details call with ratings, so the 20 requests per minute plan serves about 10 new lookups a minute.

What do you need to build a Telegram movie bot?

You build a Telegram bot that answers /movie fight club with the poster, title, year, runtime and rating.

You needValue
RuntimeNode.js 20.6 or newer, for the --env-file option and the built-in fetch
Packages1: grammy
TelegramA bot token from BotFather, inside Telegram
KeyAn amodb key, 32 lowercase hex characters. The TMDB API key page shows how to get one
HostingAny machine that stays online. Long polling needs no public address
TimeAbout 20 minutes

Which calls does the Telegram movie bot make, and what do they cost?

Every call to the API costs 1 request, and a reply served from the edge cache counts too. The poster comes from a separate host that needs no key and is not counted.

CallPathCostBot cache
SearchGET /search/movie?query={title}&language=en-US1 request10 minutes
Details with ratingsGET /movie/{id}?language=en-US&append_to_response=ratings1 request6 hours
Posterhttps://img.amodb.dev/t/p/w500{poster_path}0 requestsTelegram downloads it

The limit belongs to your amodb account, so every chat that uses your bot shares it, along with any other app on the same account. A second key does not add requests. At 20 requests per minute that is 10 new titles a minute, and a title in the bot cache costs none. On that plan an account cannot pass 28,800 requests a day. The TMDB search API page describes the search call in full.

Step 1: Get two credentials

Buy an amodb plan with your email and sign in with the 6 digit code amodb then emails you to get your first key, then create a Telegram bot with BotFather and copy its token.

Open amodb pricing to pick the plan. Every plan has every TMDB v3 compatible endpoint, images, 14 languages and the extensions. The plans differ in rate (Lite 20, Pro 40, Pro+ 120 requests per minute, from $5.19 a month), and only Pro+ also has the all in one endpoint GET /3/all/{movie|tv|person}/{id}. There is no free tier or trial. The key is 32 lowercase hex characters. In Telegram, open a chat with BotFather, send /newbot, answer the two questions and copy the token it prints.

Put both values in a .env file and add that file to .gitignore:

Shell
BOT_TOKEN=YOUR_BOT_TOKEN
AMODB_KEY=YOUR_API_KEY

Step 2: Create the project

Create a Node.js project named movie-bot and install grammY.

The type setting turns on import syntax and top level await. The authentication page shows the header and the api_key forms of the key.

Shell
mkdir movie-bot && cd movie-bot
npm init -y
npm pkg set type=module
npm install grammy

Step 3: Answer the first command

Write a /movie command that searches amodb and replies with the title of the first result.

grammY puts the text after a command into ctx.match. Start with a helper that sends the Bearer header and a command that searches.

JavaScript
import { Bot } from 'grammy';

const bot = new Bot(process.env.BOT_TOKEN);

async function getJson(path, params) {
  const url = new URL('https://api.amodb.dev/3' + path);
  for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value);
  const res = await fetch(url, { headers: { Authorization: `Bearer ${process.env.AMODB_KEY}` } });
  return res.json();
}

bot.command('movie', async (ctx) => {
  const found = await getJson('/search/movie', { query: ctx.match, language: 'en-US' });
  await ctx.reply(found.results[0]?.title ?? 'No movie found.');
});

bot.start();

Step 4: Build the reply with a poster

Take the first search hit, load it with append_to_response=ratings and build a caption with the title, year, rating and runtime.

The poster URL is https://img.amodb.dev/t/p/w500 plus poster_path. Telegram downloads the photo itself, and img.amodb.dev needs no key. A caption holds at most 1024 characters, so the code cuts the overview.

Each source in ratings is an object with value and votes, or null. When imdb is null, the caption falls back to the aggregate vote_average. The movie ratings API page explains all five sources.

SourceScaleCan be null
imdb0 to 10yes
kinopoisk0 to 10yes
tmdb0 to 10yes
metacritic0 to 100yes
rotten_tomatoes0 to 100yes

To make a Telegram movie rating bot that shows more than IMDb, add a line for each source that is not null and skip the others.

JavaScript
function buildCaption(movie) {
  const year = (movie.release_date || '').slice(0, 4) || 'year unknown';
  const imdb = movie.ratings?.imdb;
  const rating = imdb
    ? `IMDb ${imdb.value}`
    : movie.vote_average ? `TMDB ${movie.vote_average.toFixed(1)}` : 'not known';
  const lines = [`${movie.title} (${year})`, `Rating: ${rating}`];
  if (movie.runtime) lines.push(`Runtime: ${movie.runtime} min`);
  if (movie.overview) lines.push('', movie.overview.slice(0, 600));
  return lines.join('\n').slice(0, 1024);
}

Step 5: Handle errors and rate limits

Let handlers throw and catch every error in one place with bot.catch, because grammY stops the bot when a handler throws and no catch exists.

CaseCauseBot reaction
401Key missing or invalid (status_code 7 for an invalid key)Log it, tell the chat, exit. Every command would fail.
429Over your requests per minute (status_code 25)Wait Retry-After seconds, capped at 30, retry twice, then ask the user to try later.
Empty resultsNo title matches the queryReply that no movie was found.
Timeout or network errorfetch throwsReply with a short apology and log the error.
Photo rejectedTelegram cannot fetch the imageSend the caption as text.

The loop below sits inside getJson. AmodbError is a small Error subclass with a status field, shown in the final listing.

Each command costs two requests, so the 20 requests per minute plan serves about 10 new lookups a minute. The error body uses the TMDB shape {"success": false, "status_code": N, "status_message": "..."}. See the TMDB API rate limit and error codes pages for the details.

JavaScript
for (let attempt = 0; ; attempt++) {
  const res = await fetch(id, { headers, signal: AbortSignal.timeout(10_000) });
  if (res.status === 429 && attempt < 2) {
    const seconds = Math.min(Number(res.headers.get('retry-after')) || 5, 30);
    await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
    continue;
  }
  if (!res.ok) throw new AmodbError(res.status);
  return res.json();
}

Step 6: Cache answers

Keep a Map from URL to data and an expiry time, using 10 minutes for search and 6 hours for details, the same lifetimes as the edge.

The rate limit check runs before the edge cache, so only a cache in your own bot saves requests. A size cap keeps a long running bot from growing without limit. The cache lines also sit inside getJson.

JavaScript
const hit = cache.get(id);
if (hit && hit.expires > Date.now()) return hit.data;
// ...after a successful fetch:
if (cache.size > 500) cache.delete(cache.keys().next().value);
cache.set(id, { data, expires: Date.now() + ttlMs });

Step 7: The complete bot

Save the complete listing below as bot.js and start it with the .env file.

JavaScript
import { Bot } from 'grammy';

const { BOT_TOKEN, AMODB_KEY } = process.env;
if (!BOT_TOKEN || !AMODB_KEY) {
  console.error('Set BOT_TOKEN and AMODB_KEY first.');
  process.exit(1);
}

const API = 'https://api.amodb.dev/3';
const IMG = 'https://img.amodb.dev/t/p/w500';
const headers = { Authorization: `Bearer ${AMODB_KEY}` };
const cache = new Map();

class AmodbError extends Error {
  constructor(status) {
    super(`amodb returned ${status}`);
    this.status = status;
  }
}

async function getJson(path, params, ttlMs) {
  const url = new URL(API + path);
  for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value);
  const id = url.toString();

  const hit = cache.get(id);
  if (hit && hit.expires > Date.now()) return hit.data;

  for (let attempt = 0; ; attempt++) {
    const res = await fetch(id, { headers, signal: AbortSignal.timeout(10_000) });
    if (res.status === 429 && attempt < 2) {
      const seconds = Math.min(Number(res.headers.get('retry-after')) || 5, 30);
      await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
      continue;
    }
    if (!res.ok) throw new AmodbError(res.status);
    const data = await res.json();
    if (cache.size > 500) cache.delete(cache.keys().next().value);
    cache.set(id, { data, expires: Date.now() + ttlMs });
    return data;
  }
}

function buildCaption(movie) {
  const year = (movie.release_date || '').slice(0, 4) || 'year unknown';
  const imdb = movie.ratings?.imdb;
  const rating = imdb
    ? `IMDb ${imdb.value}`
    : movie.vote_average ? `TMDB ${movie.vote_average.toFixed(1)}` : 'not known';
  const lines = [`${movie.title} (${year})`, `Rating: ${rating}`];
  if (movie.runtime) lines.push(`Runtime: ${movie.runtime} min`);
  if (movie.overview) lines.push('', movie.overview.slice(0, 600));
  return lines.join('\n').slice(0, 1024);
}

const bot = new Bot(BOT_TOKEN);

bot.command('start', (ctx) =>
  ctx.reply('Send /movie and a title, for example /movie fight club.'));

bot.command('movie', async (ctx) => {
  const title = ctx.match.trim();
  if (!title) return ctx.reply('Usage: /movie fight club');
  await ctx.replyWithChatAction('typing');

  const found = await getJson('/search/movie', { query: title, language: 'en-US' }, 10 * 60_000);
  const hit = found.results[0];
  if (!hit) return ctx.reply(`No movie found for "${title}".`);

  const movie = await getJson(
    `/movie/${hit.id}`,
    { language: 'en-US', append_to_response: 'ratings' },
    6 * 60 * 60_000,
  );
  const caption = buildCaption(movie);
  if (!movie.poster_path) return ctx.reply(caption);
  try {
    await ctx.replyWithPhoto(IMG + movie.poster_path, { caption });
  } catch {
    await ctx.reply(caption);
  }
});

bot.catch(async ({ ctx, error }) => {
  console.error('Update failed:', error);
  if (error instanceof AmodbError && error.status === 401) {
    console.error('amodb rejected AMODB_KEY (401). Fix the key and restart.');
    await ctx.reply('The bot key was rejected. The owner has to fix it.').catch(() => {});
    process.exit(1);
  }
  const text = error instanceof AmodbError && error.status === 429
    ? 'Too many requests right now. Try again in a minute.'
    : 'The movie service did not answer. Try again later.';
  await ctx.reply(text).catch(() => {});
});

await bot.api.setMyCommands([{ command: 'movie', description: 'Find a movie by title' }]);
process.once('SIGINT', () => bot.stop());
process.once('SIGTERM', () => bot.stop());
bot.start({ onStart: (me) => console.log(`Running as @${me.username}`) });

Start it with the .env file, then send /movie fight club to your bot in Telegram.

Shell
node --env-file=.env bot.js

For /movie fight club the first search hit is movie 550. The bot sends its poster, https://img.amodb.dev/t/p/w500/jSziioSwPVrOy9Yow3XhWIBDjq1.jpg, with this caption:

The bot uses long polling, so it needs no public address. Keep the process running with the tool you already use for services.

Text
Fight Club (1999)
Rating: IMDb 8.8
Runtime: 139 min

A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground "fight clubs" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.

How do I keep the Telegram movie bot running?

Run node --env-file=.env bot.js under a process manager that restarts it after a crash, such as systemd, pm2 or a Docker restart policy.

The bot exits with code 1 when amodb answers 401, because every command would fail from then on. Set a restart delay of at least 30 seconds in your process manager, or the restarts loop and every pass sends one more rejected request. Fix the key, then start the bot again. The bot handles SIGINT and SIGTERM, so a normal stop ends the polling cleanly.

Is the TMDB API free to use for a Telegram bot?

The TMDB API is free only while your bot earns nothing, and a bot that takes donations or sells subscriptions needs a paid plan.

TMDB staff said on the TMDB forum (2026-10-15) that an app counts as commercial the moment it earns revenue from ads, in-app purchases, donations or subscriptions. They quoted the commercial plan at $149 a month for companies under $1M revenue, with a custom quote above (2026-03-31), and there is no small tier between free and $149. TMDB's terms of use also require its logo with a not-endorsed notice and limit caching to 6 months.

ProjectTMDBamodb
Hobby bot, earns nothingFree under TMDB's termsPaid, from $5.19 a month, no free tier
Bot with donations, ads or subscriptions$149 a month under $1M revenue, custom quote aboveFrom $5.19 a month, no extra charge; the terms do not prohibit it
Logo or attributionTMDB logo and notice requiredNo amodb logo; credit JustWatch and licensed texts and images as marked

amodb plans cost $5.19, $6.19 or $7.19 a month, which is 3.5% to 4.8% of $149, and longer periods save up to 40 percent. Pay by card, Apple Pay or Google Pay, prepaid for 1, 3, 6, 12 or 24 months; those payments do not renew automatically. Patreon is monthly and renews on Patreon until the member cancels there. Do not resell raw API access or share keys. Read Is the TMDB API free? for the full comparison.

Next steps

  • Add /trending with the trending/movie/week call from the TMDB trending API page.
  • Let users pick one of five results with an inline keyboard, using more of the TMDB search API response.
  • Send trailers with the TMDB trailer API endpoint.
  • Switch language to a user's language with the language codes page.
  • Build the same command for Discord, or read the quickstart for a first request in any language.
  • Browse every guide in the tutorials hub.