Skip to content

Instantly share code, notes, and snippets.

@hosamn
Forked from YuniorGlez/0.README.md
Last active December 3, 2022 02:04
Show Gist options
  • Save hosamn/9f32bf6c68637960bbf52026cca837ef to your computer and use it in GitHub Desktop.
Save hosamn/9f32bf6c68637960bbf52026cca837ef 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() or showDialogs() to get the list of contacts with ids or the 20 last conversations in the same order of the client view
  4. Run saveChat(userId) where userId is the id from step 3 (inside the [] )

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 getConversations() {
const AppMessagesManager = angular
.element(document.querySelector('html'))
.injector()
.get('AppMessagesManager');
return AppMessagesManager.getConversations();
}
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 showConversations() {
getConversations().then(({dialogs}) => {
dialogs.forEach(conversation => {
console.log(`[${conversation.peerID}] type : ${conversation.peer._}`);
});
});
}
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