如何在Telegram中下载群的聊天记录?

2024-05-15 02:04:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想下载在Telegram上发布在公共组中的聊天记录(所有消息)。我怎么能用python做到这一点?

我在API https://core.telegram.org/method/messages.getHistory中找到了这个方法,我认为它看起来像我要做的事情。但我该怎么称呼它呢?他们使用的MTproto协议似乎没有python示例。

我还查看了Bot API,但它似乎没有下载消息的方法。


Tags: 方法httpsorgcoreapi消息协议示例
3条回答

对于新手来说,Telegram MTProto很难使用,所以我推荐使用Telegram cli。

您可以使用第三方tg-export脚本,但对新手来说仍然不容易。

您可以使用Telethon。Telegram API相当复杂,使用telethon,您可以在很短的时间内开始使用Telegram API,而无需预先了解该API。

pip install telethon

然后注册你的应用程序(摘自telethon): enter image description here

链接是:https://my.telegram.org/

然后要获取组的消息历史记录(假设您具有组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)

这个例子是从telethon example中提取和简化的。

通过更新(2018年8月),现在Telegram桌面应用程序支持非常方便地保存聊天记录。 您可以将其存储为json或html格式。

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

相关问题 更多 >

    热门问题