Telegram 有丰富的机器人 API 供开发者使用, 与此同时也允许对个人账号进行 API 的调用比如在一个群组中我想对一些内容做出自动回复, 但是由于我不是管理员不能添加机器人做这个事情, 只能用我自己的账号来完成, 这就涉及到了其 Client 开发, 同理甚至可以开发出一个全新的第三方客户端
客户端开发有很多库, 比如基于命令行的 tg-cli 和基于 Python 的 Telethon, 但是我看 cli 版本好多年没更新了就没有用, 这里以 Telethon 为例
首先去 https://my.telegram.org 上申请个人开发者的标识: 主要包括 api_id 和 api_hash
- from telethon import TelegramClient
- api_id = 12345
- api_hash = '0123456789abcdef0123456789abcdef'
- client = TelegramClient('session_name', api_id, api_hash, proxy=(socks.SOCKS5, 'localhost', 8889), update_workers=4)
- client.start()
第一次运行会验证账号, 按照提示输入手机号 (+861xxxxxxxxxx) 后会在客户端上收到一串验证码, 继续按照提示输入即可验证完成
实现自动回复的全部代码:
- from telethon import TelegramClient
- import socks
- from telethon.tl.types import UpdateNewChannelMessage
- api_id = 12345
- api_hash = '0123456789abcdef0123456789abcdef'
- client = TelegramClient('session_name', api_id, api_hash, proxy=(socks.SOCKS5, 'localhost', 8889), update_workers=4)
- client.start()
- def replier(update):
- if isinstance(update, UpdateNewChannelMessage) and update.message.reply_to_msg_id is None:
- client.send_message(update.message.to_id, 'Test', reply_to=update.message.id)
- client.add_update_handler(replier)
- input('Press enter to stop this!')
- client.disconnect()
来源: https://juejin.im/entry/5a9005e2f265da4e7071db00