Develop with Telegram API

Develop with Telegram API

Telegram has a bunch of API allows developers to create Telegram-like messaging application on their platform free of charge. Telegram has two kinds of API, which are Bot API and Telegram API, TDLib. Visit Telegram APIs to check the differences between them. In this article, we are going to talk about how to utilize Telegram API to implement our requirements. In order to ensure consistency and security across the Telegram ecosystem, all third-party client apps must comply with the Telegram API Terms of Service.

Get App ID

According to the Transparency requirement in the Telegram API Terms of Service, developers have to obtain an app id to get access to the Telegram APIs.

Visit App configuration (telegram.org) website and fill out the web form (URL field can be dismissed), then you will get your own telegram app id.

Api_id and Api_hash is the information we will most frequently use.

Install Development Kit

Telegram has a diverse range of third party development kit, such as telethon for Python, gramjs for nodejs. They are all wrappers for the telegram API. Choosing which development kit depends on the programming language you use.

I choose Javascript for development, so I installed gramjs. If you want to get fully experience in developing with Telegram API and you do not have any preference in programming language, I highly recommend you to use Telethon.

1
npm install telegram

Introduction to GramJS

GramJS is still in early stages. In the basic document of GramJS, It only has method to call APIs without any wrapper. Therefore, we will use advanced documentation for our development. Its core is based on telethon.

Authentication with development Kit

To call the telegram API for further operation, we should firstly login into Telegram with our code. GramJS recommends to use String to store our session. The function below shows how to get String session. Run this function, then you will get a session details in the console output in string format .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const loginTelegram = async () => {
console.log("Loading interactive example...");
const client = new TelegramClient(stringSession, apiId, apiHash, {
connectionRetries: 5,
proxy: {
ip: "127.0.0.1", // Proxy host (IP or hostname)
port: 1086,
MTProxy: false,
socksType: 5
}
});

await client.start({
phoneNumber: async () => await input.text("Please enter your number: "),
password: async () => await input.text("Please enter your password: "),
phoneCode: async () =>
await input.text("Please enter the code you : "),
onError: (err) => console.log(err),
});
console.log("You should now be connected.");
console.log(client.session.save()); // Save this string to avoid logging in again
await client.sendMessage("me", { message: "Hello!" });
};

Copy the session string and put it into the SessionString class in GramJS, then you can always use this SessionString to get access to the Telegram API.

1
2
3
4
5
6
7
8
9
10
const stringSession = new StringSession(session_string);
const client = new TelegramClient(stringSession, apiId, apiHash, {
connectionRetries: 5,
proxy: { //Use proxy. If you are not using a proxy to visit telegram, ignore this code.
ip: "127.0.0.1", // Proxy host (IP or hostname),
port: 1086,
MTProxy: false,
socksType: 5
}
});

Get Dialogs

In telegram, each chat box is a Dialog. To continue our tour in telegram development, we should then get a list of dialogs. In this section, we use an iterator to iterate.

1
2
3
4
5
const getDialogs = async () => {
for await(const dialog of client.iterDialogs({})){
console.log(dialog.title)
}
};

Reference: TelegramClient | IterDialogs

Get Messages from Dialogs

To make messages easier to read, I have constructed a new data structure that facilitates subsequent operations such as storing in elasticsearch and display to our users.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const formatMessage = (message) => {
return {
time: message.time,
sender: {
username: message.sender.username,
firstName: message.sender.firstName,
lastName: message.sender.lastName,
},
text: message.text
}
}

const getTelegramMessages = async () => {
let target_dialog
for await (const dialog of client.iterDialogs({})){
if(dialog.id == dialogId)
target_dialog = dialog
}
const messages = await client.getMessages(target_dialog, {limit:1000})
const result = new Array()
for(let i in messages){
if(messages[i].sender != undefined && messages[i].text != ''){
result.push(formatMessage(messages[i]))
}
}
return result
}

Reference: TelegramClient | getMessages

Conclusion

With the operations above, we can easily store our chat history in our elastic clusters.

Maybe this is the last time I post blog about GramJS as I will use telethon in the future. I give up on using GramJS because it is using telethon as its core, and telethon is more powerful and has comprehensive documentation.

Author

Brimon

Posted on

2023-07-24

Updated on

2023-07-24

Licensed under

Comments