DEV Community

loading...

Simple automated interactions with Telegram Bots using MTProto (Pyrogram)

blueset profile image Eana Hufwe Originally published at blog.1a23.com on ・2 min read

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.

What you need

  • Python 3.6 or higher
  • Telegram account

Install Pyrogram

pip3 install 'pyrogram[fast]'
Enter fullscreen mode Exit fullscreen mode

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

Telegram API key

Get your own Telegram API key from https://my.telegram.org/apps, which will be used later.

The script

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

# Put your Telegram API key here
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()
Enter fullscreen mode Exit fullscreen mode

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.

Note

Your login session data will be stored in login.session file. Keep this file as secure as your password.

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.

The post Simple automated interactions with Telegram Bots using MTProto (Pyrogram) appeared first on 1A23 Blog.

Discussion (0)

Forem Open with the Forem app