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

sia*_*mii 13 python telegram

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

我在API https://core.telegram.org/method/messages.getHistory中找到了这个方法,我认为这看起来就像我正在尝试的那样.但我怎么称呼呢?似乎他们使用的MTproto协议没有python示例.

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

apa*_*ana 10

你可以使用Telethon.Telegram API相当复杂,使用telethon,您可以在很短的时间内开始使用电报API,而无需了解API.

pip install telethon
Run Code Online (Sandbox Code Playgroud)

然后注册您的应用程序(取自telethon): 在此输入图像描述

链接是: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)
Run Code Online (Sandbox Code Playgroud)

telethon示例中获取并简化了示例.

  • 另请注意,`InteractiveTelegramClient` 将停止与 pip 版本一起提供,因为它只是一个示例。改用`TelegramClient`。 (2认同)

Lon*_*ami 6

目前接受的答案适用于非常旧版本的 Telethon。对于 Telethon 1.0,代码可以而且应该简化为以下内容:

# chat can be:
# * int id (-12345)
# * str username (@chat)
# * str phone number (+12 3456)
# * Peer (types.PeerChat(12345))
# * InputPeer (types.InputPeerChat(12345))
# * Chat object (types.Chat)
# * ...and many more types
chat = ...
api_id = ...
api_hash = ...

from telethon.sync import TelegramClient

client = TelegramClient('session_id', api_id, api_hash)

with client:
    # 10 is the limit on how many messages to fetch. Remove or change for more.
    for msg in client.iter_messages(chat, 10):
        print(msg.sender.first_name, ':', msg.text)
Run Code Online (Sandbox Code Playgroud)

仍然可以应用任何格式,但hasattr不再需要。if msg.media例如足以检查消息是否有媒体。

注意,如果您使用的是 Jupyter,则需要async直接使用:

from telethon import TelegramClient

client = TelegramClient('session_id', api_id, api_hash)

# Note `async with` and `async for`
async with client:
    async for msg in client.iter_messages(chat, 10):
        print(msg.sender.first_name, ':', msg.text)
Run Code Online (Sandbox Code Playgroud)

  • 那么这里的“chat”变量是什么呢?它与“chat_id”相同吗? (2认同)

new*_*sha 5

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

要使用此功能,请确保您的计算机上安装了最新版本的 Telegram Desktop,然后单击设置 > 导出 Telegram 数据。

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

  • 是的,但以编程方式自动化该过程可能很有用。想象一下,您需要保存 100 个聊天记录,您手动单击以导出每个聊天记录,或者您编写一个可以作为 cron 作业运行的漂亮脚本?我更喜欢 python 方式 tbh ;) (2认同)

Sea*_*ean 2

现在,您可以使用TDesktop导出聊天记录。

这是关于 2018 年 8 月更新的博客文章


原答案:

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

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