Telegram Bot: Getting a chat id

Cyrille
2 min readFeb 27, 2023

--

This tutorial is the first of a series. It covers how to create a telegram bot that returns a chat id.

Getting a chat id in telegram is not as easy as it should be :) I would expect to find it in the UI interface (at least for admins), but sadly, it’s not there.

In order to get it, we are going to create a bot that returns the chat id when given the/chat_id command.

Photo by Rubaitul Azad on Unsplash

Prerequisites

  1. Create a Telegram group
  2. Create a Telegram bot using botfather and remember its token
  3. Add the Telegram bot to your telegram group

Coding

mkdir telegram-basic-tutorial
cd telegram-basic-tutorial
yarn add --dev typescript @types/node
npx tsc --init
yarn add grammy dotenv
touch bot.ts
touch .env

Open the tsconfig.json file and uncomment + modify the outDir row. Now the build will be stored in the /dist folder.

...
"outDir": "./dist",
...

We are adding the grammy and dotenv libraries to the project and creating our bot.ts file. Let’s edit our bot.ts file.

import { Bot } from "grammy";
import dotenv from "dotenv";

// import token from .env file
dotenv.config()
const token = String(process.env.TOKEN)

const bot = new Bot(token)

bot.on("message", ctx => ctx.reply("Hi there!"))

bot.start();

This is the boilerplate code for listening with a bot. It will respond “Hi there!” to any message.

In your .env file, add the TOKEN variable that your generated from botfather:

TOKEN=YOUR-TOKEN-FROM-BOTFATHER

Now, let’s build and run our bot.

npx tsc
node dist/bot.js

Now type anything into your group, and your bot will respond “Hi there!”.

Ok, now let’s modify our code. When we type the command /chat_id into the group, it should return the chat_id.

import { Bot } from "grammy";
import dotenv from "dotenv";

// import token from .env file
dotenv.config()
const token = String(process.env.TOKEN)

const bot = new Bot(token)

bot.command("chat_id", ctx => ctx.reply(ctx.chat.id.toString()))

bot.start();

Now, let’s build and run our bot.

npx tsc
node dist/bot.js

Type /chat_id into your group and it should return a negative number. Congratulations you now know your chat id!

You can now use this chat id to implement different services for your bot. Our next article will cover how we can use grammy to get metadata from telegram and display it on a web app. Stay tuned!

Github Code.

--

--

Cyrille

I build web2 and web3 products and teams. Depending on the project, I operate as a CTO, product manager, developer, advisor, or investor.