Many Telegram users , sooner or later, consider creating their own bot to automate tasks , reply to messages, or simply experiment with code. The good news is that you don't need to be an engineer or have a massive server at home. Creating a Telegram bot with Python only requires a little patience and dedication.
In this guide, you'll learn how to create a Telegram bot with Python step-by-step from scratch. We'll cover exactly what a bot is, how to obtain the famous token with BotFather, how to set up the environment on your computer, how to make your bot send its first message, how to program commands, and even how to extract real-time data (such as the price of Bitcoin) and automatically send it to your chat every day.
What is a Telegram bot and what types exist
A Telegram bot is essentially a special account controlled by a program rather than a person . This program connects to Telegram's servers through its API and can read what's written in the chats where it's present and respond with messages, buttons, polls, files, or any other action you've programmed it to perform.
The idea is that the bot can react to commands or messages and perform specific tasks without human intervention: send reminders, display information from a database, manage reservations, moderate groups, play with gifs, control smart lights, or act as a 24/7 assistant for an online business.
In Telegram there are two main ways to interact with bots that you might want to know about:
- “Normal” command-based bots. The user types commands that begin with “/”, such as
/start,/helpo/list_languagesand the bot responds with a specific action. They are perfect for menus, FAQs, booking systems, or any guided workflow. - Inline bots. Instead of using “/”, the user writes
@nombre_del_botdirectly in any chat, followed by a text. The bot responds "online" suggesting results, for example, @gif to search for animated GIFs related to a keyword.
In addition to these, you can also have bots that react "spontaneously" to what is written in a group. For example, detecting insults to act as anti-spam, greeting new members, or applying moderation rules without anyone typing an explicit command.

Why Telegram bots have become so popular
One of the reasons Telegram bots have exploded in popularity is that the platform offers a very open API with virtually no restrictions for developers . You don't have to request special permissions or go through endless reviews like in other messaging apps. You simply contact BotFather, create your bot, and in seconds you have a token ready to use.
This freedom has allowed bots to flourish for almost everything: managing groups and channels , launching surveys, controlling e-commerce processes, connecting with external services, receiving real-time data, or even handling internal company tasks (onboarding, team notifications, support workflows, etc.).
It also helps that the bot API is very easy to understandYou can work at a low level using HTTPS requests to https://api.telegram.org/botTOKEN/METHOD_NAME or rely on bookstores like python-telegram-bot, pyTelegramBotAPI or similar libraries in Node.js that abstract away a lot of complexity.
In the real world, this translates into a wide variety of uses. From weather or cryptocurrency price bots to complete customer service systems, educational bots, stock market notifications, or integrations with tools like Google Calendar, Trello, corporate CRMs, and much more.
Create a bot with BotFather and get the token
Before touching a single line of code, you need to let Telegram know your bot exists. This is done using @BotFather, Telegram's official bot for registering and configuring bots . The entire process is done within the app itself, on both mobile and desktop.
The basic steps to register your bot are very simple and always involve this sequence of messages with BotFather, which are handled as if you were chatting with another user:
- Open Telegram, type in the search bar @BotFather and enter the verified conversation (it has a blue checkmark).
- Press "Start" or type
/startto see the list of available commands. - Launch the command
/newbotBotFather will first ask you for a display name (what users will see on the profile) and then a Username which must end inbotand it cannot begin with a number.
For example, you could use “Btc Price” as the name and something like btc_daily_update_botOnce you complete the steps, BotFather will send you a message with several recommendations, the URL t.me/tu_usuario_bot and, above all, a API access token.
That token has a format like this: 110201543:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw And it's the key that allows your code to impersonate your bot to Telegram's servers, so Treat it like a secret: don't publish it on GitHub or share it anywhere..
From BotFather you can also customize your bot with other useful commands:
/setdescriptionto add a short description that will be seen when the bot's chat is opened./setabouttextfor the biography visible in the profile./setuserpicto upload a profile picture that doesn't look so bland./mybotsto see all the bots you've created and edit them./setcommandsor “Edit Commands” to define the list of commands that your bot will understand (for example,start - Inicia la conversación).
With this, you now have the "shell" created. The E bot exists on Telegram, has a name, description, image, and, most importantly, a unique token to connect from your code . The next step is to bring it to life with Python.
Prepare the Python environment and create the project
While you can program Telegram bots using many languages, Python is one of the most convenient options thanks to its simple syntax and the large number of available libraries. To follow this tutorial, you need to have Python 3 installed on your computer and, of course, the Telegram application (on mobile or desktop).
As a best practice, it's ideal to always work within a virtual environment (venv) . This way you avoid mixing dependencies between projects. From the folder where you're going to create your bot, you can do something like this on Windows:
py -m venv venv
.\venv\Scripts\activate
On macOS or Linux the activation command changes slightly, but the idea is the same: Create an isolated bubble where you can install only the libraries your bot will use.Once the environment is activated, it's time to install the necessary packages with pip.
Depending on the approach you want, there are two fairly common paths to getting started with Telegram bots in Python, and it's worth knowing them to choose the one that best suits your project:
- Working directly with requests and the HTTP API. You manually construct URLs of the type
https://api.telegram.org/botTOKEN/sendMessageYou send GET or POST requests withrequestsand you process the responses in JSON. - Use a library like python-telegram-bot. This library abstracts the API and gives you high-level objects like
Updater,Dispatcher,CommandHandleroCallbackContextto work with commands and messages in a much more organized way.
If you want a more structured bot with commands like /start And for a scalable design, you should also add the library python-telegram-botwhich is installed with a simple:
pip install python-telegram-bot
Make the bot send its first message using the Telegram API
Let's start with the basics: getting your bot to send a message to your own Telegram chat using the HTTP API directly. This will help you understand how requests are constructed before we complicate things with more features.
For the bot to message you, it needs two key things: the token BotFather gave you and your chat ID . Obtaining your chat ID is very simple if you follow this process carefully:
- Open the chat with your bot in Telegram via the link
t.me/tu_usuario_botor by searching for him by his username. - Type the command
/startso that there is at least one message in the history. - In your browser, enter the URL:
https://api.telegram.org/botTU_TOKEN/getUpdates
By accessing that address, the API will return a JSON object containing the latest messages associated with your bot. Inside, you'll see fields like "update_id", "message_id" and, very importantly, the field "chat" with its "id"That number (something like that) 68xxxxxxx) is your private chat ID, which is what we will use to send messages directly to your conversation.
With the token and chat ID in hand, you can define in your file py a minimal function that constructs the appropriate URL and launches the request with requests.getThe method we're going to call in the Telegram API is sendMessagewhich accepts parameters such as chat_id, text and the format mode (for example, parse_mode=Markdown).
The typical structure of that function, simplified, would be something like this, where you can clearly see how the URL is constructed and the API call is made with the necessary data:
def bot_send_text(bot_message):
bot_token = 'YOUR_TOKEN'
bot_chatID = 'YOUR_CHAT_ID'
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message
response = requests.get(send_text)
return response
Outside of the function, you can try sending a test message by creating a variable and running the file with Python. If everything is configured correctly, you'll see a message like "Hello, Telegram!" appear in your bot's chat within seconds.
test_bot = bot_send_text('¡Hola, Telegram!')
Schedule recurring messages with schedule
The next thing you'll probably want to do is automate the sending of that report so that it arrives every day at a fixed time without having to run anything manually. The library is very convenient for that. schedule, which allows you to plan tasks in a very readable way.
With schedule You can tell your script things like “execute the function report Once a day at 08:00 AM, and then let it run in an infinite loop checking for pending tasks. As long as the program keeps running, your bot will act at the specified time.
The typical script entry block, using the pattern if __name__ == '__main__'It would look like this to keep the bot powered on and attentive to scheduled tasks:
if __name__ == '__main__':
schedule.every().day.at("08:00").do(report)
while True:
schedule.run_pending()
It's important to use this type of automation with common sense to avoid overloading the website you're scraping . There's no point in making requests every second for data that could be accessed, for example, once a day or even once an hour. If you overload the destination server, you'll end up getting blocked.
Keep in mind that, working this way, your bot will only function as long as the script is running on your computer . If you close the terminal or shut down your computer, the bot will stop sending scheduled messages. To keep it active 24/7, it's best to upload the code to a server or a cloud service.
Design a structured bot using the python-telegram-bot library
As your project grows, working solely with HTTP requests can become chaotic. This is where the python-telegram-bot library comes in, organizing code around objects and command handlers and making your life much easier.
This library is based on a couple of key concepts: the object Updater, which is responsible for communicating with Telegram's servers and sending responses, and the dispatcherwhich would be something like the bot's "ear", always listening to incoming messages and deciding which function to execute when a specific command or text enters.
The cleanest way to work with your token is to isolate it in a configuration module, for example in a package called config where you save a file auth.py with a variable token. Thus, You don't upload the token to the repository, and you can add the file to your .gitignore. to avoid scares.
A very minimal first skeleton of your file bot.pyUsing the library, it could look something like the following, where the creation of the Updater and how is it obtained dispatcher associated:
from telegram.ext import Updater
from config.auth import token
if __name__ =='__main__':
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher
If you run that file as is, you'll see that the script simply finishes without errors, but it still doesn't do anything useful because you haven't told it how to react to the messages. The next step is to add event logging and define functions that act as "handlers" for the commands you want to support, usually starting with /start.
The Python standard library logging It allows you to have detailed control over what's happening inside your bot: what commands are received, if any errors occur, etc. Setting it up is as simple as defining an output format and a minimum severity level for messages:
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger('MiPrimerBot')
With this configuration you will indicate that you want to see messages on screen from INFO level upwards (INFO, WARNING, ERROR, CRITICAL) and that each line should include the date, the name of the logger, the level and the explanatory text of the event you are recording.
Respond to the /start command with a custom handler
To make your bot more than just a decorative figure, you need define functions that are executed when a specific command arrivesThese functions are called “handlers” and always receive an object as an argument. update or with a context.
Parameter update This represents the incoming message (whether a command, plain text, etc.) and includes data such as the chat, the user, and the message content. The parameter context It represents the bot itself, with methods for responding, sending photos, etc. It typically logs when a command is received and responds with a text message.
A very simple example of a handler for the command /start It would be something like this, where the logs record that the command was received and a response is sent to the same chat from which it was sent:
from telegram.ext import CallbackContext
def start(update: Updater, context: CallbackContext):
logger.info('I have received a start command')
context.bot.send_message(
chat_id=update.message.chat_id,
text="I'm from Jerez de la Frontera, the birthplace of fino sherry, Carthusian horses, and the World Capital of Motorcycling"
)
Now that you have defined the function, you must tell the dispatcher that it uses it when the command arrives /startThat's what the object is used for. CommandHandler, which maps a command text (without the slash) to the function responsible for handling it.
Registering the dispatcher is very straightforward and easy to read: “when you receive the start command, execute the start function” . The code needed to register this behavior would look something like this within the main block:
from telegram.ext import CommandHandler
if __name__ =='__main__':
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
updater.idle()
The last two lines are extremely important: start_polling() This causes the bot to regularly ask Telegram's servers for new messages (a method known as polling), and idle() It keeps the program running until you manually stop it with Ctrl+C on the console.
If you now run python bot.py and on Telegram you write /start Your bot should display the message you programmed in the handler, in addition to the corresponding log entries for each command received.
Options for hosting and running your bot 24/7
An important detail that is often overlooked is that Telegram doesn't run your code . Its servers only store messages and provide the API, but the program that controls your bot has to run somewhere, whether it's your own computer, a VPS, or a cloud hosting service.
If you're just testing, you can keep the bot running on your local machine as long as you have the console open. But if you want it to be available 24/7 to users, sooner or later you'll have to upload it to an environment that's always on and has good connectivity.
Among the most common options for small and medium-sized projects, you'll find platforms like Replit , Render , and DigitalOcean , each with its own advantages in terms of ease of use and cost. Broadly speaking, you can expect a landscape similar to this:
| repeat | Yes | Simple, it's great for beginners |
| Render | Yes | Media |
| Digital ocean | No | Simple, powerful and spacious |
For simple and learning bots, the free tiers of some services are usually sufficient, although it's advisable to monitor limitations on execution time, CPU consumption, or outgoing connections so that the bot doesn't crash without you noticing.
In terms of technology stack, the usual approach is to opt for Python with libraries like python-telegram-bot if you prefer clarity and extensive documentation, or for Node.js with solutions like Telegraf.js or node-telegram-bot-api if you already come from the JavaScript world and want to integrate with other projects in that ecosystem.
No-code alternatives and professional uses of bots
If programming isn't your thing, or you simply want to build a functional bot at top speed to validate an idea, you have several no-code platforms at your disposal that allow you to create conversational flows with visual blocks without touching a single line of Python.
Tools like Manybot, Chatfuel, Tars, Make (formerly Integromat), n8n, and integrations with Google Sheets and Airtable allow you to define question and answer logic, forms, navigation menus, and connections to other services using graphical interfaces. They are perfect for MVPs, quick tests, or projects where the bot doesn't need to perform overly advanced tasks.
The main difference compared to developing with your own code is that, with these solutions, you sacrifice some flexibility in exchange for speed and simplicity. When you need more complex functionalities, very specific integrations, or total control over the logic, the usual approach is to make the leap to a fully programmed bot.
At a business level, a Telegram bot can become a key tool for providing 24/7 customer service, automating repetitive processes, or collecting structured data without overwhelming the human team. Think of functions such as answering FAQs, managing order tracking, launching customer satisfaction surveys, onboarding new students in an online academy, or handling reservations in a restaurant.
You can also explore business models around bots: premium access to certain features by subscription, paid educational bots, exclusive content, integration with e-commerce or affiliate recommendations with tracking links, always respecting data protection regulations and Telegram's terms of use.
Table of Contents
- 1 What is a Telegram bot and what types exist
- 2 Why Telegram bots have become so popular
- 3 Create a bot with BotFather and get the token
- 4 Prepare the Python environment and create the project
- 5 Make the bot send its first message using the Telegram API
- 6 Schedule recurring messages with schedule
- 7 Design a structured bot using the python-telegram-bot library
- 8 Respond to the /start command with a custom handler
- 9 Options for hosting and running your bot 24/7
- 10 No-code alternatives and professional uses of bots

