412

I've been using telegram_bot, and trying to get groupChat id to send notifications to group chat, but don't know which methods I have to use for it.

For getting chat id I use to message.chat.id when the bot participated in the chat but which I have to use for getting group chat id can't find/

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Roman Podpryatov
  • 4,121
  • 3
  • 10
  • 5

20 Answers20

555

In order to get the group chat id, do as follows:

  1. Add the Telegram BOT to the group.

  2. Get the list of updates for your BOT:

https://api.telegram.org/bot<YourBOTToken>/getUpdates

Ex:

https://api.telegram.org/bot123456789:jbd78sadvbdy63d37gda37bd8/getUpdates
  1. Look for the "chat" object:

{"update_id":8393,"message":{"message_id":3,"from":{"id":7474,"first_name":"AAA"},"chat":{"id":<group_ID>,"title":""},"date":25497,"new_chat_participant":{"id":71,"first_name":"NAME","username":"YOUR_BOT_NAME"}}}

This is a sample of the response when you add your BOT into a group.

  1. Use the "id" of the "chat" object to send your messages.

  2. (If you created the new group with the bot and you only get {"ok":true,"result":[]}, remove and add the bot again to the group)

  3. Private chart only works in image argoprojlabs/argocd-notifications:v1.1.0 or above.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Maverick_Java
  • 5,665
  • 2
  • 13
  • 15
  • 1
    can u provide an example? – Roman Podpryatov Oct 06 '15 at 21:49
  • How to add bot to group? Created a bot, Did /setjoingroups. What is the next step? – WannaBeCoder Jan 20 '16 at 18:04
  • 1
    Jost got to your bot profile and click "add to group". Bots can't be invited into group like normal users. – golodenko Jan 27 '16 at 11:25
  • 5
    @WannaBeCoder, you can add a BOT to a group just like any other member: Go to your group properties, click on add member, then use the search icon to look for the BOT's name. BUT, keep in mind that since recent changes on Telegrams groups, you must be a group "admin" to add a new member, whether they are BOTs or not. – Maverick_Java Jan 28 '16 at 12:53
  • @Maverick_Java I was not the group admin. Figured out now. Thanks. – WannaBeCoder Jan 29 '16 at 06:17
  • 119
    For newly created group `getUpdates` request returns `{"ok":true,"result":[]}` even if I try to send bunch of messages to the group and mention bot via `@` and some random "commands" `/my_id`, `/start`, `/help`. Any ideas what to do? - UPDATE: OK, removing bot from group, and adding bot back fixed this issue (also it printed chat id in the group) --- looks like bot can't be added during group creation. – rutsky Apr 21 '17 at 23:23
  • @rutsky glad you got it working. removing and adding to group 2nd time was not the resolution here ... cant get chat id and also for me getUpdates request returns {"ok":true,"result":[]} – snh_nl Dec 19 '17 at 20:03
  • 30
    this returns: {"ok":true,"result":[]} – Tom Jan 15 '18 at 02:29
  • 6
    Hi @Tom. Have you already tried rutsky solution: "removing bot from group, and adding bot back fixed this issue (also it printed chat id in the group) --- looks like bot can't be added during group creation. " ? I have faced the same problem a couple of times, and removing the bot from group and adding it over again always solved the problem. Let me know if this won't help you. – Maverick_Java Jan 17 '18 at 11:35
  • @Maverick_Java yep it worked. i just added a different bot (and made sure to make the changes prior to adding it) – Tom Jan 18 '18 at 01:41
  • 11
    @tom, if you get {"ok":true,"result":[]} , type something into the bot channel. After this, you should get chat_id – guagay_wk Sep 24 '19 at 01:28
  • You can use url https://api.telegram.org/bot/getme – mincasoft Jun 28 '20 at 16:37
  • (If you created the new group with the bot and you only get {"ok":true,"result":[]}, remove and add the bot again to the group) It save me, thank you – cheng Aug 02 '21 at 04:33
  • step 2: `{"ok":false,"error_code":404,"description":"Not Found"}%` – Dr.jacky Jan 06 '22 at 14:15
  • after you created the bot, open bot and click Start then it will return chat_id – Wasim A. May 30 '22 at 06:17
  • To clarify what @WasimA. said: You need to start a chat with the bot, like with a normal user, then press start. That issues a `/start` command. But - this still doesn't help. I still get `{"ok":true,"result":[]}` – einpoklum Apr 09 '23 at 21:08
297

Here is the sequence that worked for me after struggling for several hours:

Assume the bot name is my_bot.

1- Add the bot to the group.
Go to the group, click on group name, click on Add members, in the searchbox search for your bot like this: @my_bot, select your bot and click add.

2- Send a dummy message to the bot.
You can use this example: /my_id @my_bot
(I tried a few messages, not all the messages work. The example above works fine. Maybe the message should start with /)

3- Go to following url: https://api.telegram.org/botXXX:YYYY/getUpdates
replace XXX:YYYY with your bot token

4- Look for "chat":{"id":-zzzzzzzzzz,
-zzzzzzzzzz is your chat id (with the negative sign).

5- Testing: You can test sending a message to the group with a curl:

curl -X POST "https://api.telegram.org/botXXX:YYYY/sendMessage" -d "chat_id=-zzzzzzzzzz&text=my sample text"

If you miss step 2, there would be no update for the group you are looking for. Also if there are multiple groups, you can look for the group name in the response ("title":"group_name").

starball
  • 20,030
  • 7
  • 43
  • 238
apadana
  • 13,456
  • 15
  • 82
  • 98
  • 2
    Excellent breakup on how to get a BOT configured. – fear_matrix Apr 28 '17 at 08:40
  • I sent *one* message to the bot but it didn't work instantly, waiting a few seconds (or probably minutes) and trying curl again worked. – Benjamin Jun 10 '17 at 14:03
  • 9
    I cant get my bot working in the group, I get {"ok":true,"result":[]} in the browser. Hope someone can help me out – user234562 Jan 13 '18 at 08:19
  • 2
    This worked for me. One thing, if you have webhooks configured, you have to disable it. Thanks! – Erich García Jun 08 '18 at 02:19
  • are we replacing the word bot with the actual name of the bot created ? Banging my head against a wall here trying to get the chat id of a group ive created, thanks – Richlewis Nov 22 '18 at 22:33
  • 5
    @TheMrkt It seems, as said apadana, that sendind a message starting with `/` like `/test something` makes getUpdates happy. – Déjà vu Mar 11 '19 at 10:00
  • @ TheMrkt, you follow "Hoi_A " answer https://stackoverflow.com/questions/43291868/where-to-find-the-telegram-api-key. It's working for me... – Naresh May 07 '19 at 12:27
  • -(negative) sign is very important. If it is negative then it is group else private. – Vikas Gupta Sep 17 '19 at 09:34
  • Not sure if it's just me who's new to chatbot dev, but wouldn't this be a worthwhile addition to the documentation? – dTanMan Sep 25 '19 at 01:47
  • I just sent "Test" to my not and I found this message in updates. (Maybe for private chats different but I would think not, if not explicitly disabled) – E. Körner Apr 11 '20 at 10:35
  • 1
    I don't know why it's not working for me. I used my https://api.telegram.org/here contains my bot token/getUpdates, it doesn't work at all. It keeps saying "{"ok":false,"error_code":404,"description":"Not Found"}" – CCCC Sep 23 '21 at 13:10
  • Same as @CCCC I get `{"ok":false,"error_code":404,"description":"Not Found"}%` – Dr.jacky Jan 06 '22 at 14:13
  • 1
    This solution works well ultil July, 2022 when no webhook setup in your group. If you had setup webhook already, just check logs in your webhook received data. – PhatHV Jul 13 '22 at 09:34
  • Make sure that your bot is not running in any computer. In that case, it will consume (not sure if this is the right word or not) update messages. Otherwise, you will see `{"ok":true,"result":[]}` – Alperen May 19 '23 at 05:28
242

As of May 2021, simply:

  • Invite @RawDataBot to your group.

Upon joining it will output a JSON file where your chat id will be located at message.chat.id.

"message": {
    "chat": {
        "id": -210987654,
        "title": ...,
        "type": "group",
        ...
    }
    ...
}

Be sure to kick @RawDataBot from your group afterwards.

Lucio Paiva
  • 19,015
  • 11
  • 82
  • 104
eivamu
  • 3,025
  • 1
  • 14
  • 20
  • 9
    Where should @RawDataBot output this? I added the bot to my group, but nothing happend. Update: you need to have an username set in Telegram, otherwise nothing happens. – Frank Meulenaar Jan 19 '19 at 07:53
  • 4
    @Cherona: I just re-verified it. But it seems that the web client has changed such that inviting the bot is a bit harder than it used to be. Here's how you can do it: Search for RawDataBot in the search field. Click the contact to start a chat session. Click the chat title to open "Contact info". Click "Add to group" and choose the group. It will immediately output the info as before. Hope it works for you. – eivamu Mar 02 '20 at 13:15
  • 2
    Working perfectly fine as of May 2021. – Lucio Paiva May 16 '21 at 13:22
  • 10
    It's actually @raw_data_bot which did the job for me. – Dejv May 20 '21 at 11:36
  • 1
    OR Invite @ShowJsonBot to your group. – 0 cęĥ Feb 17 '23 at 17:18
83

After mid-2018:
1:) Invite @getidsbot or @RawDataBot to your group and get your group id from the chat id field.

Message
 ├ message_id: 338
 ├ from
 ┊  ├ id: *****
 ┊  ├ is_bot: false
 ┊  ├ first_name: 사이드
 ┊  ├ username: ******
 ┊  └ language_code: en
 ├ chat
 ┊  ├ id: -1001118554477    // This is Your Group id
 ┊  ├ title: Test Group
 ┊  └ type: supergroup
 ├ date: 1544948900
 └ text: A

2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.

Before mid-2018: (don't Use)
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm

lindhe
  • 806
  • 2
  • 14
  • 32
Saeed Heidarizarei
  • 8,406
  • 21
  • 60
  • 103
58

the simplest way i found using only telegram-web :

  • open web.telegram in browser ( chrome in my case )
  • right click on the group name on the left menu
  • click 'inspect' button
  • you will see the group id in the attribute data-peer-id="-xxxxxxxxxx" or peer="-xxxxxxxxxx"

group chat id : -xxxxxxxxxx

channel chat id : -100xxxxxxxxxx

(for some channels/groups you need to add -100 prefix)

Edit : in some cases the ID is shown in the browsers address bar when you click a group name

https://web.telegram.org/z/#-xxxxxxxxxx

zakaria35
  • 857
  • 1
  • 7
  • 12
  • But they started to catch right-button clicks, so may be useful to open web inspector and start `Choose an element` located in upper left corner – Belegnar Oct 01 '21 at 15:20
  • This didn't work for me, HTML does not store any data attributes. – Dimitri Kopriwa Oct 23 '21 at 13:04
  • 5
    yes it seems there is some update to hide the html attributes, however you can still get the id in web-telegram , once you click the chat name the id apears on the addresse bar of the browser (chrome for me) https://web.telegram.org/z/#-xxxxxxxx – zakaria35 Oct 26 '21 at 13:57
  • 2
    THIS is the new way. I searched more than an hour for it and this is it. Thank you so much! Also: Ctrl+Shift+I or F12 if you are unable to open Inspect Element through right click. – TheLexoPlexx Oct 27 '21 at 18:45
  • Now I can see the id using web.telegram, when click in channel the id is in the browser. https://web.telegram.org/#/im?p=cXXXXXXXXXX_YYYYYYYYYYYYYYYYYYY. – malloc32 Jan 14 '22 at 07:47
  • 4
    prefixing the group from the url with the -100 did the trick for me, thanks! – Scott Fleming Feb 02 '22 at 18:31
24

You can get Chat ID in this way.

On private chat with your bot, send a random message. You will search this message later.

Get Your API-token from bot_father : XXXXXXXXX:YYYYYYY-YYYYYYYYYYYYYYYYY_YY

Then, on your browser make a request with that url :

https://api.telegram.org/botXXXXXXXXX:YYYYYYY-YYYYYYYYYYYYYYYYY_YY/getUpdates

The request returns a json response, in json text search your random message and get chat id in that object.

Yigit Yuksel
  • 1,060
  • 2
  • 18
  • 35
14

Using python and telethon it's very easy to get chat id. This solution is best for those who work with telegram API.

If you don't have telethon, run this:

pip install telethon

If you don't have a registered app with telegram, register one: enter image description here The link is this: https://my.telegram.org/

Then run the following code:

from telethon import InteractiveTelegramClient
from telethon.utils.tl_utils import get_display_name

client = InteractiveTelegramClient('session_id', 'YOUR_PHONE_NUMBER', api_id=1234YOURAPI_ID, api_hash='YOUR_API_HASH')

dialog_count = 10
dialogs, entities = client.get_dialogs(dialog_count)
for i, entity in enumerate(entities):
                    i += 1  # 1-based index
                    print('{}. {}. id: {}'.format(i, get_display_name(entity), entity.id))

You may want to send a message to your group so the group show up in top of the list.

apadana
  • 13,456
  • 15
  • 82
  • 98
11

You can retrieve the group ID the same way. It appears in the message body as message.chat.id and it's usually a negative number, where normal chats are positive.

Group IDs and Chat IDs can only be retrieved from a received message, there are no calls available to retrieve active groups etc. You have to remember the group ID when you receive the message and store it in cache or something similar.

Chris Brand
  • 1,962
  • 16
  • 9
  • Can anyone else confirm this is true? I'm close to saying yeah after reading through the documents. I'd like to be able to get the chat_id from the group link in order to fulfill my requirements. – PrimeTimeTran Feb 27 '18 at 03:54
11

My second Solution for the error {"ok":true,"result":[]}

  1. Go in your Telegram Group
  2. Add new User (Invite)
  3. Search for "getidsbot" => @getidsbot
  4. Message: /start@getidsbot
  5. Now you see the ID. looks like 1068773197, which is -1001068773197 for bots (with -100 prefix)!!!
  6. Kick the bot from the Group.
  7. Now go to the Webbrowser an send this line (Test Message):
https://api.telegram.org/botAPITOKENNUMBER:APITOKENKEYHERE/sendmessage?chat_id=-100GROUPNUMBER&text=test

Edit the API Token and the Group-ID!

Sebastian
  • 883
  • 11
  • 32
11
  • go on the group of choice
  • add @rose bot
  • type the command /id
  • type the command /identer image description here
Muhammadyk
  • 121
  • 1
  • 7
7

Group chat id should start with - (minus) is essential

This is wrong
10540154212

This is correct
-10540154212
6

create a bot, or if already created set as follows:

has access to messages

apparently, regardless of how old/new the Telegram group is:

  1. add a bot to the group

  2. remove bot from the group

  3. add bot again to the group

  4. create a script file and run getUpdates method example:

    var vApiTokenTelegram = "1234567890:???>yg5GeL5PuItAOEhvdcPPELAOCCy3jBo"; // @?????Bot API token
    var vUrlTelegram = "https://api.telegram.org/bot" + vApiTokenTelegram;

    function getUpdates() {
        var response = UrlFetchApp.fetch(vUrlTelegram + "/getUpdates");
        console.log(response.getContentText());
    }
  1. function shall log to the console the following:
[20-04-21 00:46:11:130 PDT] {"ok":true,"result":[{"update_id":81329501,
"message":{"message_id":975,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454914,"left_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"left_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}}},{"update_id":81329502,
"message":{"message_id":976,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454932,"new_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_members":[{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}]}}]}
  1. Telegram group chat_id can be extracted from above message "chat":{"id":-1001202656383,"title"
Machavity
  • 30,841
  • 27
  • 92
  • 100
Trajano Roberto
  • 179
  • 2
  • 7
5

You can get your id by sending a /start message to the bot userinfobot

Note: once u search for userinfobot in telegram u get many responses. Makesure u choose the one with @bot tag

Abhilash
  • 2,864
  • 3
  • 33
  • 67
4

I tested now 4h but it dont work 2021 with the group-chat-id. All the time the error {"ok":true,"result":[]}

But now i found a Solution:

1:) install the "Plus Messenger" (https://play.google.com/store/apps/details?id=org.telegram.plus)

2:) go in the Group => Tap now on the "Group-Name" in the Head => Double Tap now on the Headline from the Group. A Info is comming: ID123456789 is copy in the clipboard

3:) go in the Group an paste the clipboard text. It´s you Groud-ID

4:) looks like 1068773197, which is -1001068773197 for bots (with -100 prefix)!!!

btw, you see the user-id too, on your profil.

5:) Now go to the Webbrowser an send this line (Test Message):

https://api.telegram.org/botAPITOKENNUMBER:APITOKENKEYHERE/sendmessage?chat_id=-100GROUPNUMBER&text=test

Edit the API Token and the Group-ID!

Sebastian
  • 883
  • 11
  • 32
2

IMHO the best way to do this is using TeleThon, but given that the answer by apadana is outdated beyond repair, I will write the working solution here:

import os
import sys
from telethon import TelegramClient
from telethon.utils import get_display_name

import nest_asyncio
nest_asyncio.apply()

session_name = "<session_name>"
api_id = <api_id>
api_hash = "<api_hash>"
dialog_count = 10 # you may change this

if f"{session_name}.session" in os.listdir():
    os.remove(f"{session_name}.session")

client = TelegramClient(session_name, api_id, api_hash)

async def main():
    dialogs = await client.get_dialogs(dialog_count)
    for dialog in dialogs:
        print(get_display_name(dialog.entity), dialog.entity.id)

async with client:
    client.loop.run_until_complete(main())

this snippet will give you the first 10 chats in your Telegram.

Assumptions:

  • you have telethon and nest_asyncio installed
  • you have api_id and api_hash from my.telegram.org
Foad S. Farimani
  • 12,396
  • 15
  • 78
  • 193
  • This snippet does not work. I get `SyntaxError: 'async with' outside async function`. Is there a way to fix it? – Casper Feb 15 '21 at 11:37
  • I'm sorry to hear that you couldn't use my answer. this is from a long time ago. I can't promise that I can fix it immediately. – Foad S. Farimani Feb 15 '21 at 12:25
  • 1
    I may have fixed it, but it requires a session file from some other bot. I post the code here in case anyone else stumbles upon the same problem. Seems to work as long as you have the session file: https://gist.github.com/casper/444daf52c1fde5a1b839306b551f757f – Casper Feb 16 '21 at 05:20
0

I don't understand why the most obvious (and probably the simplest) answer isn't here.

As you are writing a bot, you can get the id with these three simple lines:

bot.on('message', (msg) => {
  console.log(msg)
})

Then just check the groupId from the console :D

And as you are probably trying to look the groupId to be able to send message to a group with your bot, the correct answer is probably this:

You don't use anymore the groupId. You use the group name (the one with https://t.me/careless_whisper) prefixed with @. And remember that your group has to be public. Source: Telegram API

So if your group name is careless_whisper the recipient will be @careless_whisper

Jannunen
  • 344
  • 5
  • 9
0

I'd like to note very specific case made me monkey around it.

I've got the chat_id with above steps in the format like -1001379XXXXXX. So I just supposed the real id is 1001379XXXXXX, and left it in a such format to the grafana admin page. But in fact the id got this - as the integral part. If was really needed to be copied together with numbers.

Eljah
  • 4,188
  • 4
  • 41
  • 85
0
function adminCheck( chat_id, name ) {
var bAdminCheck = false;
var contents = JSON.parse( getAdmin( chat_id ) );      
var i = 0;
while( !bAdminCheck && (i < contents.result.length ) ) {
    if( name == (contents.result[i].user.first_name + " " + contents.result[i].user.last_name) ) {
        bAdminCheck = true;  
    }
    i++;
}  
return bAdminCheck;

}

Trajano Roberto
  • 179
  • 2
  • 7
0

Indeed adding @RawDataBot Give it 10 seconds to send you the message witch include the chat ID.

Evertos
  • 11
  • 1
-2

If you are implementing your bot, keep stored a group name -> id table, and ask it with a command. Then you can also send per name.