Simple automated interactions with Telegram Bots using MTProto (Pyrogram)

Telegram is a popular IM platform that is famous for its openness. A lot of applications are being discovered with their public Bot API and User API. Exposed as an HTTP interface, the Bot API is more popular on Telegram, but to interact with a bot, we still need to expose its User API, which is using an original protocol named MTProto. Below is my simple code snipped that sends a message to a bot and mark its first reply as read, using Pyrogram — a Python wrapping of MTProto.

As such use is especially commonly seen among Chinese Telegram users, this post would also include some descriptions in zh-cn.

使用 Python 的 MTProto 实现(Pyrogram)实现与 Telegram Bot 的自动化交互(如签到等)

本文介绍了一个使用 Python 实现与 Telegram Bot 进行自动化交互的脚本。其功能包括向 Bot 发送特定内容的文本信息,并将其首条回复标记为已读。

What you need
依赖

  • Python 3.6 or higher
    Python 3.6 或以上
  • Telegram account
    Telegram 账号

Install Pyrogram
安装 Pyrogram

pip3 install 'pyrogram[fast]'

[fast] here means to use the C-based cryptography module for better performance.

Telegram API key
Telegram API 密钥

Get your own Telegram API key from https://my.telegram.org/apps, which will be used later.
从上述链接处获取你的 Telegram API 密钥。

The script
脚本

from pyrogram import Client, Filters, MessageHandler, Message
from threading import Event

# Put your Telegram API key here
# 在这里改为你的 Telegram API 密钥
api_id = 12345
api_hash = "12345678901234567890abcdefabcdef"

# User to send message to
# 收信用户的用户名
user = "botfather"
# Message content
# 信息内容
command = "/help"

feedback_evt = Event()


def mark_as_read(client: Client, message: Message):
    client.read_history(message.chat.id, message.message_id)
    feedback_evt.set()


with Client("login", api_id, api_hash) as app:
    app.send_message(user, command)
    app.add_handler(MessageHandler(mark_as_read, Filters.chat(user)))
    feedback_evt.wait()

Change the highlighted lines accordingly.
将上述代码高亮部分进行适当的更改。

First time use
第一次使用

Run the script with Python, and you should be prompted to log in with your phone number and login code. This is only needed on the first run.
使用 Python 运行此脚本,你会看到登陆的相关指示。按照提示输入你的手机号码和验证码。登陆只需在第一次运行时进行。

Note 注

Your login session data will be stored in login.session file. Keep this file as secure as your password.
你的登陆会话信息将会被储存在 login.session 文件内,请妥善保管此文件,不要泄露给他人。

Now this script is ready to run. You can run this with anything you want, bash script, cronjob, or whatever that can call a command.
至此脚本已准备就绪。


Comments

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注