banner
Alexeisie

AlexEisie

啊? Email: alexeisie@brs.red
github

從0看Telethon做Telegram相冊/文件爬蟲(Telegram Album and Replies Crawler On Telethon)

1. 什麼是 Telethon#

Telethon 是一個基於 asyncio 的 Python 3 MTProto 庫,用於作為用戶或通過機器人帳戶(機器人 API 替代方案)與 Telegram 的 API 進行交互。

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#

Message 類型非常重要,主要是因為我們正在使用一個用於消息平台的庫,所以消息被廣泛使用:在事件中、在獲取歷史記錄時、回覆等等。
它基於 ChatGetter 和 SenderGetter。

在 Telethon 中每條消息都是一個 Message 對象
Message中的成員非常多,這裡我挑幾個對本文有幫助的成員變量和函數

嘿嘿,還沒寫完呢

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。