Skip to content

Instantly share code, notes, and snippets.

@futpib
Forked from agentcooper/0.README.md
Last active May 15, 2018 16:43
Show Gist options
  • Save futpib/7ef829d5be7a7c88d2b2a396a956ed02 to your computer and use it in GitHub Desktop.
Save futpib/7ef829d5be7a7c88d2b2a396a956ed02 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}.txt`));
}
function saveJSON(data, filename) {
const blob = new Blob([
data
.map(m => `[${(new Date(m.date * 1000)).toLocaleString('ru-RU')}] <${m.from_id}> ${m.message}`)
.reverse()
.join('\n')
], { type: 'text/plain' });
const e = document.createEvent('MouseEvents');
const a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/plain', 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