How to create a telegram bot with Python in minutes

Creating a telegram bot with Python in minutes may seem like a clickbait title for a post, but trust me, it’s possible. If you’re going through a boring afternoon or you’re locked down due to COVID restriction and you want to do something different, keep reading and let’s create our first Python Telegram bot! 🙂
For this project, all you will have to use is the python-telegram-bot package that’s basically a wrapper around telegram APIs. Python Telegram Bot is fully compatible with Python 3.6+ and will make developing a Telegram Bot a piece of cake.
So, let’s start by installing this package (I strongly recommend to use a virtual environment for this kind of things: if you don’t know how to do it, just look at this old article or stay tuned, because I’m going to write something about it soon…
$ pip install python-telegram-bot –upgrade
Now that you have installed the package, let’s start with creating our first bot. And guess what? You don’t need any Python to create a bot, you just need to chat with the Telegram BotFather account.
Once you start chatting with the BotFather bot, you just need to issue the /newbot command and answer the questions of BotFather will ask you: the name of your bot (it’s the display name) and the username of your bot.


That’s it, your bot is ready! There is a lot of other stuff that you can ask to BotFather (like changing the profile pic of your bot, for example) but for this basic tutorial, we won’t need anything else.
Now, you’re going to face a tough decision: what will your bot do? The bot we will create with this example will give visitors information about their biorhythm. If you don’t know what a biorhythm is, check this page on Wikipedia and you will find out two important things:
- According to the theory of biorhythms “a person’s life is influenced by rhythmic biological cycles that affect his or her ability in various domains, such as mental, physical, and emotional activity”.
- The proposal has been independently tested and, consistently, no validity for it has been found. 🙂
So our bot will be as useful as reading the horoscope… that’s cool uh? 🙂
But don’t worry: at the end of the article, you will be able to program any kind of bots, either completely useless like this one or useful ones! 🙂
Now, let’s see how can we program the bot.
The python-telegram-bot package consists of a wrapper around Telegram APIs. The Telegram APIs are exposed via the telegram.Bot class. However, on top of this class, they have built the telegram.ext module, which will make your work a lot easier, allowing you to create a bot in minutes.
The telegram.ext module contains a lot of classes, but the most important two are telegram.ext.Updater and telegram.ext.Dispatcher . The Updater class is responsible for fetching new updates from Telegram and passing them to the Dispatcher class, which will handle them through a Handler class.
So let’s start coding!
This first example is quite trivial. In the main function, we have created the Updater class, which has automatically created for us a Dispatcher object, available through the .dispatcher property of the Updater class.
Then, we’ve added some handlers for:
- the /start command (we simply call the callback function start() that reply to the user with an informative message)
- the /help command (we simply call the callback function help() that reply to the user with an informative message)
- what happens if an error occurs while dispatching messages (we simply call the callback function error() )
- what happens if the user writes something that is not a command (we simply call the callback function text() that reply to the user with the same text received)
Finally, we have written the callback functions, that use the update object received to send messages to the user.
Let’s test this primitive bot. Start your bot with:
and now, let’s start chatting with our new bot:

Now, we wanted to create a bot to tell the user their daily biorhythm, right? This will be easy, we will use the /start command to get the birthday of the user as the chat starts, and then we will create a function to handle a new /biorhythm command to answer the user with its personal biorhythm.
Let’s start with the first part: knowing the user’s birthday.
The first thing to do is to change the function that handles the /start command. We will ask the user it’s birthday and we will call a function to start the interaction with the user. To make it simple, we will ask the user the year, the month, and the day they were born in.
As you can see, in the update parameter you will find also some useful information about the user, like its name. However, since this is just a starting tutorial to whet your appetite, I won’t discuss here the thousand of things you will be able to do with this package, if you want to know everything about the python-telegram-bot package, just check the official documentation.
Now, at the very beginning of our script, we will define a new variable STATE that will be used to understand what question the user is answering. Don’t worry if you can’t get it now, you will get it in a minute.
Now, we need to implement the function start_getting:_birthday_info() we are calling in the start() function and that starts… getting birthday info from user 🙂 :
As you can see, at the beginning we set the variable STATE to the value BIRTH_YEAR so that we will know, when the user will answer, that it was answering the birth year question. Then, we just send a message to ask for the year of birth.
Now, the user will answer with a normal text, right? So we need to change the text() function to wait for its answer:
Here in the text() function we just need to understand what’s the question the user is answering by using the STATE variable we defined before, and call a specific function to handle each answer.
These functions could be written like this:
As you can see, when we receive the user birth year, we just check if it is a valid value and in this case, we save it to the context.user_data[] dictionary, and then we go ahead setting the next value for the STATE variable and asking the next question.
When the last question is asked and we received the day of birth, we just create a date variable and store it in the context.user_data[] dictionary as well.
If the user enters an invalid value, we just tell them that it’s not correct and doesn’t change the value of the STATE variable, so the user is stuck with that question until it doesn’t answer correctly.
Ok, now we just need to handle the /biorhythm command and we’ve finished.
Let’s start adding a new command handler into our main() function:
and let’s write the function that calculate the biorhythm:
As you can see I have written two different functions, one to handle the command and the other one to calculate the biorhythm to separate the responsibility of these functions.
So, here there’s the complete code of our bot:
It’s time to test it, right?

Oh my gosh… I hope you won’t find too many mistakes in this article, but in that case bear with me, my intellectual cycle today is only at 28%… that’s not so good uh?
I will keep the bot alive, so you can try it if you want (the username is @mastro35_mastrobot) but if it doesn’t work … consider that it’s running on my raspberry pi and that it could be offline sometimes…
Ok guys, it’s enough for today! If you liked this article feel free to click on the buy me a coffee button or subscribe to become a member and support me on a monthly basis.
Happy coding and… stay safe! D.
Did you find this article helpful?
Categories: Dev
Updated: January 16, 2021
You May Also Enjoy

The Sunday tip #2: Measuring Python code performance with the timeit module
Good code is also code that performs well, here’s how you can measure your code’s performance in Python

The Sunday tip #1: Python cached integers
Did you know that Python compiler optimize your program caching small integers?

Managing Python versions with pyenv
Are you sure that you are installing Python right?

How to create a computer virus in Python
Is it possible to create a self-replicating virus in Python? In this article, we’ll find out…
Как подключить телеграм бота python?

Самый свежая, современная и всегда самая актуальная библиотека — aiogram.
По ссылке открывается репозиторий. В нём есть примеры.
Если машина, с которой вы запускаете бота, находится в РФ, то вам понадобится использование proxy (в связи с блокировкой от РКН).
Бесплатные прокси можно поискать в телеграм, или купить доступ к прокси за небольшие деньги.
Как установить telegram ext python
In this article, we are going to see how to create a telegram bot using Python.
In recent times Telegram has become one of the most used messaging and content sharing platforms, it has no file sharing limit like Whatsapp and it comes with some preinstalled bots one can use in any channels (groups in case of whatsapp) to control the behavior or filter the spam messages sent by users.
Requirements
- A Telegram Account: If you don’t have the Telegram app installed just download it from the play store. After downloading create an account using your mobile number just like WhatsApp.
- .python-telegram-bot module: Here we will need a module called python-telegram-bot, This library provides a pure Python interface for the Telegram Bot API. It’s compatible with Python versions 3.6.8+. In addition to the pure API implementation, this library features a number of high-level classes to make the development of bots easy and straightforward. These classes are contained in the “telegram.ext” submodule. For more information, you can check their official GitHub repo.
Installation of the module
We can install this module via pip and conda with the below command.
Steps to create your first bot
Step 1: After opening an account on Telegram, in the search bar at the top search for “BotFather”
Step 2: Click on the ‘BotFather’ (first result) and type /newbot
Step 3: Give a unique name to your bot. After naming it, Botfather will ask for its username. Then also give a unique name BUT remember the username of your bot must end with the bot, like my_bot, hellobot etc.
Step 4: After giving a unique name and if it gets accepted you will get a message something like this –
Here the token value will be different for you, we will use this token in our python code to make changes in our bot and make it just like we want, and add some commands in it.
Как установить telegram ext python
Telegram can be used for chatops using the extensive Bot API provided.Its user base,availability of mobile and web app support makes it good candidate for personal and small business use,if not enterprise.
Let’s build a sample Bot which send us random photo from Unsplash using Python,inspired by this post
Create Telegram Bot
Interestingly Telegram provides us an official Bot BotFather to request our Bot creation.Open the link in Telegram and request your Bot.

Request Unsplash API key
With the Bot now available we need Unsplash API key for our Bot to access and request images.The procedure is simple.
- Visit Unsplash Developer page
- Register and request API key for your account.

Additonal documentation on using API is available here
Install dependencies
With Telegram Bot and Unsplash API key its now time to prepare your Python environment.Install the Telegram Bot library using
Main Program
With our unique URL we can fetch the random image details as a JSON which will be used by our Bot to respond to the User.

Below is the sample program to create a Bot.I have updated the script in the source to use latest Bot API.
Using Bot
We are now ready to use our Bot.
- Run the Python script above.
- Start conversation with our Bot from Mobile or Web.
- Send /pic as message
- The Bot responds with random image.
Congrats you have built your first usable Telegram Bot.

What’s Missing
You might have started noticing the limitations in your script and Bot,the availability,memory usage,timeouts etc.