You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python(Telethon)区分Telegram中的相册/组图?

Telegram相册照片识别与聚合方案(基于Telethon)

核心解决思路

Telethon的消息对象自带grouped_id字段——同相册内的所有照片消息会共享同一个grouped_id值,这就是区分相册的关键标识,无需依赖messageId或photoID。

实现步骤

  1. 维护一个临时缓存(用字典实现),以grouped_id为键,存储正在聚合的相册数据。
  2. 遍历消息时,对照片消息做如下处理:
    • 若消息带有grouped_id,则将照片添加到对应缓存条目的photos列表中;缓存条目基础信息(messageId、text、date等)取相册第一条消息的值。
    • 若没有grouped_id,则按单张照片格式单独保存。
  3. 遍历完成后,将缓存中的所有相册数据转成目标JSON格式保存。

代码示例

from telethon import TelegramClient
import json
from collections import defaultdict

# 替换为自己的API信息
API_ID = 123456
API_HASH = 'your_api_hash_here'
TARGET_CHAT = 'your_channel_or_group_username'

async def process_messages():
    # 初始化相册缓存,默认值为目标JSON结构
    album_cache = defaultdict(lambda: {
        "messageId": None,
        "text": "",
        "date": "",
        "sender_id": None,
        "isMedia": True,
        "isAlbum": True,
        "photos": []
    })

    async with TelegramClient('session', API_ID, API_HASH) as client:
        # 批量获取消息(可根据需求调整limit或改为实时监听)
        async for msg in client.iter_messages(TARGET_CHAT, limit=200):
            if msg.photo:
                # 处理相册照片
                if msg.grouped_id:
                    cache_item = album_cache[msg.grouped_id]
                    # 仅初始化一次相册基础信息(取第一条消息的数据)
                    if not cache_item["messageId"]:
                        cache_item["messageId"] = msg.id
                        cache_item["text"] = msg.text or ""
                        cache_item["date"] = msg.date.isoformat()
                        cache_item["sender_id"] = msg.sender_id
                    # 添加已下载的照片文件名(此处假设已完成下载,文件名自定义)
                    cache_item["photos"].append(f"photo_{msg.id}.jpg")
                # 处理单张照片
                else:
                    single_photo = {
                        "messageId": msg.id,
                        "text": msg.text or "",
                        "date": msg.date.isoformat(),
                        "sender_id": msg.sender_id,
                        "isMedia": True,
                        "isAlbum": False,
                        "photos": [f"photo_{msg.id}.jpg"]
                    }
                    # 可直接写入文件或暂存
                    with open('single_photos.json', 'a', encoding='utf-8') as f:
                        f.write(json.dumps(single_photo, ensure_ascii=False) + '\n')

        # 将聚合后的相册数据写入文件
        with open('albums.json', 'w', encoding='utf-8') as f:
            json.dump(list(album_cache.values()), f, ensure_ascii=False, indent=2)

if __name__ == '__main__':
    import asyncio
    asyncio.run(process_messages())

注意事项

  • 若需实时监听新消息,可改用client.add_event_handler处理,此时需要给同相册消息留一定收集时间(比如设置定时器,延迟几秒后再将缓存中的相册数据写入文件)。
  • 照片文件名需根据实际下载逻辑调整,示例中仅用photo_{msg.id}.jpg作为占位。

内容的提问来源于stack exchange,提问作者Baxtiyor Bahodirov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:53:16