AhFei

AhFei

简洁的写作需要勇气

Registration and Use of Telegram Bot Written in Python

I might have made some mistakes, please let me know if I’ve gotten anything wrong!


First, I recommend a TG forwarding bot to avoid storing messages in the TG favorites and letting them gather dust.

Project address: AhFeil/extract_forward_tgbot: Store messages forwarded to it in a file and push them to a webpage for easy viewing and editing (github.com)

Its most basic usage: (For more, please check the GitHub project homepage)

  1. Forward messages to it (only supports plain text messages and messages with images), or send messages directly.
  2. It will extract the text and internal links from the messages and store them in a file, with internal links placed after the text in order.
  3. Send the command /push, and it will copy all the content from the above file to another easily accessible file, currently using Web Notepad, which can be viewed on the corresponding webpage.
  4. Access the webpage on a computer to view and efficiently process.

Registering a Bot on Telegram and Configuration#

Register a Bot#

The registration process is very simple. Send a message to "BotFather" in Telegram, which is this bot: https://t.me/BotFather:

  1. Open the chat with @BotFather.
  2. Send /start.
  3. Send /newbot.
  4. Send the Bot's name (title, nickname).
  5. Specify the Bot's username (username, ID). Note that this username must end with bot and cannot be changed.
  6. If there are no duplicates, registration is complete. The message sent will contain the Bot's token, which looks like this: 6111111110:AAxxxxxvfly2xxxx9iGxxLa_atxxcomxuNU.
  7. Keep the token safe and do not disclose it.

register-Telegram-Bot.png

Get chat_id#

First, register the bot, click start, then send any message to the newly registered bot, and then open the URL:

# Modify the token part inside, do not delete the bot part
https://api.telegram.org/bot6111111110:AAxxxxxvfly2xxxx9iGxxLa_atxxcomxuNU/getupdates

The "id" in "chat" is the chat_id of the account that sent the message. Save it.

Add Commands to the Bot#

The essence of commands is text that starts with /, so you can directly send /command to trigger it.

Use BotFather to set commands for the Bot. The process is to send /setcommands, then select the bot you want to modify, and then send the command list in the following format:

start - See what I can do
forward - Push to the webpage
emsg - Save the earliest message in storage
dmsg - Delete the latest message and return the text
shutdown - Stop running
clear - Clear stored information

Then click the M next to the Bot input box to see the set command list.

Configure the Bot's Personalized Introduction#

Send /mybots, select a bot, then click [Edit Bot]. Here you can edit the name, avatar, and introduction, as well as commands.

The About section edits the information displayed on the interface below.

customize-About-Telegram-Bot.png

Description is the interface displayed when entering the bot for the first time:

customize-Description-Telegram-Bot.png

In fact, you can also find the option to edit the introduction information in the bot's chat window, which is more convenient on both computer and mobile.


Official Telegram Bot#

Official documentation: Bots: An introduction for developers (telegram.org)
Some libraries listed by the official TG: Bot API Library Examples (telegram.org)

Telegram-Bot-flowchart.png

Some Limitations#

Incomplete, just a record.

Note: The bot must be set as a channel administrator; otherwise, it cannot send messages.

The channel must be set to public.

Messages can be sent in the channel via @name, but not to individuals; it can only be done via chat_id.

Moreover, the bot can only proactively send messages to users after they have sent a message to it or added the bot to a group. The bot cannot proactively message strangers.

Custom Keyboard & Inline Keyboard#

Custom keyboard and inline keyboard have the following differences:

  1. Inline keyboard appears above the input area, while custom keyboard appears below the keyboard input area.
  2. Pressing the inline keyboard will return a callback query to the bot, while pressing the custom keyboard will only send a text message to the bot, which is essentially the same as a text command.

View Directly with a Browser (Webhook)#

Before writing code, you can manually use the webhook to view the information received by the bot for an intuitive understanding.

The Telegram API interface is in URL format, similar to the websites we usually use.

You can copy the following URL into your browser's address bar, replacing Your Token with the actual token, and then access it:

https://api.telegram.org/botYour Token/getupdates

# For example, like this
https://api.telegram.org/bot6111111110:AAxxxxxvfly2xxxx9iGxxLa_atxxcomxuNU/getupdates

After sending a message to the bot, refresh the browser, and you will receive a message similar to the following:

{'chat': {'first_name': 'Jean',
          'id': 24601,
          'last_name': 'Valjean',
          'type': 'private',
          'username': 'MonsierMadeleine'},
 'date': 17691833,
 'from': {'first_name': 'Jean',
          'id': 24601,
          'is_bot': False,
          'last_name': 'Valjean',
          'username': 'MonsierMadeleine'},
 'message_id': 7417,
 'text': 'I am warning you Javert'}

The message is wrapped and sent in JSON format, essentially a nested dictionary, meaning a dictionary wrapped in another dictionary.


If you type the following URL in the address bar:

https://api.telegram.org/botYour Token/sendMessage?chat_id="Some Chat id"&text="Hello"

https://api.telegram.org/bot6111111110:AAxxxxxvfly2xxxx9iGxxLa_atxxcomxuNU/sendMessage?chat_id=2066666604&text="Hello"

Replace it with the actual token and chat ID, edit the text, press enter, and your Bot will send "Hello" to the specified user.

Similarly, Telegram has defined many functions, such as sendMessage, sendPhoto, etc.

Message keys include chat (user's name, ID, and chat type), date (the date the message was sent), from (sender's information), message_id (pointing to a specific message), while text is the text of the message sent by the user.

In Telegram, chat types are divided into three types: private, group, and channel.


Python-Telegram-Bot#

Choose a programming language and a library that wraps the API for easy development.

Here, Python is used, and the library used is python-telegram-bot, which facilitates quick operations of the official API. Its related websites are as follows:


It is recommended to create three files, such as extract_forward_tgbot.py and tgbotBehavior.py, the former for setting up routes and registering to start the routes, and the latter for placing specific functions (defining bot actions).

Also, config.py is used to configure token and other configuration information.

Here comes the flowchart!

image

Actual Writing#

I started with this library's wiki: Extensions Your first Bot (github.com).

You can take a look at the small example written by AhFei below, which is at least in Chinese and easier to understand. Then look at the official wiki; actually, there's no need to write more; the official documentation is the best reference.

This example only requires filling in the bot_token, and the rest can be copied and pasted to run (if on a domestic network, you also need to configure the proxy address).
It is recommended for those interested to run it once; if successful, then modify it.


First, pull the library (Python 3.7+)

pip3 install python-telegram-bot~=20.3

First, look at config.py, configure the bot_token, and the proxy address.

# config.py
import platform
from enum import Enum
import os
import sys

# Assign parameter values to variables
bot_token = "6111111110:AAxxxxxvfly2xxxx9iGxxLa_atxxcomxuNU"

# The following is not related to the bot, mainly for development convenience. If on Windows, it indicates a development environment, configure the proxy and modify some variable values; if on Linux, it is the production environment.

system = platform.system()  # Get the operating system name

if system == 'Windows':
    # In the development environment
    os.environ["http_proxy"] = "http://127.0.0.1:10809"
    os.environ["https_proxy"] = "http://127.0.0.1:10809"
elif system == 'Linux':
    # In the production environment
    pass
else:
    # Exit directly
    sys.exit('Unknown system.')

Next, look at extract_forward_tgbot.py, where three actions, start, myid, and transfer, are imported, and routes are configured, meaning:

  1. When the bot receives '/start', it executes the start function.
  2. When the bot receives '/myid', it executes the myid function.
  3. When the bot receives content other than commands, it executes the transfer function.

Temporarily extracted code from my project, the forwarding bot; later, I will change it to simple yet practical examples when I have time.

This is our main program, and it needs to be started with python3 extract_forward_tgbot.py.

# extract_forward_tgbot.py

from telegram import Update   # Get the message queue
from telegram.ext import filters, MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes

import config
# Import the functions defining bot actions from tgbotBehavior.py
from tgbotBehavior import start, transfer, myid

if __name__ == '__main__':  
    # Create an instance, placing the token here
    application = ApplicationBuilder().token(config.bot_token).build()  
  
    # Similar to routing, which function to execute when receiving /start; the left side is the command, and the right side is the function defining the action
    start_handler = CommandHandler('start', start)  
    # (~filters.COMMAND) means messages other than commands  
    transfer_handler = MessageHandler((~filters.COMMAND), transfer)  
    # 
    myid_handler = CommandHandler('myid', myid)  

    # Register start_handler for scheduling  
    application.add_handler(start_handler)  
    application.add_handler(transfer_handler)  
    application.add_handler(myid_handler)  
  
    # Start until Ctrl-C is pressed
    application.run_polling(allowed_updates=Update.ALL_TYPES)

Finally, look at tgbotBehavior.py, which defines various actions of the bot.

# tgbotBehavior.py

from telegram import Update  
from telegram.ext import ContextTypes  

import config  

# Reply with fixed content  
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):  
    # Define some behaviors
    
    # Send a message to the user who sent /start
    await context.bot.send_message(chat_id=update.effective_chat.id,  
                                   text=f"This is a forwarding bot.")  

# Return ID
async def myid(update: Update, context: ContextTypes.DEFAULT_TYPE):  
    # update.effective_chat.id is the chat id of the user communicating with the bot
    your_chat_id = update.effective_chat.id  

    await context.bot.send_message(chat_id=update.effective_chat.id, text=f'Your chat id is {your_chat_id}')  

async def transfer(update: Update, context: ContextTypes.DEFAULT_TYPE):  
    # Define some behaviors
    # Omitted
    pass

After running the main program:

  • Sending /start will receive "This is a forwarding bot."
  • Sending /myid will receive "Your chat id is 123456789."
  • Other messages will not receive any response.

The structure is quite clear; first, write the functions defining actions, then configure the routing and enable it.
With reference documentation, you can write a feature-rich bot!

Using systemd Daemon#

When actually running the bot on Linux, using the systemd daemon is a good way to run it persistently. For specific configurations, you can refer to this article: Deployment Process of Telegram Forwarding Bot.

CheatSheet#

  • User ID: update.effective_chat.id

  • Forwarding source: update.message.forward_from_chat.title and update.message.forward_from_chat.username, the former is the channel name, and the latter is the @username.

  • Source ID of the forwarded message: update.message.forward_from_message_id

  • Text message content: update.message.text

  • Image message content: update.message.caption


If you have read the section "View Directly with a Browser (Webhook)" and practiced, you will find that the above structure corresponds one-to-one with what is on the webpage, allowing you to check the webpage to find out how to obtain information.


Original link: https://blog.vfly2.com/2023/08/register-telegram-bot-and-build-a-bot-using-python/

Copyright statement: All articles on this blog are original works by AhFei, unless otherwise stated, and are licensed under CC BY-NC-SA 4.0. Please indicate the source when reprinting Chengfei's Blog (blog.vfly2.com).

Stay updated ٩(•̤̀ᵕ•̤́๑)ᵒᵏᵎᵎᵎᵎ with clear and repeatable practical skills. You are welcome to subscribe using RSS and to leave comments for corrections.

You can communicate in the Telegram group https://t.me/vfly2 regarding any issues encountered during the article steps.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.