
This is a comprehensive telegram bot guide/tutorial in one place to get you going in the shortest time possible.
Telegram bot have so many features, but here we focus on the most used tools that you will highly likely need to make your first bot.
If you are interested only in code, go to “How to make telegram bot” section.
Why make telegram bot
If you have decided to make a telegram bot, then you already have a use for it, but anyway, this is a list of possible use cases that I already use telegram bot for:
- Automate user interactions and data acquisition.
Telegram bot is a great way to automate data collection from users, effectively cutting the need for employees to do so.
Whether you are collecting users data for advertisement purposes, customer service or any other purpose, telegram bot is a great way to do that while ensuring implied user consent, because the user will enter his data himself. - Integrate with your online store/shop.
You can use telegram bot to complement your online store, allowing people to buy products and services, as telegram bot has the ability to process payment using it’s API. - Use it as Restful API client
If you have any server or web app that you need to control/access from your phone wherever and whenever you want, telegram bot is your friend.
Integrating aiohttp library (or any similar library) into your telegram bot you can use commands to send API requests to that web app, thus eliminating the need for a using desktop or any non-trusted app.
Though in this case you have to make sure that only your telegram account can use it to send API requests.
How does telegram bot work
A functioning telegram bot has 4 components:
- Registered telegram bot, that has it’s own telegram user_name and link.
You or other users will use this user_name to chat with your bot.
Registering a bot on telegram will also generate a unique access token that is required for you to make the bot logic. - Telegram bot API.
This is owned by telegram (the company).
They provided us with this API so we can make use of their powerful messaging app for more than messaging.
It’s hosted on their servers, it’s already their, so you don’t need to do any programming on that side, but it’s important to know about it to understand how telegram bot works. - Your telegram logic server
This is where you -as a programmer- come in.
You will program this part to determine the logic of your bot, in other words, you will write the code that process input coming from the user. - Telegram app itself, as it’s the interface that users will see and interact with.
This is the regular telegram app that any user can install on their phone from Apple’s app store or Google’s play store.
Of course computers’ telegram app and telegram web will work as well, they are just less common to use as most users depends on their phones.
The flow of data in a telegram bot
When a user want to interact with your telegram bot, this is how the data flows in the system:
- User search for your bot by user_name or clicks on the bot’s link, and it will open a chat with your bot on the telegram app on his phone.
- User interact with your bot, messaging it directly or use commands defined by you as the owner/programmer of the bot.
- The user’s input go straight to a telegram server owned by the company (normal users don’t know that you have a server, and can only interact with the company’s server).
- Your logic server gets user’s input from telegram’s (the company) server (later you will see how that happens) , and now starts processing it with the logic that you have put on it.
Once your logic server finishes processing the input, it sends back the response/output of that process to telegram’s (the company) server. - Telegram’s server send this response back to the user, on the chat that he has with your bot, so he can see it on telegram app on his phone.
example: user says “hello” to your bot on the app >> This message goes to telegram’s server >> Then from telegram’s server to your logic server >> say that you have programmed your logic server to respond to that specific message with “Hey, how are you doing today” , then your logic server sends this response to telegram’s server >> telegram’s server sends this response back to the user’s telegram app >> the user see that you bot responded to his “hello” message with “Hey, how are you doing today”.
↓↓ Check this simple info graphic below ↓↓

What you need to make a telegram bot
- Make/register a new telegram bot
telegram has provided you a bot called @BotFather , you use this bot to register a bot that you own.
You choose a name and a user_name for your bot.
Don’t forget to copy the token of your bot, and save it somewhere safe, as this is how you are authorized to control the bot, anyone who has this token can control the bot, so make sure no one but you have this token. - Programming skills.
You need to have programming skills in at least one programming language, as you will be the one who will program your logic server to control the behavior of your bot. - A server to deploy your telegram bot.
When you finish programming and testing your telegram bot, you need to deploy it some where so that it keeps running and responding to users.
How to make telegram bot
Organize your telegram bot code into sections
When you write the logic code of your telegram bot, it helps a lot to organize your code into chunks/sections so it’s more readable, easier to debug and you know where to look when you need to fix/update some functionality of your code.
It’s also a time saver to use functions whenever possible, or whenever you think you may need to re-use some kind of functionality later on in your code.
This concept is known among programmers as DRY (Don’t Repeat Yourself), and it makes your code more organized, more readable and take less time to develop.
Imports, variables and classes
Exactly as it sounds, you use this section to include libraries and to declare variables.
One of the important variables to declare is the token variable, which will be a string variable that contains the token you got from BotFather.
from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import Application,ApplicationBuilder,Updater, CommandHandler, MessageHandler, filters, ConversationHandler, CallbackQueryHandler, CallbackContext, ContextTypes , JobQueue import asyncio, re, atexit, aiosqlite ############## ### variables ### ############## my_token = “put you token here” trusted_users = [] ## list of trusted users users_to_notify = {} ## dictionary of users to send notifications, user_name:user_id
Database declaration and functions
If your bot will interface with a database -which is likely- then it’s recommended to create the database at the beginning of the program you write.
After that you can define the functions that will interface with the database in this section as well, then use those functions later in the bot logic to interface with the database.
I recommend using some library that support asynchronous operations, since the telegram API supports async operations already, and so most of telegram libraries out there.
db = aiosqlite.connect('db_name.db') cursor = db.cursor() cursor.execute(‘CREATE TABLE IF NOT EXISTS table_name(table_attributes)’) db.commit async def some_db_function(): ## some code here
General purpose functions
Here you can define any other type of functions that you need in your bot, example calculations, processing input data, rest-API requests, integration with 3rd party services (google, Microsoft, banking, etc..).
##################### ### general functions ### ##################### def some_math_function(): ## do some math # saving db and shutting down gracefully def close_db(): db.commit() db.close() print('\n\nDB was successfully saved and closed\n\n') exit() # end # execute a function at exit atexit.register(close_db) # end
Telegram bot functions
These are the functions that are executed on your bot, each has it’s own purpose and usage.
Keep in mind that telegram bot API and most of the libraries that support telegram bots support asynchronous execution, and in most cases you are required to declare your functions as async, (with the exception of the main function that has the bot application instance, this one must not be asynchronous)
commands
These are functions that are called and executed when a user sends a command to the bot, and it starts with ‘/’ symbol
You need to make a command function inside your logic server to make it work, and you need to set a command in Botfather to make it visible to users, and when you set it as visible to user he can use that command simple by tapping the command from the menu.
A command is set by you the programmer to make it easy for a user to start or execute a task.
Note that if you programmed a command and didn’t set it in BotFather as visible to user, the user can still be able to execute it if he write it as a message, (example if he writes “/help”), this can be useful for you if you want to add some administrative commands that are not visible to users, but keep in mind that you still have to protect access to these commands (more on that later).
Messages
You use messages functions to tell the bot what to do if it receives a message.
You may want to process that message, or perhaps you want to point the user towards using a command.
You certainly can choose when the bot can reply, and control the behavior of the bot if the user message the bot directly or in a group which your bot exists in.
data collection
Some times you want to use the bot to collect data from the user.
You usually use a conversation to do that, this way your bot can manage a conversation with the user asking him to enter specific information or answer a specific question.
It’s useful to put data-collection functions in a separate section, as these may get long and make up a big chunk of your code, separate those functions and thank me later.
Objects
Most of the times you want to use telegram’s features to your advantage, as telegram has many objects that you can use in your logic code.
For example: say you want to give users multiple choices poll, and the user to choose from those choices, so you can use one of telegram’s keyboard objects.
You can use these objects by defining a function that will describe and return an object to the code.
Error
When errors happen, and they will most likely happen, you want to have at least errors reporting in your code.
Main function
The main function is the function that brings your work all together to run your bot.
Note that the main function can not be asynchronous, as if contains the bot instance declaration.
application instance
When you finally finish writing all your bot’s functionalities it’s time to declare a bot instance.
The exact syntax to declare a bot depends on the library you are using, but usually this where you use your token.
Handlers
After declaring a bot instance you need to declare handlers, these link the action that the user take with a function that you declared before.
Examples are: conversation handler , command handler , error handler, etc…
polling or web-hook setup
Now you need to set how your bot-logic server will communicate with telegram’s API.
You have two ways: polling or web-hook.
Polling means that your logic server will communicate with telegram’s server every x seconds.
To use polling you need only to set up polling interval on your logic server.
Web-hook means that telegram’s server will contact your logic server immediately whenever it receives an update from any user
To use web-hooks you need to set up your logic bot to listen to a certain port and set address and port on telegram’s API.
Telegram API can send you web-hook requests on port 443 or 8443, so you need to have one of them available on your logic server.
For testing phase using polling is the only logical way, and for production usage I still recommend using polling, for it’s simpler, you can move your bot to another node without changing any configurations and you can run it on any node even if it doesn’t have a static IP address.
running main function
Now you need to run you program, which means you run the main, which contains all the handlers.
A full example here:
################## ### main and run ### ################## def main(): app = Application.builder().token(my_token).build() # handlers app.add_handler(CommandHandler('start',start)) app.add_handler(CommandHandler('shutdown',shutdown)) app.add_error_handler(error) zzz = ConversationHandler(entry_points=[CommandHandler(‘command1’, command1)],states={0:[MessageHandler(filters.Text and ~filters.COMMAND, collect_name)]}, fallbacks=[CommandHandler('cancel',cancel_conversation)], per_message=False, conversation_timeout=300) app.add_handler(zzz) # polling print('starting polling') app.run_polling(poll_interval=0.8) if __name__ == '__main__': main()
Note 1: when your code gets large (1000+ lines) which is easy after a few days of adding features and fine tuning edge-cases, it may help to off load some sections of your code to other files and import these files into you main code file.
For example you can move your general purpose functions or database functions to external files, and when you need to make any change to those functions you can update those files.
Note 2: There are more handlers and functions in telegram bot API, but these are the most commonly used and the ones you will likely need when you start your telegram bot journey.
Test your telegram bot
Testing a telegram bot includes running the bot to check connectivity and check it’s functionality trying every handler and every command.
Handling edge-case inputs are a main concern when testing, because you never know what the user may enter.
Deploy your telegram bot
When you are done testing and everything is running correctly, it’s finally time to launch your bot.
When you want to deploy your bot, it’s preferred to use a server that is always on and always connected to the internet.
Note that the word server doesn’t necessarily mean you must have a very expensive computer in a server rack, it can be any computer that is always on and always connected to the internet.
An easy and cheap way if you want to run a telegram bot is using something like a raspberry pi or get yourself a VPS subscription.
Extra tips for you telegram bot:
- Deploy You telegram bot only once
When you want to use polling technique to connect your bot server, you should never run two instances of your bot, for this will not work and it will make your first server stop working.
Instead, it’s recommended to register a separate telegram bot for testing purposes, so you can run tests of your new bot version without disconnecting the first bot. - Use docker containers (recommended)
When you want to deploy you telegram bot on a server it’s recommended to use a docker container.
Running an app or service in a container has many benefits like the reuse, isolation and ease of updating your app. - Deploy your telegram bot as a binary
If you are using a VPS it’s recommended to deploy your bot as a binary, this way you can ensure high security, as your code will contain the bot token it’s not recommended to just leave that code on the server in the form of a readable file.
When you want to deploy you bot as a binary, I suggest that you make a minimal docker image that can run a binary, without copying any binary to it.
All you need to do is to choose a work directory, then mount a directory from your host to that working directory in the container before starting the container.
Copy the binary to that directory of your host, and start the container with a command to run the binary. The code below will show you how to make an image for this purpose.
## check platform, if you are on ARM then use ARM base image FROM fedora:latest ## the following line will create a variable that you can change when running the container ENV TZ=Europe/Rome ## following line will choose /app as the working directory for following commands, it will create it if # it does not exist WORKDIR /app ## You prefferably can copy nothing, but use -v to attach a directory from host to /app instead # COPY --chown=root:root --chmod=755 binary_file . RUN dnf install -y tzdata glibc && dnf clean all RUN ln -fs /usr/share/zoneinfo/$TZ /etc/localtime CMD ["/app/banary_file"]
- Updating your telegram bot binary
When you need to update your bot, finish testing of your new version, build it into a binary, then when it’s done, stop the container for few moments and copy the new binary to replace the old one, then start the container again.
You can also automate the update and deployment process to start when least traffic is expected, but that’s a task for another day. - Set telegram bot to send you error reports
When you are testing your bot console feed back is enough, but after deploying your bot to the server you can’t always access the console, that’s way I recommend to make the bot send you any error that happens someway, on telegram, email, sms, or any other way, so you can know immediately when an error happen and act to fix it. - Get familiar with documentation
It can be intimidating to start working with a new framework or library, it’s easy to get lost, you don’t know where to start, you don’t know what resources to use… I’ve been there myself.
The best advice I can give you is to take a breath, understand that you need a bit of research before you start coding, and realize that you have an ally, it’s called the documentation.
Open the documentation, read the welcome page, and don’t get into examples right away, instead, look at the index, the structure of pages, and try to understand how it is organized.
The reason I want you to do that, is to get to know the primary sections/sectors, try to draw a map in your mind to the documentation site, what each section talks about, why would you want to read it, and is that functionality that this sector is talking about useful for what you have in your mind.
Sooner or later you will need to check the documentation for guidance, that’s when your understanding to the documentation structure becomes useful, because when that happens you will know exactly where to look. - Make a command accessible for only a selection of trusted administrative users
You may want to have some protected commands in your bot, that no one can access but you and your team, for example commands for statistics and analysis, or commands to update your data base.
Even if those commands are hidden (don’t appear in the menu) , you still should protect those commands.
A common way to do so, is by using the telegram accounts user_name of the user who is using the command, you can declare a list of trusted users who have privileges and check against that list.
An example:
async def protected_function(update: Update, context: CallbackContext): user_name = str(update.effective_user.username) if user_name in trusted_users: print(f"Trusted user '{user_name}' is trying to execute function zz") ## add your logic here else: print(f"user {user_name} is blocked from accessing a protected command") await update.message.reply_text("You are not authorized to use this command")
- Keep using version control
Using version control tools like git is not a luxury, it’s a must when you are developing a program, even if you are not collaborating with other programmers, for it’s benefits of branching, backup (on remote server or cloud services like GitHub or GitLab) and release management among other benefits.
Backup tools that are based on files copy to other destinations are not enough for a programmer, even if it is automated and remote based, for they don’t retain history and don’t give enough control over the structure of the code.
If using a console to manage git repositories is not for you (although I recommend that way), then you can use any GUI tool to control your repositories.
Nowadays git is well integrated in many IDEs and code editors like Kate and others. - Pro tip:
If you want to receive API requests to your telegram account as a notification mechanism, you need to use some web app framework to do so.
Integrating a web app framework with telegram BOT is a great way to have your own webhook where otherwise you don’t, especially when mixing that with aiohttp library as well, it’s a very powerful tool that is under-estimated.
Here’s an example of how I do it myself:
I have multiple docker containers on a server, and I use telegram to control those containers and get reports on their status.
I have an API as a docker container on that host machine that is soul purpose is to work as a portal on that machine.
Using aiohttp, I can send REST requests to that docker to do something to some other container (example: read status, restart, run a command on it, etc…) , the API container receives this request and perform that task, then collect the output of the command from std_out and sends it back to my telegram bot as another REST request, then the API on my telegram logic server will receive and read this request, collect it’s payload and sends it back to my telegram chat as a message with notification.
This is how I can control any container on any server I have with my phone without some un-trusted 3rd party app.
And remember, if you can imagine a task, you can make it happen.
Need to develop and deploy a telegram bot as fast and securely as possible?
You can hire me on Fiverr or Upwork.
Share this article