博客已迁移至github 村长在路上
百分百可实现完成,无坑文档
官网文档 Quick-Start — Telethon 1.26.1 documentation
版本要求: python3.8
安装依赖:
pip3 install requests[socks] #python>=3.5
pip3 install --upgrade telethon # 客户端
申请api_id 与 api_hash 申请时号码记得加区号 如+86 13993339884 https://my.telegram.org/
测试Demo
session_name = 'morey_session'
api_id = 27682732
api_hash = 'b46a9959587bec8cfee1ec1faef515da'
client = TelegramClient(session_name, api_id, api_hash)
client.start()
client.loop.run_until_complete(client.send_message('me', '你好 lison')) #发送消息给自己
#打印对话列表,获取id
for dialog in client.iter_dialogs():
print(dialog.name, 'has_ID', dialog.id)
官网推荐写法
python3.8
#根据自己电话号码进行申请
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)
async def main():
#获取到自己的信息
me = await client.get_me()
print(me.stringify())
#打印出自己的用户名密码
username = me.username
print(username)
print(me.phone)
#获取所有的对话框id
async for dialog in client.iter_dialogs():
print(dialog.name, 'has ID', dialog.id)
#给自己的收臧夹发送消息
await client.send_message('me', '你好, myself!')
# 给群/组发送消息
await client.send_message(-100123456, 'Hello, 群!')
# 发送消息给好友 通过id
await client.send_message('+34600123123', 'Hello, 王二麻子')
# 通过用户名发送消息给好友
await client.send_message('username', 'Testing Telethon!')
#回复好友信息
await message.reply('在')
# 发送图片给自己
await client.send_file('我', '/home/me/Pictures/holidays.jpg')
# 打印收臧夹的历史记录
async for message in client.iter_messages('me'):
print(message.id, message.text)
#下载聊天消息中的图片
if message.photo:
path = await message.download_media()
print('File saved to', path) # 图片下载位置
with client:
client.loop.run_until_complete(main())
async 声明异步函数(协程),特点是函数在执行过程中可以被挂起,执行其他异步函数,等挂起条件消失后再回来执行
await 声明程序挂起,await后面只能跟异步函数,或__await__属性的对象
常见报错
不能算报错,只是网络有延迟,直接输入你的电话号码即可。
解决办法:
正确写法
client.loop.run_until_complete(client.send_message('me', '你好 lison'))
错误写法
client.send_message('me', '你好 lison')
长期 无法获取groupchatID 网络卡
https://api.telegram.org/bot{token}/getUpdates
脚本发送一条消息