Skip to content

Instantly share code, notes, and snippets.

@bozzmob
Forked from agentcooper/0.README.md
Created April 18, 2018 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bozzmob/e19011e36db7f6771eb3b87ed1103f9e to your computer and use it in GitHub Desktop.
Save bozzmob/e19011e36db7f6771eb3b87ed1103f9e 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);
}
@destinius
Copy link

The code works wonderfully however I wanted to ask you a few questions, how could I use this for a Public channel where its id is @channel? because executing the saveChat with the user doesn't work for me. And neither does the showContacts () show me the id of the public channel

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