Skip to content

Instantly share code, notes, and snippets.

@agentcooper
Last active April 9, 2024 19:27
Show Gist options
  • Star 73 You must be signed in to star a gist
  • Fork 24 You must be signed in to fork a gist
  • Save agentcooper/b5c0cec210bd81c6b49a6385f9d66069 to your computer and use it in GitHub Desktop.
Save agentcooper/b5c0cec210bd81c6b49a6385f9d66069 to your computer and use it in GitHub Desktop.
Telegram chat backup/export

How to use

  1. Login to https://web.telegram.org
  2. Copy-paste contents of telegram-scripts.js into JS console
  3. Run showContacts() to get the list of contacts with ids
  4. Run saveChat(userId) where userId is the id from step 3

Process can take a while, check console for progress. Occasionall FLOOD_WAIT errors are expected. Once done, browser will download the JSON file.

Motivation

Proposed solution requires no dependencies and works with any browser/OS.

telegram-history-dump has a dependency on telegram-cli which failed to work for me.

function getContacts() {
const AppUsersManager = angular
.element(document.querySelector('html'))
.injector()
.get('AppUsersManager');
return AppUsersManager.getContacts().then(ids => ids.map(id => AppUsersManager.getUser(id)));
}
function saveContacts() {
getContacts().then(contacts => {
saveJSON(contacts, 'contacts.json');
});
}
function showContacts() {
getContacts().then(contacts => {
contacts.forEach(contact => {
console.log(`[${contact.id}] ${contact.first_name} ${contact.last_name}`);
});
});
}
function saveChat(userId) {
const LIMIT = 100000;
var AppMessagesManager = angular
.element(document.querySelector('html'))
.injector()
.get('AppMessagesManager');
AppMessagesManager.getHistory(userId, 0, LIMIT)
.then(res => res.history.map(id => AppMessagesManager.wrapForHistory(id)))
.then(json => saveJSON(json, `${userId}.json`));
}
function saveJSON(data, filename) {
const blob = new Blob([JSON.stringify(data, undefined, 4)], { type: 'text/json' });
const e = document.createEvent('MouseEvents');
const a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initMouseEvent(
'click',
true,
false,
window,
0,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null
);
a.dispatchEvent(e);
}
@bird1388
Copy link

bird1388 commented Mar 9, 2018

Hi

how can find another user without have a number?

in this script you can find (userID) only in your contact, but i want save a chat a user not in my save contact

@kn666
Copy link

kn666 commented Mar 23, 2018

Thanks! How could I export channel history?

@mokhosh
Copy link

mokhosh commented Apr 1, 2018

Thanks a ton. How do i backup my own "saved messages" with this?

@benplumley
Copy link

benplumley commented May 5, 2018

Anyone planning to use this for long chats, edit line 25 const LIMIT = 100000; to be something a bit higher. I found that 100000 per year the chat had existed was enough, though this will depend loads on the volume.

Edit: that's for a 2-person chat, multiply up again by the number of people over this.

@SassNinja
Copy link

I found this while searching a way to transfer my Telegram data from my old to my new phone.
But after having read the script I think there's no way to import the data on my new phone, is there?

The official Telegram docs are not promising either:

You will now have a text searchable PDF export of your Cloud Chat History.

Serious?!
2018 and they suggest to 'backup' by creating a PDF? That's pathetic!!
No suprise Telegram has no chance to push whatsapp away.

Anyway in the course of trying the script I added a function to export all chats with one command instead of calling saveChat over and over.
In case someone needs it just add the following to the end of the script

function saveChats() {
  const LIMIT = 100000;

  const AppUsersManager = angular
    .element(document.querySelector('html'))
    .injector()
    .get('AppUsersManager');

  const AppMessagesManager = angular
    .element(document.querySelector('html'))
    .injector()
    .get('AppMessagesManager');

  getContacts().then(contacts => {
    contacts.forEach(contact => {
      AppMessagesManager.getHistory(contact.id, 0, LIMIT)
        .then(res => res.history.map(id => AppMessagesManager.wrapForHistory(id)))
        .then(json => saveJSON(json, `${contact.first_name}_${contact.last_name}.json`));
    });
  });
}

@nh43de
Copy link

nh43de commented Jun 6, 2018

What date format are these posted in?

@Techwolf
Copy link

Not working for me. Getting:

showContacts()
undefined

@caiobegotti
Copy link

It would be nice if it could also dump media files :-(

@YuniorGlez
Copy link

If you need to export a group conversation or a bot chat you can use the showConversations() I made in my fork

@cosmicwize
Copy link

cosmicwize commented Nov 3, 2018

I found this while searching a way to transfer my Telegram data from my old to my new phone.
But after having read the script I think there's no way to import the data on my new phone, is there?

The official Telegram docs are not promising either:

You will now have a text searchable PDF export of your Cloud Chat History.

Serious?!
2018 and they suggest to 'backup' by creating a PDF? That's pathetic!!
No suprise Telegram has no chance to push whatsapp away.

Anyway in the course of trying the script I added a function to export all chats with one command instead of calling saveChat over and over.
In case someone needs it just add the following to the end of the script

function saveChats() {
  const LIMIT = 100000;

  const AppUsersManager = angular
    .element(document.querySelector('html'))
    .injector()
    .get('AppUsersManager');

  const AppMessagesManager = angular
    .element(document.querySelector('html'))
    .injector()
    .get('AppMessagesManager');

  getContacts().then(contacts => {
    contacts.forEach(contact => {
      AppMessagesManager.getHistory(contact.id, 0, LIMIT)
        .then(res => res.history.map(id => AppMessagesManager.wrapForHistory(id)))
        .then(json => saveJSON(json, `${contact.first_name}_${contact.last_name}.json`));
    });
  });
}

I just stumbled upon your reply and got blown away by your flames towards Telegram. You clearly are a WhatsApp user. If you have a new phone just login to Telegram, all the data is in the cloud. No need to run a single script. If you have a new number just follow these steps https://telegram.org/faq#q-how-do-i-change-my-phone-number

@lulzimgashi95
Copy link

To download channels history you would need to pass id like this :
saveChat(-1005555555)

@JamesHope1219
Copy link

when I run showContacts(), it response a errr: Uncaught ReferenceError: angular is not defined

@ta1bbty
Copy link

ta1bbty commented Nov 22, 2021

Same here. Perhaps the application has moved from angular to some other framework.

CC: @JamesHope1219 @agentcooper

@nickolay
Copy link

You need to select "Switch to Old Version" (i.e. https://web.telegram.org/?legacy=1 ) before using this.

@hosamn
Copy link

hosamn commented Dec 2, 2022

Now Getting "S undefined"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment