我想下载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)
然后获取组的消息历史记录(假设您具有组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示例中获取并简化了示例.
目前接受的答案适用于非常旧版本的 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)
通过更新(2018 年 8 月),Telegram 桌面应用程序现在支持非常方便地保存聊天记录。您可以将其存储为 json 或 html 格式。
要使用此功能,请确保您的计算机上安装了最新版本的 Telegram Desktop,然后单击设置 > 导出 Telegram 数据。
https://telegram.org/blog/export-and-more
| 归档时间: |
|
| 查看次数: |
10582 次 |
| 最近记录: |