We create a Telegram bot in Python + Aiogram

Lord777

Professional
Messages
2,578
Reaction score
1,515
Points
113
We create a bot for Telegram!

Introduction
Preparation:
  • We create the necessary files
  • Importing modules and components

Bot development:
  • First command, alternative database replacement and regular buttons
  • Bringing regular buttons to life
  • Statistics output (Inline buttons, callback_data)
  • Newsletter to bot users (+ sending a photo)
  • FSM

To summarize:
  • What have you learned?

We create the necessary files
Create a folder with the name of our Bot, it contains three files: main.py, keyboard.py, config.py. We open these files in any text editor (I use Sublime, because it is convenient to switch between files + design).

22bc298b7a6e45edd33d0.png


Importing modules and components
Install the library using pip in the console

# - * - coding: utf8 - * -

We connect the token of our Bot:

storage = MemoryStorage () # FOR FSM

Along the way, we go to config.py and register our key with BotFather:

botkey = '1770592647: AAHrIpW5XW6jYKmB56Kg63r_2LcCK8gOKtg' # TOKEN WITH BOTFATHER

First command, alternative database replacement and regular buttons
Before starting with the start command, you need to add buttons that will appear when you enter the command. Open keyboard.py and write such lines, importing the library at the beginning.

from aiogram import Bot, types

The returned to <br> of The of The of of of of of of The of of of of of of of The of The <br> <br> <br> <br> we of of of of of of The for for for for for for for for for for We main.py .

We are creating a bot that can collect statistics and send newsletters. So, first, you need to teach him to write down the id of the user who sent the / start command.

In order not to mess with the database (Like Sql3), I will make it an alternative via a regular txt file.

To do this, create a text editor user.txt in the folder with the bot.

4aeb339ba144783d56ba9.png


Let's start with the / start command:

@ dp.message_handler (Command ("start"), state = None)

What have we done?

Opened the file for reading. We set a condition, if there is no user with such an id in the file, then we write it down. If there is, do not touch it. And of course we send a response to the user's command.
To make the bot work without stopping after executing commands, we write at the very end of main.py

################################################ # # ##########

We launch the bot through the main.py file.

You can double-click on the file, or open cmd and write
cd the path to the folder with the bot
python main.py
If you have the same - you did everything right, you can go to the bot itself.

c660ef209096f98a660a0.png

We send the command / start.

Everything works. We look in the file user.txt. Our ID signed up. The buttons are not pressed because nothing has been added to them. If you click on the button, it will display an error in the console (the button does not lead anywhere), but the bot will work.

Bringing regular buttons to life
Let's try to animate the Info button. Simple lines to make the bot respond to the button.

@ dp.message_handler (content_types = ['text'])

Statistics output (Inline buttons, callback_data)
Fine. The button was revived, but we will not launch it yet. Let's add statistics viewing using the Inline button, callback_data, and even tighten the admin panel.

Go to keyboard.py and write the following:

stats = InlineKeyboardMarkup () # CREATE A BASE FOR THE INLINE BUTTON

Just like we did regular buttons, but styled according to the aesthetics of Inline buttons.

Now go to config.py. We write our ID for the admin panel. You can take it from our user.txt file.

botkey = '1770592647: AAHrIpW5XW6jYKmB56Kg63r_2LcCK8gOKtg' # TOKEN WITH BOTFATHER

We return to main.py and complete the code.

Reviving the statistics button.

@ dp.message_handler (content_types = ['text'])

Next, we prescribe "Catch callback" and what should be done at the same time. We make a feature so that when you click "yes", the Bot does not send a new message, but edit the old one (looks more aesthetically pleasing), displaying the number of bot users.

We need to count all the lines (ID) from the text editor user.txt and display their number.

It all looks like this:

@ dp.callback_query_handler (text_contains = 'join') # WE WRITTEN IN THE CALLBACK BUTTONS "JOIN" MEANS AND HERE WE CATCH "JOIN"

It's time to launch the bot. Click "Statistics".

We press "Yes".

The same actions, but without the admin panel.

Clicked "Information".

Newsletter to bot users (+ sending a photo)
We make a mailing list to users. I decided to make it so that a photo was also sent with the text. We drop the photo into our folder with the bot. Rename it to something beautiful (I have it lzt.png)

@ dp.message_handler (commands = ['mailing'])

We insert this code immediately after the start handler. Check what type of photo. I have it in jpg, that's why I write in the code .jpg

Briefly about the code:

The mailing command was set to / rassilka. Made the bot send text separated by a space to the command. Like this: /mailing mailing text
Again, this will only be executed if you are an admin. We read the ID from the text editor and send messages with a photo to them. asyncio.sleep (0.4) is the delay before sending a message to a new user (in order not to get a restriction from Telegram). We record how many users received the newsletter and how many users blocked the bot. When the distribution is over, display the statistics of the distribution.
We launch the bot and check.

We look at the result:

Fine.

FSM
Let's do this thing. For admins, when entering the / me command, the bot asks to send a link to the lolz profile and waits for a response. We send him our profile. He writes it to the database (But since we want to do everything in a simple way, I will again take a textbook instead of the database). Further, he asks to indicate to us the text, which also writes to our "database" (Further it will be clear which text). Let's add the CREATOR button. By clicking on it, the bot will send us a link to the lolz profile and the text that we specified via / me.

Let's get started.

We create our "database" two files in the folder with the bot: link.txt and text.txt they will store our responses.

Go to main.py I put the code for this above the start, because everything related to FMS and State is better to write at the beginning, so that it does not distract in the middle of the main code.

We register the State group. We call it meinfo.

Q1 and Q2 what is it? I cannot explain this now, but in the course of the process everything will become clear (we write as many of them as we have questions. In this case, 2 (the bot asks for a link and text) lass meinfo (StatesGroup):

Now we write when the bot will start listening to our responses.

class meinfo (StatesGroup):

We run and check. Enter the command / me:

Everything works and is saved in our "database" textbooks link.txt and text.txt. Now we create the "Developer" button. Add one more button to the main buttons in keyboard.py.

from aiogram import Bot, types

In main.py where @ dp.message_handler (content_types = ['text'])

We prescribe the following:

@ dp.message_handler (content_types = ['text'])

We launch, check. We re-register / start so that the new button appears.

Fine. Everything works. If you change the data again via / me, then when you click on "Developer" there will already be your other text and link.

What have you learned?
To summarize:
  • We've learned how to create both regular and inline buttons.
  • Collect statistics (Count users in the bot)
  • Connect admin panel
  • Understood at the very least in callback-data
  • The bot can now edit its messages
  • Defeated FSM

That's all! Good luck with your programming!
 
Top