Language: English | Русский | Español | Português | Türkçe | Deutsch | Français | Bahasa Indonesia | العربية | فارسی | Oʻzbek | हिन्दी | 中文 | اردو | Tagalog | አማርኛ

← Home

Telegraf (Node.js): get chat_id and user ID

In Telegraf (Node.js Telegram Bot framework), you get chat_id and user_id from the context. Here are examples.

From a message

bot.on('message', (ctx) => {
  const chatId = ctx.chat.id;
  const userId = ctx.from.id;
  return ctx.reply(`Chat ID: ${chatId}, User ID: ${userId}`);
});

From a callback query

bot.on('callback_query', (ctx) => {
  const chatId = ctx.chat.id;
  const userId = ctx.from.id;
  return ctx.answerCbQuery().then(() =>
    ctx.reply(`Chat ID: ${chatId}, User ID: ${userId}`)
  );
});

From channel_post

bot.on('channel_post', (ctx) => {
  const chatId = ctx.chat.id;  // channel ID
  return ctx.reply(`Channel ID: ${chatId}`);
});

Debugging with @print_id_bot

Use @print_id_bot to inspect the raw update:

Forward a message to the bot and send /dump to see the exact structure Telegraf receives.

FAQ

Where is chat_id in ctx?

ctx.chat.id. For most updates, ctx.chat is the chat where the update originated.

How do I get chat_id when the bot is added to a group?

When a user sends a message after the bot is added, ctx.chat.id in that message handler is the group chat_id. Or add @print_id_bot and send /id to get it manually.

Does Telegraf pass the raw update?

Yes. ctx.update contains the full Telegram update. Use /dump in @print_id_bot to compare.

What about ctx.message.chat.id?

Same as ctx.chat.id for message updates. Telegraf normalizes ctx.chat for convenience.

Can I use this for channels?

Yes. For channel_post, ctx.chat.id is the channel ID. Your bot must be an admin to receive those updates.


Use @print_id_bot /dump to inspect update structure for Telegraf.

Open @print_id_bot


Related pages