HOWTO backup your Telegram chats (if you don’t fear the terminal)
Update: Telegram Desktop version 1.3.8 added an option to export all your data as either a set of HTML files or a JSON file. This was added to comply to the European GDPR directive. I’ve tried this out and it works as promised and is now definitely the easiest option to export your data. Thanks European Union!
This article is kept for archiving purposes but the methods outlined probably shouldn’t be used anymore.
Note: i’ve updated this article in april 2016 with a new method that’s still clunky, but works a little bit better.
Considering that WhatsApp was sold in February 2014 to Facebook for a petty $19 billion dollars you might have looked around for alternatives. Currently the most promising messaging client is Telegram, an alternative mostly financed by Pavel Durov, who ironically founded Facebook’s biggest competitor in Russia: VK.
Now some people might suggest switching from WhatsApp to Telegram is simply trading one evil (Facebook) for another (VK). However, Durov has nothing to do with VK anymore and the people behind Telegram say they respect your privacy. Telegram is mostly open source as well. Time will tell if Telegram can stay true to their promises.
Anyway, one missing feature (the only one, in my opinion) is the ‘export chat’ option that is available on WhatsApp. I’m not that interested in transferring messages between devices, but i do think it’s important to have an export of your digital history, whether it’s e-mail, instant messaging or your tweets.
There are multiple feature requests for the various (semi) official apps, but currently there doesn’t seem to be a simple solution.
Anyway, i found a hack, but unfortunately it’s pretty technical and not for those afraid of the command line. Unfortunately it’s only for Linux and Mac systems as well.
Basically you’re using a combination of the command line tg command and a Ruby script called telegram-history-dump. Used in conjunction, you get a set of JSON files that you can further process, for example using a Python script that compiles it to a CSV file you can open in Excel. Here’s something i wrote for that.
Here’s what you should do:
- Open up a Terminal and follow the instructions to install tg for your operating system. On my MacBook with Yosemite i needed this ugly hack to properly install the brew dependencies. On El Capitan i ran into countless other problems including something where i actually needed to comment out some C code in a source file. Following the instructions in this issue solved it for me.
- Now run tg (
bin/telegram-cli
) and follow the steps to get an activation code. - Follow the instructions to install telegram-history-dump. The default configuration worked fine for me.
- Run the script from the command line. This will get you a map of JSONL files that contain your precious messages.
- You could try and run my python script to get CSV files for easier viewing.
Alternatively, if you don’t want to run the telegram-history-dump script for some reason you could also try these steps with just tg:
- Run the command
contact_list
to get an overview of all your contacts. - Use the command
history
to get the chat log. The first argument is the name of your friend (note that tg offers tab completion!), the second one is the number of messages. There doesn’t seem to be a setting for ‘all messages’ so simply pick a high number, e.g.:history My_Friends_Name 10000
- tg doesn’t offer a way to export the history to a text file, so you either need to copy-paste the stuff from the terminal or save the terminal output to a file (the last option works best for the OS X Terminal).
- Note that
history
also works for groups. There is nogroups_list
command, but usingdialog_list
will also show groups. - Repeat for every user and/or group you want to export.
I know, this is all pretty clunky. Hopefully the people at Telegram and/or the coders who create the clients will create a better export option in the future.
apapau
Super
giomba
Hey, under GNU/Linux (and MAC, I suppose) you can simply use the ‘script’ command, to log everything on terminal.
So, for example:
$ script my_conversations.log # starts logging in file my_conversations.log
$ telegram-cli # runs telegram-cli
> history my_friend 65536 # prints history (which is logged)
> safe_quit # stops telegram client
$ exit # stops logging
To read conversations, you can use:
$ less -R my_conversations.log
so they’re colourful and highlighted too!
azzam
i cant run tg (bin/telegram-cli) ,
the output is bash: syntax error near unexpected token `bin/telegram-cli’
please help me, cause i really want to back up my important massage/chat
Joe
Same here, totally new to this, granted! I can’t get tg installed to begin with, be that via Homebrew:
“./configure: line 1827: config.log: Permission denied
./configure: line 1837: config.log: Permission denied”
or Mac Ports:
“-bash: ./configure: No such file or directory”
or:
“-bash: export: `./configure’: not a valid identifier”
What am I doing wrong? Appreciate any productive hints and help
Alex
Great, thanks for this article. I tried this first in a VM with ubuntu-14.04.2-desktop-amd64.iso, didn’t work (always crashed and some users reported the same problems on Github). Then I moved to an AWS EC2 instance and did it from there, worked without problems this time.
Alex
loser
omg so hard.. i wish somebody could do it for me :(
Oldboy
It’s strange that there is no easier way of doing this. On my iPhone 5S, Telegram messages are stored in plain text in an SQLite database called “tgdata_index.db”. Making a jailbreak tweak or something wouldn’t be difficult I suppose.
The file can be found at: var/mobile/Containers/Data/Application/
/Documents/tgdata_index.db
Anand
Here is a tiny script that works (today) on browser firebug console.
var msgss = ”;
$.each($(‘.im_history_message_wrap’), function(i,e){
var msgwrp = $(e);
var dtsplit = $($(‘.im_message_date_split > .im_service_message’, msgwrp)).text();
var cnts = $(‘.im_content_message_wrap’,msgwrp);
$.each(cnts, function(ii,ee){
var cntwrp = $(ee);
var athr = $(‘.im_message_author’,cntwrp).text();
var dte = $(‘.im_message_date’,cntwrp).text();
var txt = $(‘.im_message_text’,cntwrp).text();
var imgg = $($(‘.im_message_photo_thumb > .im_message_photo_thumb’, cntwrp)).attr(‘src’)
msgss+=(athr + ‘[‘ + dtsplit + ‘ ‘ + dte + ‘]:’ + txt + ((imgg)? imgg : ”) + ‘\n’);
});
});
console.log(msgss);
rinaldosjr
I’ve got the following error in a Mac Yosemite:
gcc -I. -I. -I/usr/local/include -I/usr/local/Cellar/readline/6.3.8/include -I/usr/local/include -I/usr/include -I/usr/include -I/usr/include -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated-declarations -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -Wno-unused-parameter -fPIC -c -MP -MD -MF dep/main.d -MQ objs/main.o -o objs/main.o main.c
main.c:836:5: error: ‘__builtin___snprintf_chk’ will always overflow destination buffer [-Werror,-Wbuiltin-memcpy-chk-size]
snprintf (serv_addr.sun_path, 108, “%s”, unix_socket);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/secure/_stdio.h:57:3: note: expanded from macro ‘snprintf’
__builtin___snprintf_chk (str, len, 0, __darwin_obsz(str), __VA_ARGS__)
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
make: *** [objs/main.o] Error 1
Any clue? Thanks!
Farhad Malek
Hi,
Can someone help please?
Is it possible to print out a history of my telegram chat with my wife?! Unfortunately it is required for her visa, to prove that we are a proper couple!
Thanks,
Farhad Malek
maryam
Can someone perhaps make a video of this please. I’m so confused :'( Thanks
Samim Pezeshki
I created a Lua script which saves as many messages as you want into a sqlite database.
https://github.com/psamim/telegram-cli-backup
Alex
These instructions and the instructions in the links are frustratingly vague. For example:
2. Now run tg (bin/telegram-cli) and follow the steps to get an activation code.
What on earth does that mean?! Is the user to type in terminal “tg” or “bin/telegram-cli” or “telegram-cli” or “/bin/telegram-cli” or to navigate to the folder? At any rate, this file does not exist, because in step 1, the instructions are all over the place and unclear:
At one point it just says: “Install these ports:
devel/libconfig
devel/libexecinfo
lang/lua52”
Yes. HOW?? With what Terminal-command?? Sorry, this incompleteness is just lazy.
Alex
Update (regarding the installation instructions in step 1):
sudo port install devel/libconfig
sudo port install devel/libexecinfo
sudo port install lang/lua52
do not work. The ports are not in the library, even after executing sudo port selfupdate, etc.
The command ./configure is also problematic, even despite having successfully carried out the first steps of the Macports instructions.
Bart
To those having trouble, it’s really doable.
Look for the Terminal.app on your computer.
Look here: http://brew.sh/ install ‘brew’ by copy pasting the line in the Terminal. This will allow you to install stuff with brew using the Terminal.
Next install git with brew: copy paste in the Terminal ‘brew install git’.
Install tg, follow the instructions on https://github.com/vysheng/tg
1. copy paste this: git clone –recursive https://github.com/vysheng/tg.git && cd tg
2. copy paste these line by line:
brew install libconfig readline lua python libevent jansson
export CFLAGS=”-I/usr/local/include -I/usr/local/Cellar/readline/6.3.8/include”
export LDFLAGS=”-L/usr/local/lib -L/usr/local/Cellar/readline/6.3.8/lib”
./configure && make
(note these commands might change, look at the url)
When you are done, copy paste: ‘bin/telegram-cli’
Now everything should be pretty self-explanatory.
Bart
A final note, you might need to have Command Line Tools installed for brew to work. Look here: http://osxdaily.com/2014/02/12/install-command-line-tools-mac-os-x/
This and my previous comment should allow total newbs to follow this guide.
g3r4
I’ve been looking in the internet for the folder where Telegram keeps all the media without luck, I found it myself, it is at:
/Users/[YOUR USER]/Library/Containers/ru.keepcoder.Telegram/Data/Library/Caches/ru.keepcoder.Telegram/cache/
Hope this is useful to someone. (This is on Mac OS X Yosemite, Telegram version Version 1.71.23467)
hasti
Hello
If we deactivate our telegram and then we install it again..will we be able to recover all previous chats?
Tim
Thanks for the article! Unfortunately a plain text dump is pretty limited, and both the tg history command and telegram-cli-backup seem to have trouble with large backlogs now. But they did inspire my final solution, which I’ll leave here in case anyone finds it useful.
It’s Python script for tg which will export conversations of any size to newline separated JSON format:
https://github.com/tvdstaaij/telegram-json-backup
Writing a conversion script to turn the JSON into nicely formatted text would be fairly trivial.
Alex
Evernote!! (no terminal required)
Open the web-version of your telegram account e.g. in google chrome. have the evernote plugin installed and once you select the desired chat conversation that you want to be archived, click on the evernote button in your chrome menu bar and save the chat thread as “article” – and hurray! ALL your chat including images will be saved (and can then further be exported as html via the evernote export function within its own native app).
Enjoy!
vvvv
Hi, thanks for these instructions. When I run telegram-cli I get the following error:
*** No public keys found
I do have a public key in .ssh but obviously here something else is meant. Any help would be appreciated!
vvvv
found the solution here: https://github.com/vysheng/tg/issues/148
Nima
Hi folks,
as we see, most command lines posted here are related to Linux or Mac OS. Now I wanna know how to use command line Telegram client “tg” in win 10. Could someone please tell me that?
Anonymous
So…
You do not need to use Terminal.app
Use redirection:
command > file
will redirect the output of command
One can wrap this to a script with a loop to get all of messages.
Tim
New project in Ruby supporting both plain text and json output, and also media downloads: https://github.com/tvdstaaij/telegram-history-dump
@Nima
See this readme for building telegram-cli on Windows:
https://github.com/vysheng/tg/blob/master/README-Cygwin.md
salah makki
keep previous history
Matze
thanks Tim for the hint on Windows!! will try that.
best
M.
Richard steuart
It could never ring the bell to me !
Ashkan
Hi,
when I apply command to connect to Telegram DC IP address, I get this error:
*** Connect with 173.240.5.1:443 Time Out.
I wonder where in what file I can change this IP address to a new one.
Thanks.
angel
As I can get the information of a group?
Thanks
Wenyan
Thanks for the article! But I am totally new with computer, is anyone can teach me ? Thanks a lot.
Wenyan
Ivan
Hey folks, there is a Chome extension available called “Save Telegram Chat History”. It’s very simple, no command line and so forth, just works with your web-browser.
jojo
@ ivan
thanks man
you made my day !
Bernie Calucci
WHERE THE FUCK are these files on OS X how is it POSSIBLE that there’s ABSOLUTELY NO DOCUMENTATION as to where this retarded app which claimed to protect our privacy WRITES our PRIVATE conversations! WHERE is the COMPLETE file location list for EVERY platform!?!
Bernie Calucci
I don’t WANT NO STUPID SCRIPT I WANT ACCESS TO THE ACTUAL FILE TO PROTECT IT!!!! How is it possible that I’ve been hours on the internet and there is no clear documentation about this!!
Abdullah
Same here.
Dron
Updated Anand’s script to show correct time and quoted text:
var msgss = ”;
$.each($(‘.im_history_message_wrap’), function(i,e){
var msgwrp = $(e);
var dtsplit = $($(‘.im_message_date_split > .im_service_message’, msgwrp)).text();
var cnts = $(‘.im_content_message_wrap’,msgwrp);
$.each(cnts, function(ii,ee){
var cntwrp = $(ee);
var athr = $(‘.im_message_author’,cntwrp).text();
var dte = $(‘.im_message_date’,cntwrp).attr(‘data-content’);
var txt = $(‘.im_message_text’,cntwrp).text();
var imgg = $($(‘.im_message_photo_thumb > .im_message_photo_thumb’, cntwrp)).attr(‘src’)
var quoteAuthor = $($($(‘.im_message_reply_author span’, cntwrp))[1]).text();
var quoteText = $($($(‘.im_message_reply_body span’, cntwrp))[1]).text();
msgss += dtsplit ? ‘\n’ + dtsplit + ‘\n’: ”;
if (quoteAuthor) {
msgss += ‘| ‘ + quoteAuthor + ‘:\n’+
‘| ‘ + quoteText + ‘\n’;
}
msgss += (athr + ‘ [‘ + dte + ‘]’ + ‘:\n’ +
txt + ((imgg)? imgg : ”) + ‘\n\n’);
});
});
console.log(msgss);
Dron
Or
pastebin . com / Hwb57pJa
(remove spaces)
A.Turk
Hello
vocative A
فریبا عباسی
EHSANZAHIRABADI
HI
Dear Telegram
I lost My Channel
Yesterday i delet my telegram account in your site and when i connect again , i can\’t access in my channel admin .
my user name :
@Hard6063
+989188611743
My Channel is:
http://telegram.me/servaj
Tim
Is it possible to convert the cache4.db to another format, say html or excel?
Marry
LOL I guess I need to pay someone to do this for me. It is so techy and difficult :(
Zach
I might do a video tutorial for linux soon. However I have an issue with large group exports not writing to anything other than .json
User
Let me test if this works!
mansor
Hello
I want …… How do I backup all my telegram
@m_reezza_d
Im delet acount telegram.plz
bahareh mostofi
i can not sing in and download telegram
Ronz
Wish the best
Silom
Can anyone backup the messages of a deleted telegram account?if so how can I vanish messages forever that no one reach them,tnx
anon
just log in from a web browser, open convo, right click and select print, print to pdf. way easier
Somebody
This saves medias too?
Michael
Many thanks. Works like a charm.
Renier
Thanks a lot man – worked great!
mahan Irani
hi dear all
instead of these confusing commands just check the following link in google chrome extensions and then use telegram web. u can easily export chat content in ur pc. :)
mahan Irani
google chrome extension:
Check out “Save Telegram Chat History”: https://chrome.google.com/webstore/detail/save-telegram-chat-histor/kgldnbjoeinkkgpphaaljlfhfdbndfjc?utm_source=gmail
Ali
I delete my account . And my channnel is in the air. I want to backup my telegram channel.
Espedu Tamadre
> “Telegram is mostly open source as well”
LOL! Far from it! Only the client is ‘mostly’ open source, although it allegedly contains some binary blobs. The server is obviously proprietary and closed source.
vaishnavi
I need my chat log back. Awaiting your help
MK
look into https://github.com/fabianonline/telegram_backup/releases
FR
TY, working great for me on mac.
Got all chats with telegram-history-dump!
Anonymous
great job!
thank you
wcat
Very nice thank you for showing me those tools. FYI you can output to different formats now like html.
Neda
I deleted my account so i register again but i lose my all memory backup please help me i want it
Thankyou
Telegramalyzer
While this is a nice method, it appears a little easier to me to use a Chrome plugin (which actually works very well). Those video explains it pretty straightforward: https://www.youtube.com/watch?v=P3h5rvGz4-w
It\’s actually just installing the Chrome plugin, accessing web.telegram.org, receiving the chat history and saving it.
By the way (and I hope it is okay that I write this here): Yesterday we published our webapp Telegramalyzer where you can analyze your Telegram chat logs (that you retrieved via the Chrome plugin). That way you can see what your most used emojis are, your messages over time, who writes, weekdays, hour chart,…
Would be glad if someone checked it out :)
farda
Hi, how can I recover deleted telegram chats on my iPhone?
Thanks in advance.
redh
Hi. What about a service in windows that will actually collect last x messages (I need from a group to fetch last message) with a predefined frequency? Maybe this feature could transform in Telegram to SMS (for those who are in a meeting and want to not miss any important info from a group).
Susan
I have a very serious problem. Someone has hacked my telegram. I want to change the number, it says I have to delete the other account and I don’t have it. what should I do? please help. Thanks
Zahra
Thanks for your help
Emma
pretty clunky – is not the word! I wasted three hours by just solving a problem with sending messages (this helped: https://osxtips.net/text-messages-not-delivered/ ) and then I finished with it – your arcticle about backup was just in time! H*king thanks.
Ya
Thanks a lot! The GDPR feature of Telegram is INCOMPELTE! It does not allow downloading whole history of group chats!
Side note: tg-cli is very unstable, and I had to mod it to make it work. The script is also unstable and loves to crash on some occasions.
Denny
Thanks pal for this feature. Now i can backup and save telegram chats and files :)
Woody
Useful article, I found this very late and wanted to programmatically interact with my telegram chats this way. In the end I ended up just building a macro to export the chat logs which worked cleaner… We live in a more AI world every day :D
Wanted to share that I made a Telegram Chat Analyzer, in case anyone else here finds it useful:
https://coupleflow.app/telegram-chat-analyzer