banner
Alexeisie

AlexEisie

啊? Email: alexeisie@brs.red
github

从0看Telethon做Telegram相册/文件爬虫(Telegram Album and Replies Crawler On Telethon)

1. 什么是 Telethon#

Telethon is an asyncio Python 3 MTProto library to interact with Telegram’s API as a user or through a bot account (bot API alternative).

2.Telethon 缺点#

下载死慢,官方 API 限速

3.Telethon 官方文档#

注:你可以在官方开发文档中获取到一些本文所讲述的内容,如有疑问可以先查询该文档。
https://docs.telethon.dev/en/stable/
pip 包名:telethon

4. 学习 Telethon Client#

公式化代码块

api_id = 123456789
api_hash = 'a1b2c3d4'
phone = '+11145141919'
#telegram客户端连接
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

5. 学习 Telethon Channel#

在 Telethon 中,每个 Channel 都是一个 chat entity,Channel 主要可分为 broadcast,megagroup 两类,分别对应” 频道 “和” 讨论组 “
我们可以通过client(GetDialogsRequest(offset_date=last_date,offset_id=0,offset_peer=InputPeerEmpty(),limit=chunk_size,hash=0)).chats来获取到所有 chat entity 的集合
对于每个 Chat 对象,有以下几个比较重要的成员
image

  • id 用于获取唯一标识
  • title 用于获取 Channel 名称
  • broadcast 为 True 时意味着该 chat 是一个” 频道 “
  • megagroup 为 True 时意味着该 chat 是一个” 讨论组 “
  • 以下示例代码用于过滤出所有” 频道 “并由用户选择出目标 chat
chats = []
last_date = None
chunk_size = 200
channels = []
result = client(GetDialogsRequest(
    offset_date=last_date,
    offset_id=0,
    offset_peer=InputPeerEmpty(),
    limit=chunk_size,
    hash=0
))
chats.extend(result.chats)
for chat in chats:
    try:
        if chat.broadcast == True:
            channels.append(chat)
    except:
        continue
print('Choose a group to scrape members from:')
i = 0
for c in channels:
    print(str(i) + '- ' + c.title)
    i += 1
c_index = input("Enter a Number: ")
target_channel = channels[int(c_index)]

获取到 chat 对象后,我们可以通过client.iter_messages(target_channel, ***)来获取 chat 中的消息列表,下面列出几个对本文有帮助的参数。

  • entity即指定的 chat entity
  • limit (int | None, optional)即获取的历史消息最大上限,值为 None 时获取全部内容
  • offset_id (int)即获取的消息 ID 初始偏移量,使用后仅获取消息 ID小于该 ID 的消息列表 (消息 ID 越大越新)
  • max_id (int)
  • min_id (int)
  • search (str)即搜索字符串
  • filter (MessagesFilter | type)即消息类型过滤,可用的值见https://tl.telethon.dev/types/messages_filter.html
    image
  • reverse (bool, optional) 默认的获取顺序是 ID 由大至小 (由旧到新),值为 True 时将会由小至大获取
  • reply_to (int, optional) 该值设定后,获取消息 ID 对应的消息的回复 (评论) 消息集合。该值设定时 fliter 与 search 将会失效。
    注:仅能用于获取频道及其讨论组的消息,应用于一般 chat 和私人频道是将会失效。

这里还将介绍一种已淘汰的消息获取方式,它在通过 ID 获取消息上更具优势client.get_messages(entity,***ids)当 ids 被设定时,将会直接返回 ids 对应的消息对象而非集合。

6. 学习 Telethon 中的 Message#

The Message type is very important, mostly because we are working with a library for a messaging platform, so messages are widely used: in events, when fetching history, replies, etc.
It bases ChatGetter and SenderGetter.

在 Telethon 中每条消息都是一个 Message 对象
Message中的成员非常多,这里我挑几个对本文有帮助的成员变量和函数

欸嘿,还没写完呢

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。