telegram CopyRightZGQInc 极客 教程 Python Telegram API

极客:Telegram 官方服务端归档贴纸 API 分页 Bug 逆向分析与全量导出

calendar_month 2025年08月09日 00:01:24 person ZGQ Inc. schedule 约 15 分钟阅读

这绝对是我这辈子遇到过的最令人破防的官方服务端级别弱智 Bug。

起因是我打算用 Python 写一个脚本,导出我 TG 账号里所有已归档的贴纸包。 (科普:TG 客户端最多只能同时激活 200 个贴纸包,超过限制后,最老的贴纸包会被系统自动塞进隐形的归档库里。) 我玩 TG 这么多年了,打开底层数据一看:好家伙,我已经攒了 3000 多个已归档的贴纸包! 于是我就想着全部爬出来做个索引。

然后我就被 Telegram 官方极其恶心的 messages.getArchivedStickers() 接口给生生硬控了整整几个月! 在尝试了各种循环、延迟、休息等复杂的爬虫规避逻辑后,我依然无法获取完整列表。直到我把底层抓包数据拆开,我才敢 100% 确信:这根本不是什么第三方库的客户端方法定义写错了,这 TM 就是 Telegram 俄罗斯官方服务端写出的极其弱智的底层翻页 Bug!


🕵️‍♂️ 深度逆向技术报告:

👉 🔗 官方 API 文档说明

依据官方这极其简陋的文档,该接口接受两个参数:偏移量 offset_id 和获取限制数量 limit。旨在实现一个极其标准的列表分页浏览机制。 其理论上的标准工作流程应该是:

  1. 客户端发送 offset_id=0,服务器正常返回第 1 页的贴纸包列表。
  2. 客户端提取第 1 页列表里最后一个贴纸包的 ID,并将其作为下一次请求的 offset_id,去请求第 2 页。
  3. 如此循环往复,直到服务器返回一个空列表,宣告抓取结束。

但是实际情况却是: Telegram 的后端服务器,仅仅只正确响应了 offset_id=0 的首次请求,以及第二页的请求! 对于所有后续的、哪怕你携带了极其合法的 offset_id 的第三页、第四页请求,官方服务器统统彻底无视了这个参数,直接极其弱智地再次给你返回第 1 页的重复数据! 这种极其恶劣的循环死锁行为,导致任何超过 2 页数据量 (大于100个) 的归档贴纸包,在这个宇宙中都永远无法通过此官方 API 访问到!

以 Telethon 为例,使用 GetArchivedStickersRequest() 方法,脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import json
import asyncio
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetArchivedStickersRequest

API_ID = '数据删除'
API_HASH = '数据删除'
SESSION_NAME = 'account'
JSON = 'sticker.json'

async def main():
    async with TelegramClient(SESSION_NAME, API_ID, API_HASH) as client:
        try:
            initial_request = await client(GetArchivedStickersRequest(offset_id=0, limit=1, masks=False))
            total_count = initial_request.count
        except:
            return

        seen_ids = set()
        all_archived_sets = []
        offset_id = 0
        is_stuck = False

        while len(seen_ids) < total_count:
            count_before = len(seen_ids)
            print(f"DEBUG: offset_id = {offset_id}")
            try:
                result = await client(GetArchivedStickersRequest(offset_id=offset_id, limit=100, masks=False))
            except:
                break
            if not result.sets:
                break

            new_items = 0
            for s in result.sets:
                if s.set.id not in seen_ids:
                    seen_ids.add(s.set.id)
                    all_archived_sets.append(s.set)
                    new_items += 1

            print(f"新增 {new_items} 个")

            if new_items == 0 and len(result.sets) > 0:
                print("API开始返回重复数据 终止")
                is_stuck = True
                break

            offset_id = result.sets[-1].set.id

        print(f"最终获取 {len(all_archived_sets)} / {total_count} 个贴纸包")
        with open(JSON, 'w', encoding='utf-8') as f:
            json.dump(
                [{'id': s.id, 'access_hash': s.access_hash, 'title': s.title, 'short_name': s.short_name}
                 for s in all_archived_sets],
                f, indent=4, ensure_ascii=False
            )

if __name__ == '__main__':
    asyncio.run(main())

终端真实输出记录:

DEBUG: offset_id = 0 新增 40 个 DEBUG: offset_id = 591378... 新增 37 个 DEBUG: offset_id = 747964... 新增 0 个 API开始返回重复数据 终止 最终获取 77 / 3410 个贴纸包

使用基于 TDLib 实现的 Telegram X 查阅已归档贴纸包页面,依然返回77个贴纸包。不仅如此,Unigram 以及官方客户端都只能获取少于 80 个的数据。

基于以上证据,我们可以得出结论: 这不是 messages.getArchivedStickers() 方法定义的问题。因为该方法在前两页的请求中工作得非常完美,证明其参数设计是正确的。TDLib 和 Telethon 都在以正确的方式使用这个方法。 这是服务器端实现的 Bug。问题的根源在于,当处理拥有超过 100 个数据的账户时,服务器的后端逻辑在处理到第三页的分页请求时出现了错误。它没能正确解析 offset_id 参数来定位到数据列表的相应位置,而是错误地重置或返回了初始位置的数据。

打个极其通俗的比方: 这就好比你极其兴奋地在看一本小说,看完前两页,翻过去第三页,结果印的又是第一页的内容。

那很搞笑了,我倒要看看这帮官方大爷什么时候能把这种弱智 Bug 给修了。


后续进展与修复验证(Update)

info Note

官方修复确认:该问题在反馈至官方后,Telegram 服务端团队已在后续版本更新中修复了该分页逻辑缺陷,相关 Issue 已正式 Close。

结论:Telegram 官方已修复此 Bug!

Telegram 官方此前在 bugs.telegram.org 确认并修复了该服务器端分页问题(对应 Issue:“Sticker archive doesn’t display all archived sets”,随着服务端修补及客户端 10.12+ 版本发布已全量生效)。

经实时测试验证,messages.getArchivedStickers 携带 offset_id 的翻页请求已经能够完全正常遍历所有历史数据,不再出现“第三页重新回滚到第一页”或只返回 ~77 个包的死循环。


导出结果统计

已使用 account.session 会话完成了全量贴纸包与自定义 Emoji 包的抓取与导出(共发起了 120 余次分页请求,均无死循环):

类别 数量 说明
已安装普通贴纸包 198 个 当前处于活跃/已添加状态的贴纸包
已安装自定义 Emoji 包 200 个 当前安装的自定义 Emoji 包
已安装面具包 (Masks) 6 个 脸部挂件/面具贴纸包
自建贴纸包 (Created by Me) 39 个 通过 @Stickers 创建的原创贴纸/Emoji 包
已归档普通贴纸包 3,550 个 历史自动归档的普通贴纸包(顺利翻页至第 95 页)
已归档自定义 Emoji 包 571 个 历史自动归档的 Emoji 包(顺利翻页至第 31 页)
已归档面具包 0 个 无已归档面具
去重后总计 4,529 个 涵盖账号下所有的贴纸与 Emoji 资产

全量贴纸与 Emoji 导出脚本

配套的完整导出与归档脚本(基于 Python 与 Telethon),支持自动处理 FloodWait 限流、分页遍历、自定义 Emoji 与面具包分类提取以及 Markdown 报告生成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
"""
Telegram All Stickers and Emojis Exporter
=========================================
Exports all installed, archived, and created sticker packs and custom emoji packs
associated with the Telegram account.
"""

import os
import sys
import json
import asyncio
from datetime import datetime

# Windows console encoding fix
if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding='utf-8', errors='replace')
        sys.stderr.reconfigure(encoding='utf-8', errors='replace')
    except Exception:
        pass

from telethon import TelegramClient
from telethon.errors import FloodWaitError
from telethon.tl.functions.messages import (
    GetAllStickersRequest,
    GetEmojiStickersRequest,
    GetMaskStickersRequest,
    GetMyStickersRequest,
    GetArchivedStickersRequest,
)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, BASE_DIR)
from config import API_ID, API_HASH

SESSION_PATH = os.path.join(BASE_DIR, 'account')
OUTPUT_DIR = os.path.join(BASE_DIR, 'output', 'stickers_export')
STICKER_JSON_COMPAT = os.path.join(BASE_DIR, 'sticker.json')

def parse_set(s, category, is_archived=False):
    s_obj = getattr(s, 'set', s)
    short_name = getattr(s_obj, 'short_name', '') or ''
    is_emoji = bool(getattr(s_obj, 'emojis', False))
    
    url = None
    if short_name:
        url = f"https://t.me/{'addemoji' if is_emoji else 'addstickers'}/{short_name}"
        
    installed_date = getattr(s_obj, 'installed_date', None)
    installed_date_str = installed_date.isoformat() if isinstance(installed_date, datetime) else None

    return {
        'id': s_obj.id,
        'access_hash': s_obj.access_hash,
        'title': s_obj.title,
        'short_name': short_name,
        'count': getattr(s_obj, 'count', 0),
        'url': url,
        'category': category,
        'archived': is_archived or bool(getattr(s_obj, 'archived', False)),
        'emojis': is_emoji,
        'masks': bool(getattr(s_obj, 'masks', False)),
        'official': bool(getattr(s_obj, 'official', False)),
        'creator': bool(getattr(s_obj, 'creator', False)),
        'installed_date': installed_date_str,
    }

async def fetch_paginated_archived(client, label, masks=False, emojis=False):
    print(f"\n[*] 正在获取已归档【{label}】...")
    all_sets = []
    seen_ids = set()
    offset_id = 0
    page = 1
    
    while True:
        try:
            res = await client(GetArchivedStickersRequest(
                offset_id=offset_id,
                limit=100,
                masks=masks,
                emojis=emojis
            ))
        except FloodWaitError as e:
            print(f"[!] 触发 Telegram FloodWait,等待 {e.seconds} 秒...")
            await asyncio.sleep(e.seconds + 1)
            continue
        except Exception as e:
            print(f"[!] 获取出错: {e}")
            break

        total_count = getattr(res, 'count', 0)
        items = getattr(res, 'sets', [])
        if not items:
            print(f"[-] 第 {page} 页为空,结束获取。")
            break

        new_count = 0
        for item in items:
            s_dict = parse_set(item, category=f'archived_{"emoji" if emojis else "mask" if masks else "sticker"}', is_archived=True)
            if s_dict['id'] not in seen_ids:
                seen_ids.add(s_dict['id'])
                all_sets.append(s_dict)
                new_count += 1

        print(f"    第 {page} 页 (offset_id={offset_id}): 返回 {len(items)} 个,新增 {new_count} 个,累计 {len(all_sets)} / {total_count}")

        if new_count == 0:
            print(f"[-] 本页未发现新项目(可能已触及末尾或重复),终止翻页。")
            break

        last_id = items[-1].set.id
        if last_id == offset_id:
            print("[-] offset_id 未更新,终止避免死循环。")
            break
            
        offset_id = last_id
        page += 1
        await asyncio.sleep(0.35)

    print(f"[+] 【{label}】获取完毕,共获取 {len(all_sets)} 个。")
    return all_sets

async def fetch_my_stickers(client):
    print("\n[*] 正在获取用户自建贴纸包 (My Stickers)...")
    all_sets = []
    seen_ids = set()
    offset_id = 0
    page = 1
    while True:
        try:
            res = await client(GetMyStickersRequest(offset_id=offset_id, limit=100))
        except Exception as e:
            print(f"[!] 获取自建贴纸包出错: {e}")
            break
        items = getattr(res, 'sets', [])
        if not items:
            break
        new_count = 0
        for item in items:
            s_dict = parse_set(item, category='my_created', is_archived=False)
            if s_dict['id'] not in seen_ids:
                seen_ids.add(s_dict['id'])
                all_sets.append(s_dict)
                new_count += 1
        if new_count == 0:
            break
        offset_id = items[-1].set.id
        page += 1
        await asyncio.sleep(0.2)
    print(f"[+] 自建贴纸包获取完毕,共 {len(all_sets)} 个。")
    return all_sets

async def main():
    print("=" * 60)
    print(" Telegram 贴纸包与 Emoji 包全量导出工具")
    print("=" * 60)
    
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    
    client = TelegramClient(SESSION_PATH, API_ID, API_HASH)
    await client.connect()
    
    if not await client.is_user_authorized():
        print("[!] 错误:账号未授权,请检查 session 文件。")
        await client.disconnect()
        return

    me = await client.get_me()
    print(f"[+] 成功登录账号: {me.first_name} (@{me.username or '无'}, ID: {me.id})")

    # 1. 已安装普通贴纸包
    print("\n[*] 正在获取当前安装的普通贴纸包...")
    r_installed_stickers = await client(GetAllStickersRequest(hash=0))
    installed_stickers = [
        parse_set(s, category='installed_stickers', is_archived=False)
        for s in getattr(r_installed_stickers, 'sets', [])
    ]
    print(f"[+] 当前安装普通贴纸包: {len(installed_stickers)} 个")

    # 2. 已安装自定义Emoji包
    print("\n[*] 正在获取当前安装的自定义Emoji包...")
    r_installed_emojis = await client(GetEmojiStickersRequest(hash=0))
    installed_emojis = [
        parse_set(s, category='installed_emojis', is_archived=False)
        for s in getattr(r_installed_emojis, 'sets', [])
    ]
    print(f"[+] 当前安装自定义Emoji包: {len(installed_emojis)} 个")

    # 3. 已安装面具贴纸包
    print("\n[*] 正在获取当前安装的面具贴纸包...")
    r_installed_masks = await client(GetMaskStickersRequest(hash=0))
    installed_masks = [
        parse_set(s, category='installed_masks', is_archived=False)
        for s in getattr(r_installed_masks, 'sets', [])
    ]
    print(f"[+] 当前安装面具贴纸包: {len(installed_masks)} 个")

    # 4. 用户自建贴纸包
    my_created = await fetch_my_stickers(client)

    # 5. 已归档普通贴纸包
    archived_stickers = await fetch_paginated_archived(client, "普通贴纸包", masks=False, emojis=False)

    # 6. 已归档自定义Emoji包
    archived_emojis = await fetch_paginated_archived(client, "自定义Emoji包", masks=False, emojis=True)

    # 7. 已归档面具贴纸包
    archived_masks = await fetch_paginated_archived(client, "面具贴纸包", masks=True, emojis=False)

    await client.disconnect()

    # 汇总与统计
    print("\n" + "=" * 60)
    print(" 导出汇总统计")
    print("=" * 60)
    print(f"  当前已安装贴纸包: {len(installed_stickers):>5} 个")
    print(f"  当前已安装Emoji包:  {len(installed_emojis):>5} 个")
    print(f"  当前已安装面具包: {len(installed_masks):>5} 个")
    print(f"  用户自建贴纸包:   {len(my_created):>5} 个")
    print(f"  已归档普通贴纸包: {len(archived_stickers):>5} 个")
    print(f"  已归档Emoji包:    {len(archived_emojis):>5} 个")
    print(f"  已归档面具包:     {len(archived_masks):>5} 个")

    # 全局去重与分类合并
    all_items_dict = {}
    
    def merge_items(item_list):
        for item in item_list:
            key = item['id']
            if key not in all_items_dict:
                all_items_dict[key] = item
            else:
                # 保留更多属性(如creator或最新状态)
                if item.get('creator'):
                    all_items_dict[key]['creator'] = True

    merge_items(installed_stickers)
    merge_items(installed_emojis)
    merge_items(installed_masks)
    merge_items(my_created)
    merge_items(archived_stickers)
    merge_items(archived_emojis)
    merge_items(archived_masks)

    total_unique = len(all_items_dict)
    print(f"  -----------------------------")
    print(f"  全部去重后总数:   {total_unique:>5} 个")

    # 写入分类文件
    def save_json(path, data):
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    save_json(os.path.join(OUTPUT_DIR, 'installed_stickers.json'), installed_stickers)
    save_json(os.path.join(OUTPUT_DIR, 'installed_emojis.json'), installed_emojis)
    save_json(os.path.join(OUTPUT_DIR, 'installed_masks.json'), installed_masks)
    save_json(os.path.join(OUTPUT_DIR, 'my_created_stickers.json'), my_created)
    save_json(os.path.join(OUTPUT_DIR, 'archived_stickers.json'), archived_stickers)
    save_json(os.path.join(OUTPUT_DIR, 'archived_emojis.json'), archived_emojis)
    save_json(os.path.join(OUTPUT_DIR, 'archived_masks.json'), archived_masks)

    # 写入全量 JSON
    full_export = {
        'account_id': me.id,
        'account_name': me.first_name,
        'export_time': datetime.now().isoformat(),
        'counts': {
            'total_unique': total_unique,
            'installed_stickers': len(installed_stickers),
            'installed_emojis': len(installed_emojis),
            'installed_masks': len(installed_masks),
            'my_created': len(my_created),
            'archived_stickers': len(archived_stickers),
            'archived_emojis': len(archived_emojis),
            'archived_masks': len(archived_masks),
        },
        'items': list(all_items_dict.values())
    }
    all_json_path = os.path.join(OUTPUT_DIR, 'all_stickers_and_emojis.json')
    save_json(all_json_path, full_export)

    # 保持与之前脚本兼容的 sticker.json
    save_json(STICKER_JSON_COMPAT, list(all_items_dict.values()))
    print(f"\n[+] 已写入兼容文件: {STICKER_JSON_COMPAT}")
    print(f"[+] 已写入完整数据: {all_json_path}")

    # 导出纯文本链接列表(方便批量导入或分享)
    sticker_urls = [
        item['url'] for item in all_items_dict.values()
        if item['url'] and not item['emojis']
    ]
    emoji_urls = [
        item['url'] for item in all_items_dict.values()
        if item['url'] and item['emojis']
    ]

    with open(os.path.join(OUTPUT_DIR, 'all_sticker_links.txt'), 'w', encoding='utf-8') as f:
        f.write('\n'.join(sticker_urls))

    with open(os.path.join(OUTPUT_DIR, 'all_emoji_links.txt'), 'w', encoding='utf-8') as f:
        f.write('\n'.join(emoji_urls))

    print(f"[+] 已导出普通贴纸链接列表: {len(sticker_urls)} 条 (all_sticker_links.txt)")
    print(f"[+] 已导出Emoji链接列表:    {len(emoji_urls)} 条 (all_emoji_links.txt)")

    # 生成 Markdown 概览报告
    summary_md = f"""# Telegram 贴纸包与 Emoji 包导出报告

- **导出时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
- **Telegram 账号**: {me.first_name} (`{me.id}`)
- **去重后总包数**: {total_unique}

## 分类统计

| 类别 | 数量 | 导出文件 |
| :--- | :--- | :--- |
| **已安装普通贴纸包** | {len(installed_stickers)} | `installed_stickers.json` |
| **已安装自定义 Emoji 包** | {len(installed_emojis)} | `installed_emojis.json` |
| **已安装面具贴纸包** | {len(installed_masks)} | `installed_masks.json` |
| **自建贴纸包 (Created by Me)** | {len(my_created)} | `my_created_stickers.json` |
| **已归档普通贴纸包** | {len(archived_stickers)} | `archived_stickers.json` |
| **已归档自定义 Emoji 包** | {len(archived_emojis)} | `archived_emojis.json` |
| **已归档面具贴纸包** | {len(archived_masks)} | `archived_masks.json` |
| **总计 (去重)** | **{total_unique}** | `all_stickers_and_emojis.json` |

## 文件导出清单

1. **`all_stickers_and_emojis.json`**: 包含所有贴纸与Emoji包的完整元数据(ID、access_hash、标题、短名称、贴纸数量、添加链接、安装时间等)。
2. **`all_sticker_links.txt`**: 所有普通贴纸包的 `https://t.me/addstickers/...` 链接列表,共 {len(sticker_urls)} 条。
3. **`all_emoji_links.txt`**: 所有自定义 Emoji 包的 `https://t.me/addemoji/...` 链接列表,共 {len(emoji_urls)} 条。
4. **`sticker.json`**: 根目录下与之前脚本格式完全兼容的导出文件。
"""
    with open(os.path.join(OUTPUT_DIR, 'README.md'), 'w', encoding='utf-8') as f:
        f.write(summary_md)

    print(f"[+] 已生成说明与报告: {os.path.join(OUTPUT_DIR, 'README.md')}")
    print("\n[✔] 全部导出完成!")

if __name__ == '__main__':
    asyncio.run(main())
bolt 分享到 Telegram
除特别声明外,本博客所有文章均采用 CC BY-NC-SA 4.0 国际许可协议 open_in_new 许可。转载请注明出处,禁止商业使用,相同方式共享。
arrow_back 日常:为情怀补票,闲鱼 900 块收了两台远古机皇 Note FE 与 S7 Edge 极客:破解三星 Quick Share 电脑版限制,伪造主板 BIOS 厂商信息强行安装 arrow_forward

© 2026 ZGQ Inc. · Built with Jekyll · Hosted on Cloudflare Pages · ToS · Privacy & Disclaimer