Skip to content

Instantly share code, notes, and snippets.

@sajjadintel
Forked from agentcooper/0.README.md
Created June 9, 2018 13:16
Show Gist options
  • Save sajjadintel/f59fbf1899c13c8ef4ca8157a9a488d5 to your computer and use it in GitHub Desktop.
Save sajjadintel/f59fbf1899c13c8ef4ca8157a9a488d5 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment