Obtaining chat_id having chat link in Telegram API - api

I am using Telegram API to develop a program to join Telegram groups or channel by their links.
Methods that join group or channel (e.g. channels.joinChannel) need chat_id or channel_id, but I have only the links of the groups or channels (e.g. #channel_username or https://t.me/channel_username or https://t.me/joinChat/xxxxx)
How can I obtain chat_id or channel_id of a group or channel having its link?
P.S: I'm not the admin of these groups or channels.

I found the answer:
First we must use checkChatInvite method. It uses the chat link as input parameter and outputs the chat specifications includes chat_id.
Then we use joinChat method method. it uses the chat_id got from the previous step and joins to that group or channel.

Selected answer seems to be outdated. In recent versions there is checkChatInviteLink call, but it requires the chat url to start with https://t.me/joinchat/
If you want to resolve a link like https://t.me/chatname, you can use searchPublicChat API call.
This works for me (using https://github.com/alexander-akhmetov/python-telegram):
def resolve_channel_link(tg, link):
if link.startswith('https://t.me/'):
link = link.split('/')[-1]
else:
raise RuntimeError('cant parse link', link)
r = tg.call_method('searchPublicChat', [{'username', link}])
r.wait()
if r.error:
raise RuntimeError(r.error_info)
assert(r.update['#type'] == 'chat')
return r.update['id']

Related

How to get the chat id, bot id, message id, channel id, group id using python-telegram-bot API?

I have created a bot in telegram and I wish to control it using python.
I am using python-telegram-bot API. What is the easiest way to figure out various ids using the python: bot id, chat id, message id, group id, channel id? Is there any readymade code available for this?
I suppose you have something like that
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text, echo))
with dispatcher.add_handler you associate a specific function to run when the bot receive a message (in this case only text messages due to Filters.text)
The function will be something like that:
def echo(update, context):
...
...
chat_id = update.message.chat_id
message_id = update.message.message_id
text = update.message.text
...
...
All the informations you need are inside the Update object, received by the Dispatcher, i extracted the more usefull, but there are a lot others. Check the documentation for more details.

Invoking GET statuses/user_timeline with user_id='' seems to invoke GET statuses/home_timeline. Why?

As I was trying to harvest the user_timelines for a list of user_ids, I noticed that my own home_timeline was also being harvested. In the end I discovered that whenever my list used a null string entry for user_id, executing the code below was the same as executing
twitter_api.statuses.home_timeline. That is ok, but I do not see such behavior Twitter- documented? What am I missing in the documentation?
auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,CONSUMER_KEY, CONSUMER_SECRET)
twitter_api = twitter.Twitter(auth=auth)
twitter_api.statuses.user_timeline(user_id='')
You're correct - if you invoke the Twitter API v1.1 user_timeline method without a user_id or screen_name parameter specified (or null), it will return the user_timeline for the authenticated user making the API call. This is undocumented behaviour.
Note that home_timeline is a different method, and will return Tweets from the users you follow, not your own Tweets. I think you're describing the former (user_timeline), not home_timeline.
I'll make a note to get this added to the official API documentation.

How to look up YouTube Live Chat Ban ID to delete it

The YouTube Live Streaming API has the ability to ban and un-ban a user from chat and provides the following method specifically to perform the un-banning:
https://developers.google.com/youtube/v3/live/docs/liveChatBans/delete
The API requires you to pass the id parameter that identifies the chat ban to remove and states that the value uniquely identifies both the ban and the chat. However, there does not appear any way to look up the chat bans for a channel, other than when you get the ID back initially when the ban occurs.
So is there no way to un-ban a user via the API long after the ban has occurred and you no longer have the ban ID?
Actually, LiveChatBanId is a base64-encoded string containing
banned user channel id
owner channel id
some random bytes?
Here is some python code that will generate it for you
import base64
banned_user_id = 'banned user id'
owner_channel_id = 'channel owner id'
decoded = f"\x08\x01\x12\x18{banned_user_id}\x1a8\n\r\n\x0b7cHT2DHCA7s*'\n\x18{owner_channel_id}\x12\x0b7cHT2DHCA7s".encode('utf-8')
encoded = base64.b64encode(decoded)
print(encoded)
Fill in banned_user_id and owner_channel_id
You may need to invoke the "LiveChatBans: delete" method twice, that's how Google works

How to forward a message in Telegram API

There are 2 methods in Telegram API that forward message:
messages.forwardMessage
messages.forwardMessages
I want to use forwardMessage method to forward a message from a channel, group or user to another one. Definition of this method is:
messages.forwardMessage#33963bf9 peer:InputPeer id:int random_id:long = Updates;
As you see this method has 3 input parameters:
peer that represents the channel, group or user that we forward message to. (Destination)
id that is message_id.
random_id that has internal use.
As we know the message_id is a unique number in a chat. so a message_id in a group has refers to a message that differs with the same message_id in other group.
So the main question is that how we determine the source peer of forwarding? Because the source peer is not determined by message_id.
P.S: My question is about methods in Telegram API, not Telegram Bot API.
There seems to an issue with ForwardMessageRequest which doesn't specify the source chat. Obviously message_id is not unique and through my tests I noticed wrong messages will be forwarded by just specifying the message_id. And I noticed message_id is not unique.
But the issue doesn't exist with ForwardMessagesRequest. Following is an example how to use the ForwardMessagesRequest version.
Forwarding Example:
Here is the code I used for testing (I am using Telethon for python, but it won't matter since it's directly calling telegram API):
source_chat = InputPeerChannel(source_chat_id, source_access_hash)
total_count, messages, senders = client.get_message_history(
source_chat, limit=10)
for msg in reversed(messages):
print ("msg:", msg.id, msg)
msg = messages[0]
print ("msg id:", msg.id)
dest_chat = InputPeerChat(dest_chat_id)
result = client.invoke(ForwardMessagesRequest(from_peer=source_chat, id=[msg.id], random_id=[generate_random_long()], to_peer=dest_chat))

How to obtain Telegram chat_id for a specific user?

How to obtain user chat_id in Telegram bot API?
The documentation says:
Integer | Unique identifier for the message recipient — User or GroupChat id
The message updates you receive via getUpdates or your webhook will contain the chat ID for the specific message. It will be contained under the message.chat.id key.
This seems like the only way you are able to retrieve the chat ID. So if you want to write something where the bot initiates the conversation you will probably have to store the chat ID in relation to the user in some sort of key->value store like MemCache or Redis.
I believe their documentation suggests something similar here, https://core.telegram.org/bots#deep-linking-example. You can use deep-linking to initiate a conversation without requiring the user to type a message first.
I created a bot to get User or GroupChat id,
just send the /my_id to telegram bot #get_id_bot.
It does not only work for user chat ID, but also for group chat ID.
To get group chat ID, first you have to add the bot to the group,
then send /my_id in the group.
Here's the link to the bot.
There is a bot that echoes your chat id upon starting a conversation.
Just search for #chatid_echo_bot and tap /start. It will echo your chat id.
Another option is #getidsbot which gives you much more information. This bot also gives information about a forwarded message (from user, to user, chad ids, etc) if you forward the message to the bot.
First, post a message in a chat where your bot is included (channel, group mentioning the bot, or one-to-one chat). Then, just run:
curl https://api.telegram.org/bot<TOKEN>/getUpdates | jq
Feel free to remove the | jq part if your dont have jq installed, it's only useful for pretty printing. You should get something like this:
You can see the chat ID in the returned json object, together with the chat name and associated message.
You can just share the contact with your bot and, via /getUpdates, you get the "contact" object
Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:
#!/usr/bin/perl
use Data::Dumper;
use WWW::Telegram::BotAPI;
my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
token => $TOKEN
) or die "I can't connect";
my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";
The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.
You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:
$ sudo cpan WWW::Telegram::BotAPI
Hope this helps
chat_id is nothing but id of user (telegram user account id). You can start a chat with #get_my_chat_id_bot. It will send you back the chat_id (your user_id).
There are following commonly used ids: channel id, group id, bot id, chat id(user id).
Straight out from the documentation:
Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.
Create a bot with a suitable username, e.g. #ExampleComBot
Set up a webhook for incoming messages
Generate a random string of a sufficient length, e.g. $memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
Put the value 123 with the key $memcache_key into Memcache for 3600 seconds (one hour)
Show our user the button https://telegram.me/ExampleComBot?start=vCH1vGWJxfSeofSAs0K5PA
Configure the webhook processor to query Memcached with the parameter that is passed in incoming messages beginning with /start. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.
Now when we want to send a notification to the user 123, check if they have the field telegram_chat_id. If yes, use the sendMessage method in the Bot API to send them a message in Telegram.
Whenever user communicate with bot it send information like below:
$response = {
"update_id":640046715,
"message":{
"message_id":1665,
"from":{"id":108177xxxx,"is_bot":false,"first_name":"Suresh","last_name":"Kamrushi","language_code":"en"},
"chat":{"id":108xxxxxx,"first_name":"Suresh","last_name":"Kamrushi","type":"private"},
"date":1604381276,
"text":"1"
}
}
So you can access chat it like:
$update["message"]["chat"]["id"]
Assuming you are using PHP.
Extending #Roberto Santalla answer and if you prefer to use Telegram API together with javascript and axios library then you might want the following:
const method = 'get'
const headers: any = {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
timestamp: +new Date(),
}
const options = { headers: { ...headers } }
const urlTelegramBase =
'https://api.telegram.org/bot123456:ABCDEF'
const urlGetUpdates = `${urlTelegramBase}/getUpdates`
const username = 'user_name'
const {
data: { result: messages },
} = await axios[method](urlGetUpdates, options)
const chat_id = messages.find(
messageBlock => messageBlock.message.chat.username === username
).message.chat.id
console.info('chat_id': chat_id)