How to Create a Telegram Bot and Get the Chat ID

    How to Create a Telegram Bot and Get the Chat ID

    Create a Telegram bot with BotFather, find the chat ID of a private chat or group with getUpdates, and send messages with curl, Node.js and Python.

    To create a Telegram bot, open a chat with @BotFather in Telegram, send /newbot, and choose a name and a username that ends in "bot". BotFather replies with a token, which your code uses to call the Bot API. To send messages you also need a chat ID: send your bot a message, call getUpdates with the token, and read chat.id from the response.

    This guide covers each step, including the chat ID of a group, and ends with code that sends a message from curl, Node.js and Python. The steps follow Telegram's bot features guide and Bot API reference as of November 2026.

    Step 1: Create the bot with BotFather

    BotFather is Telegram's own bot for creating and managing bots. Everything happens in a chat with it.

    1. In Telegram, search for @BotFather and open the chat.
    2. Send /newbot.
    3. Enter the bot's name. This is the display name people see in the chat and in contact details. You can change it later with /setname.
    4. Enter the bot's username. It must be 5 to 32 characters long, may only use Latin letters, numbers and underscores, and must end in "bot", as in tetris_bot or TetrisBot. Choose carefully: the username can't be changed later.
    5. BotFather replies with the bot's token, a string like 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw (Telegram's own example).

    BotFather also has a Mini App with the same functions in a graphical interface, if you prefer it to commands.

    Keep the token secret

    Anyone with the token can control the bot, so treat it like a password. Keep it in an environment variable or a secrets manager, not in your code or your repository. If it leaks, send /token to BotFather to generate a new one.

    The examples below read the token from an environment variable:

    export TELEGRAM_BOT_TOKEN="110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw"
    

    Check that the token works

    Every Bot API request goes to https://api.telegram.org/bot<token>/<method>. Note the word bot in front of the token. The getMe method needs no parameters and is meant for testing the token:

    curl "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getMe"
    

    Every response is JSON with an ok field. If ok is true, the result holds your bot's details. If it is false, the description field says what went wrong.

    Step 2: Get the chat ID

    A bot can't start a conversation. A person has to message it first, or add it to a group. Until then, the bot has no chat to send to, and you have no chat ID to look up.

    The chat ID of a private chat

    1. Open your bot at https://t.me/<your_bot_username> and tap Start, or send it any message.

    2. Ask Telegram for the bot's recent updates:

      curl "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates"
      
    3. Find message.chat.id in the response. Shortened, it looks like this:

      {
        "ok": true,
        "result": [
          {
            "update_id": 830154927,
            "message": {
              "message_id": 1,
              "from": { "id": 123456789, "is_bot": false, "first_name": "Ana" },
              "chat": { "id": 123456789, "first_name": "Ana", "type": "private" },
              "date": 1795512600,
              "text": "/start"
            }
          }
        ]
      }
      

    Here the chat ID is 123456789. In a private chat, the chat ID is the same as the user's ID and is a positive number.

    If result is an empty list, check three things:

    • Telegram keeps updates for at most 24 hours. Send the bot a new message and call getUpdates again.
    • getUpdates doesn't work while the bot has a webhook set. If you set one earlier, remove it with the deleteWebhook method first.
    • Each update is returned until you confirm it, by calling getUpdates with an offset higher than its update_id. If another program is already polling with the same token, it may have confirmed your update before you saw it.

    The chat ID of a group

    1. Add the bot to the group, as you would add a person.

    2. In the group, send a command addressed to the bot by its username, such as /start@your_bot_username.

    3. Call getUpdates and find the group's chat object:

      "chat": { "id": -1001234567890, "title": "Ops team", "type": "supergroup" }
      

    Group chat IDs are negative. A supergroup's or a channel's ID has 13 digits after the minus sign, as in the example above; a basic group's ID is shorter.

    The command in step 2 matters because of privacy mode. By default, a bot in a group doesn't see ordinary messages. It receives commands addressed to it, replies to its messages, and service messages such as people joining. A bot that is a group admin, or one with privacy mode turned off in BotFather (/setprivacy, after which you re-add the bot to the group), receives every message except those from other bots. For finding the chat ID, the command is enough.

    Two more things about chat IDs:

    • When a basic group is upgraded to a supergroup, its ID changes. The old group receives a message with a migrate_to_chat_id field holding the new ID; update the ID you stored, or your messages stop arriving.
    • Chat IDs can be larger than a 32-bit integer can hold. Telegram says they fit in a signed 64-bit integer or a double-precision float, so store them as one of those, or as a string.

    For a public supergroup or channel, you can also send to its username, written as @channelusername, instead of the numeric ID.

    Step 3: Send a message

    The sendMessage method needs two parameters: chat_id and text. The text can be 1 to 4,096 characters long after formatting is parsed. Add "parse_mode": "HTML" to use simple formatting tags such as <b>, <i>, <code> and <a href="...">.

    With curl

    curl -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage" \
      -H "Content-Type: application/json" \
      -d '{"chat_id": 123456789, "parse_mode": "HTML",
           "text": "Nightly import finished: <b>1,204</b> rows"}'
    

    With Node.js

    This uses the fetch built into Node.js 18 and later, so there is nothing to install:

    const token = process.env.TELEGRAM_BOT_TOKEN;
    const chatId = process.env.TELEGRAM_CHAT_ID;
    
    async function sendTelegram(text) {
      const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ chat_id: chatId, text, parse_mode: 'HTML' }),
      });
      const data = await res.json();
      if (!data.ok) throw new Error(`Telegram: ${data.description}`);
      return data.result;
    }
    
    sendTelegram('Nightly import finished: <b>1,204</b> rows').catch(console.error);
    

    With Python

    This uses only the standard library:

    import json
    import os
    import urllib.request
    
    def send_telegram(text):
        token = os.environ["TELEGRAM_BOT_TOKEN"]
        body = json.dumps({
            "chat_id": os.environ["TELEGRAM_CHAT_ID"],
            "text": text,
            "parse_mode": "HTML",
        }).encode()
        request = urllib.request.Request(
            f"https://api.telegram.org/bot{token}/sendMessage",
            data=body,
            headers={"Content-Type": "application/json"},
        )
        with urllib.request.urlopen(request, timeout=10) as response:
            return json.load(response)
    
    send_telegram("Nightly import finished: <b>1,204</b> rows")
    

    For a wrong chat ID, a bot the user has blocked or a bad token, Telegram answers with an error status, which urlopen raises as an HTTPError. Its body holds the same description field.

    Formatting and limits

    • In HTML mode, any <, > or & that isn't part of a tag must be written as &lt;, &gt; or &amp;. Escape text that comes from users or logs before you send it, or the request fails.
    • Split text longer than 4,096 characters into several messages.
    • Telegram's FAQ asks bots to send no more than about one message per second to a single chat, and no more than 20 messages a minute to a group. Above that, requests start failing with status 429.

    Connect users without asking for their chat ID

    Asking people to look up a chat ID doesn't work for a product. The usual way around it is a deep link. A link like https://t.me/your_bot_username?start=CODE opens a chat with your bot, and when the person taps Start, your bot receives the message /start CODE. The update carries the chat ID, so your server matches CODE to the account that created the link and saves the chat. Telegram allows the letters A-Z and a-z, digits, _ and - in the code, up to 64 characters. Make each code random, use it once and let it expire.

    To receive that /start message as it happens, the bot needs a webhook or a process that keeps calling getUpdates. For sending alone, a single HTTPS request like the ones above is all it takes.

    Reports in Telegram without your own bot

    A common reason to build a bot is to get a regular summary of what happened in an app: signups, orders, failed jobs. For that, Eventkiwi has its own Telegram bot, so you don't create a bot or look up a chat ID.

    Eventkiwi connects a chat with the deep-link method described above:

    1. Open Channels in the Eventkiwi app and choose Connect Telegram.
    2. For a private chat, scan the QR code or click Open Telegram. The Eventkiwi bot replies to confirm the chat is connected.
    3. For a group, add the Eventkiwi bot to the group (the dialog shows its username) and send the /start command shown in the dialog.
    4. Add the new channel to an aggregator (in Eventkiwi, a container for your events with its own report schedule).

    The link and the command work once and expire after an hour. Sending /stop in the chat stops reports there, and Send test on the Channels page sends a sample report so you can check you picked the right chat.

    Your code then sends events to Eventkiwi with one HTTP request each:

    curl -X POST "https://app.eventkiwi.com/api/event?_id=YOUR_AGGREGATOR_ID" \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"name": "import_completed"}'
    

    On the schedule you set (hourly, daily, weekly or monthly, in your timezone), the report arrives as a text message followed by trend charts. The text has a short written summary, then up to 20 events with their counts, the change since the last report and the top tags. The charts follow as one or more images. With sample data, it looks like this:

    Telegram08:00

    Daily report — My shop

    Orders up 12% on Monday, two thirds of them on the Pro plan. Signups are flat. Failed payments halved, down to 9.

    • • order_paid: 184 (+20 (+12%))
    • • user_signup: 212 (+3 (+1%))
    • • payment_failed: 9 (−10 (−53%))
    order_paid+12%
    184
    user_signup+1%
    212
    payment_failed−53%
    9
    refund_requested+14%
    8

    An Eventkiwi report is a scheduled summary of counts. If you need a message the moment something happens, such as a deploy finishing, your own bot and sendMessage are the right tool. The Telegram channel docs cover the setup in more detail, and the post on Telegram reports explains how the charts are designed for a phone.

    Questions

    Is creating a Telegram bot free? Yes. Telegram's FAQ says bots can message their users at no cost by default. Telegram charges, in Telegram Stars, only for paid broadcasts, which let a bot send more than about 30 messages per second.

    Can a bot message someone who hasn't started it? No. A person has to send the bot a message or add it to a group first.

    Why does getUpdates return an empty list? Usually because no one has messaged the bot in the last 24 hours, because a webhook is set, or, in a group, because the bot didn't receive the message due to privacy mode. Send /start@your_bot_username in the chat and try again.

    Can I change my bot's username? No. You can change the name with /setname, but the username is fixed once the bot is created. To use a different username, create a new bot.

    Do I need a server to send messages? No. Sending is one HTTPS request, so a cron job, a CI step or a serverless function can do it. You need a running process or a webhook only to receive messages.