Backup Telegram public chat messages with NodeJS and TDLib

Some channels and public chats change owners or hacked. But history messages are very cool. This information is important and useful for.
So I got information about changes in one public Telegram chat and decide make backup with NodeJS.

step 1:

Build the binary (https://github.com/tdlib/td#building)

step 2:

Register app in the Telegram Apps. Copy api_id and api_hash

step 3:

Create new NodeJS project
Install tdl and tdl-tdlib-ffi packages – more

step 4:

Create index.js with packages

const path = require('path');
const {Client} = require('tdl');
const {TDLib} = require('tdl-tdlib-ffi');

Init client

const client = new Client(new TDLib(path.resolve(__dirname, `${config.TDLIB.PATH}tdlib/lib/libtdjson`)), {
  apiId: config.MAIN.API_ID, // Your api_id
  apiHash: config.MAIN.API_HASH, // Your api_hash
});

Where config.TDLIB.PATH path with libtdjson file from step 1
config.MAIN.API_ID and config.MAIN.API_HASH from step 2

Add client connect and login code

const up = async () => {
  await client.connect();

  await client.login(() => ({
    getPhoneNumber: retry => retry ?
      Promise.reject('Invalid phone number') :
      Promise.resolve(config.MAIN.PHONE_NUMBER),
    getAuthCode: retry => retry ?
      Promise.reject('Invalid auth code') :
      Promise.resolve(config.MAIN.AUTH_CODE),
    getName: () =>
      Promise.resolve({firstName: 'John', lastName: 'Doe'}),
  }));

  // Your manipulations with telegram client code here

  client.destroy();
};

(() => {
  console.info('Telegram client up');
  up();
})();

Where config.MAIN.PHONE_NUMBER your Telegram account number
config.MAIN.AUTH_CODE – code which send from Telegram to You to verify session

step 5:

Get chat list and display title. In the index.js before

client.destroy();

Add this code:

const chats = await client.invoke({
    _: 'getChats',
    offset_order: '9223372036854775807', 
    offset_chat_id: 0,
    limit: 150,
  });

  for(const chatId of chats.chat_ids) {
    const chatInfo = await client.invoke({
      _: 'getChat',
      chat_id: chatId,
    });
    console.info(`title '${chatInfo.title}' chat id '${chatId}'`);
  }
 

This display list Your chats titles and ids

step 6:

Find chat id with messages to backup

Add next code to get messages:

const name = 'chatToBAckup';
const chatId = 'xxxxxx'; // Your chat id
let chatHistory = await client.invoke({
    _: 'getChatHistory',
    chat_id: id,
    from_message_id: 0,
    limit: 50,
});
let count = chatHistory.messages.length || chatHistory.total_count || 1;
console.info(`messages ${chatHistory.total_count} = '${JSON.stringify(chatHistory.messages[count - 1])}' `);
let i = 0;
let from = (chatHistory.messages[count - 1] && chatHistory.messages[count - 1].id) ?
    chatHistory.messages[count - 1].id : null;

while (i < 2) {
    chatHistory = await client.invoke({
       _: 'getChatHistory',
       chat_id: id,
       from_message_id: from,
       limit: 50,
    });
    count = chatHistory.messages.length || chatHistory.total_count || 1;
    from = (chatHistory.messages[count - 1] && chatHistory.messages[count - 1].id) ?
    chatHistory.messages[count - 1].id : null;
    console.info(`messages ${chatHistory.total_count} = '${JSON.stringify(chatHistory.messages[count - 1])}' `);
    i++;
}

This code make 2 request with 50 limit and get last 100 messages from chat.

Now You can process messages .Or copy to JSON(Database).

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.