Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I download the chat history of a group in Telegram?

I would like to download the chat history (all messages) that were posted in a public group on Telegram. How can I do this with python?

I've found this method in the API https://core.telegram.org/method/messages.getHistory which I think looks like what I'm trying to do. But how do I actually call it? It seems there's no python examples for the MTproto protocol they use.

I also looked at the Bot API, but it doesn't seem to have a method to download messages.

like image 444
siamii Avatar asked Jun 09 '17 22:06

siamii


2 Answers

You can use Telethon. Telegram API is fairly complicated and with the telethon, you can start using telegram API in a very short time without any pre-knowledge about the API.

pip install telethon

Then register your app (taken from telethon):

   

the link is: https://my.telegram.org/

Then to obtain message history of a group (assuming you have the group id):

chat_id = YOUR_CHAT_ID
api_id=YOUR_API_ID
api_hash = 'YOUR_API_HASH'

from telethon import TelegramClient
from telethon.tl.types.input_peer_chat import InputPeerChat

client = TelegramClient('session_id', api_id=api_id, api_hash=api_hash)
client.connect()
chat = InputPeerChat(chat_id)

total_count, messages, senders = client.get_message_history(
                        chat, limit=10)

for msg in reversed(messages):
    # Format the message content
    if getattr(msg, 'media', None):
        content = '<{}> {}'.format(  # The media may or may not have a caption
        msg.media.__class__.__name__,
        getattr(msg.media, 'caption', ''))
    elif hasattr(msg, 'message'):
        content = msg.message
    elif hasattr(msg, 'action'):
        content = str(msg.action)
    else:
        # Unknown message, simply print its class name
        content = msg.__class__.__name__

    text = '[{}:{}] (ID={}) {}: {} type: {}'.format(
            msg.date.hour, msg.date.minute, msg.id, "no name",
            content)
    print (text)

The example is taken and simplified from telethon example.

like image 124
apadana Avatar answered Oct 12 '22 07:10

apadana


With an update (August 2018) now Telegram Desktop application supports saving chat history very conveniently. You can store it as json or html formatted.

To use this feature, make sure you have the latest version of Telegram Desktop installed on your computer, then click Settings > Export Telegram data.

https://telegram.org/blog/export-and-more

like image 5
newsha Avatar answered Oct 12 '22 09:10

newsha