您可以使用Telethon https://github.com/LonamiWebs/Telethon。 Telegram API 相当复杂,通过 telethon,您可以在很短的时间内开始使用 telegram API,而无需任何有关 API 的预先知识。
pip install telethon
然后注册您的应用程序(摘自 telethon):
链接是:https://my.telegram.org/ 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)
该示例取自并简化自电视马拉松的例子 https://github.com/LonamiWebs/Telethon/blob/0e38ab4/telethon_examples/interactive_telegram_client.py.