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

新手上路,请多包涵

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

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

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

原文由 siamii 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.8k
1 个回答

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

 pip install telethon

然后注册您的应用程序(取自 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)

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

原文由 apadana 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题