> 电报群有许多有趣的群组,一直想通过自动化的脚本抓取频道上的消息。研究下Telethon库来抓取其中的内容
## 前期准备工作
Telegram 有丰富的机器人 API 供开发者使用,与此同时也允许对个人账号进行 API 的调用。比如在一个群组中我想对一些内容做出自动回复,但是由于我不是管理员不能添加机器人做这个事情,只能用我自己的账号来完成,这就涉及到了其 Client 开发,同理甚至可以开发出一个全新的第三方客户端。开发有很多库,比如基于命令行的 tg-cli 和基于 Python 的 Telethon这里以 Telethon 为例。
### 申请API_ID与API_HASH
首先去 https://my.telegram.org 上申请个人开发者的标识:主要包括 api_id 和 api_hash。

## Telethon使用
telethon具体使用参考官方文档:https://docs.telethon.dev/en/stable/
### 安装依赖
```python
pip install Pysocks
pip install async-timeout
pip3 install telethon
```
### Telethon获取频道消息
这里核心使用client.iter_messages获取telegram频道的https://t.me/chxyy2019的消息,抓取其中文本消息保持到文件。
```python
from telethon import TelegramClient, sync
import socks
api_id = 你的api_id
api_hash = '你的apd_hash'
client = TelegramClient('spider', api_id, api_hash, proxy=(
socks.SOCKS5, 'localhost', 1080)).start()
async def main():
async for message in client.iter_messages("https://t.me/chxyy2019"):
t = 'D:/pan/' + message.date.strftime('%Y-%m-%d %H-%M-%S')+'.txt'
if message.message:
with open(t, 'w', encoding='utf8') as f:
f.write(message.message)
with client:
client.loop.run_until_complete(main())
```
https://t.me/chxyy2019是个资源分享群,抓取的其中资源存入本地磁盘。

### Telethon获取某频道实时消息
使用client.iter_messages获取的是频道所有的消息,这里增量抓取频道信息。频道中的消息其实分为很多种有文本、图片、视频、文档等。这里我们增量抓取一个频道的图片消息,并下载保存。
```python
from telethon import TelegramClient, events,types
import logging
import asyncio
import socks
logging.basicConfig(
format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARN)
api_id = 你的api_id
api_hash = '你的api_hash'
img_store_path = 'D:/pcimg/'
channel_link = "https://t.me/yidu520"
client = TelegramClient('spider', api_id, api_hash, proxy=(
socks.SOCKS5, 'localhost', 1080)).start()
img_store_path = 'D:/'
@client.on(events.NewMessage(chats=channel_link))
async def newMessageListener(event):
message = event.message
print(isinstance(message.media,types.MessageMediaPhoto))
if message.media and isinstance(message.media,types.MessageMediaPhoto):
print(message.media)
filename = img_store_path+"/"+str(message.media.photo.id)+'.jpg'
await client.download_media(message.media.photo, filename)
with client:
client.run_until_disconnected()
```
实时获取https://t.me/yidu520中的图片消息,并保持到本地磁盘。


使用Telethon抓取电报资源