夜火笔记

pyrogram 一个telegram api库 操作tg账号自动收发信息

2024-05-23
笔记 pythontelegram
2分钟
364字

最近写了个小工具,使用python操作普通的telegram号,给telegram bot发消息,获取返回内容,入库。

申请telegram的api什么的这些前置项就不赘述了

刚开始找到一个python-telegram库( https://github.com/alexander-akhmetov/python-telegram ),试了一下,感觉并不是多好使。获取最新的消息也有点问题。

后来发现了pyrogramhttps://github.com/pyrogram/pyrogramhttps://docs.pyrogram.org ),感觉挺符合我的使用习惯。

登录授权

https://docs.pyrogram.org/start/auth

1
from pyrogram import Client
2
# api_id 和 api_hash改为自己的 运行后会提示输入tg账号和授权码
3
app = Client("account", api_id=<api_id>, api_hash=<api_hash>)
4
with app:
5
    print(app.get_me()) # 获取账号信息
6
    session_string = app.export_session_string() # 获取session_string
7
    print(session_string)
8
9
# 使用session_string登录 范例
10
with Client("account", session_string=session_string) as app:
11
    print(app.get_me())
12
13
app.run()

发送消息

消息对象的账号为对方账号@后面的内容 https://docs.pyrogram.org/api/methods/send_message

1
msg_result = await app.send_message(<消息对象的账号>, <消息内容>)

接收消息

接收消息有多种方式

使用@app.on_message()装饰器进行接收 https://docs.pyrogram.org/start/examples/echo_bot

1
from pyrogram import Client, filters
2
3
app = Client("my_account")
4
5
@app.on_message(filters.text & filters.private)
6
async def echo(client, message):
7
await message.reply(message.text)
8
9
app.run() # Automatically start() and idle()

使用app.get_messages() 轮询 https://docs.pyrogram.org/api/methods/get_messages

1
# Get one message
2
await app.get_messages(chat_id, 12345)
3
4
# Get more than one message (list of messages)
5
await app.get_messages(chat_id, [12345, 12346])
6
7
# Get message by ignoring any replied-to message
8
await app.get_messages(chat_id, message_id, replies=0)
9
10
# Get message with all chained replied-to messages
11
await app.get_messages(chat_id, message_id, replies=-1)
12
13
# Get the replied-to message of a message
14
await app.get_messages(chat_id, reply_to_message_ids=message_id)

使用app.get_chat_history()查询历史消息 https://docs.pyrogram.org/start/examples/get_chat_history
https://docs.pyrogram.org/api/methods/get_chat_history

1
from pyrogram import Client
2
3
app = Client("my_account")
4
5
async def main():
6
async with app:
7
# "me" refers to your own chat (Saved Messages)
8
async for message in app.get_chat_history("me"):
9
print(message)
10
11
app.run(main())
本文标题:pyrogram 一个telegram api库 操作tg账号自动收发信息
文章作者:夜火/xloong
发布时间:2024-05-23
Copyright 2026
站点地图