Sign In
Sign In

String Conversion in Python

String Conversion in Python
Hostman Team
Technical writer
Python
11.12.2023
Reading time: 9 min

Python is one of the most popular programming languages. It has many built-in methods and functions, including those for working with strings. 

Strings are data objects that store a sequence of characters, including letters, numbers, punctuation marks, etc. String conversion is necessary when the user cannot perform some operations on strings due to their peculiarities. For example, he cannot add two strings storing numbers and get their sum. For this purpose, it is necessary to perform the conversion first and then realize the addition. This principle works for all other data types as well.

This instruction will tell you how to convert strings to other data types.

String conversion

String conversion is the process of changing a string data type to another, implemented using Python's built-in methods. There are several cases when you might need it.

  • Information received from users

This may occur in some applications where the user, for example, fills out an input form. By default, all the specified information will be passed as a string. For further interaction with the data, you'll need to convert them to the correct type.

  • Information read from files.

In this case, the user, just as in the previous example, needs to transform the received sequence of characters, whether they are in JSON or XML files. 

  • Data from the database.

When interacting with the database, some data may also be interpreted into the program code as strings. You'll need to convert them to the appropriate data type for the code to work properly.

  • String Comparison.

If you need to compare two strings, they must be of the same data type. However, the choice of this type depends on the comparison requirements. For example, if you want to find out which of the numbers in the compared sequences are larger, you would convert strings into a numeric data format and then perform the comparison.

Based on the examples above, we can say that it is impossible to correctly perform the required operations in your code without converting strings. The Python built-in methods can help with the implementation of this process.

-

String → Integer

First, let's talk about converting a sequence of characters into numbers. The first method is int(). It allows you to convert a string to an integer in Python. Its syntax looks as follows:

int(example_string)

It takes an initial sequence of characters as an argument and then converts it to an integer.

Let's look at an example:

example_string = "112"
result = int(example_string)
print(result)

The result is shown in the picture below.

Image10

If a function argument contains not only digits but also letters or other characters, int() will not be able to perform the conversion and will generate a ValueError. However, in some cases, it can be bypassed. For example, the user passed a number in hexadecimal notation into the argument, which implies the presence of letters in this sequence. In this case, an additional argument is used that specifies the base of the number system. It will make it clear that it is indeed a number.

Let's look at this example:

example_string = "A1"
result = int(example_string, 16)
print(result)

The compiler will not generate any errors and will output the result shown in the image below.

Image4

We have successfully executed the code and the program has converted the string into a decimal integer 161.

String → Float Number

In this chapter, we will talk about converting a sequence of characters into floating-point numbers. The float() function will help us with this. Its syntax does not differ from the function discussed in the previous chapter. It's worth noting that a float number must contain a period, not a comma. Otherwise, Python simply won't be able to interpret the number passed in the string. 

Here is an example of how to use the function:

example_string = "112.112"
result = float(example_string)
print(result)

This example will convert the character sequence 112.112 into a floating point number. The result is shown in the image below.

Image5

In addition to the above function, we should mention the round() function. It allows you to specify the required number of digits after the point. 

For example, if we need the final number to contain only one digit after the dot when converting the string, we should declare the round() function and pass the corresponding argument:

example_string = "112.112"
result = round(float(example_string),1)
print(result)

After these transformations, the result is as follows:

Image3

String → List

Let's look at converting strings to lists in Python, specifically the split() function. 

Lists are comma-enumerated elements enclosed in square brackets. All elements of a list have their unique identifier (index). The data types of the elements may differ.

Now, let's talk about the split() function itself. It splits a string into a list of substrings using a delimiter. By default, it is equal to a space, but it can be changed if necessary. For this purpose, when calling the function, you should specify a unique delimiter, which will be used to form a list of the sequence of characters.

Let's try to apply this function:

example_string = "Monkey-Lion-Tiger"
example_list = example_string.split("-")
print(example_list)

This will give us a list of 3 items as shown in the image below.

Image1

String → Date

While writing code, a programmer may need to convert a string into a date. For this case, Python also has special modules.

strptime method

This method belongs to the datetime module. It creates a date and time object from a string matching the specified format. 

The syntax is as follows:

datetime.strptime (date_string, date_format)

Consider the example below, where we have a sequence of characters 2023-01-01 12:30:31 that we need to convert to date and time. First of all, initialize the module and then write the rest of the code:

from datetime import datetime

date_string = "2023-01-01 12:30:31"
date_object = datetime.strptime(date_string, "%Y-%d-%m %H:%M:%S")
print(date_object)

The date and time format in the example is %Y-%d-%m %H:%M:%S, but it may be different for you because it depends on the date format in the source string.

As you can see from the picture below, the conversion was successful.

Image2

parser.parse function

Now, let's move on to the dateutil module and its parser.parse function. It works the same way as the previous method, but there is one difference. The parser.parse function automatically determines the format of the specified date. 

The syntax of the function call looks as follows:

parser.parse(example_string)

Now let's consider its use by example, remembering to declare the module at the beginning of the code:

from dateutil import parser

date_string = "2023-01-01 12:30:31"
date_object = parser.parse(date_string)
print(date_object)

In the example, we used the familiar date and time. The result is the same as in the previous method.

Image2

String → Function

A function is a code fragment that performs a specific task and can be used many times. When this code fragment is assigned to a string type variable, you may need to convert it into a function. The built-in eval() function will help with this.

eval() analyzes all the data passed to it as an argument and executes the resulting expression if possible. 

Its syntax is as follows:

eval(expression)

Let's look at the use of eval() with an example:

example_string = "print('Hello, user!')"
eval(example_string)

In this example, we store the call to print() in the example_string variable. eval(), in turn, takes the contents of this variable as an argument and calls the read expression. 

As you can see from the picture below, the function call has been successfully executed.

Image9

Use the above function carefully. You should always control the expression that eval() accepts. If passed in from the outside, for example, by other users, it can harm your system. 

String → Bytes

Bytes are a sequence that, unlike strings, are made up of individual bytes. Their syntax is roughly the same as a regular sequence of characters. The only difference is the prefix b before the beginning of the sequence.

The encode() function will help us convert strings to bytes in Python. It will encode the character sequence and return a string of bytes. All you need to specify when calling it is the encoding. The default encoding is utf-8.

Let's look at the example:

example_string = "Hello, user!"
example_bytes = example_string.encode()
print(example_bytes)

The result is a byte version of the specified string in the example_string variable, as shown in the image below.

Image6

If you want to decode the bytes object back to its original form, use the decode() function.

String → Dictionary

A dictionary is a kind of data structure that stores data in the key-value form.

Let's look at two ways to convert a string to a dictionary in Python. 

json.loads()

The first function we consider is json.loads(). It refers to the json module. It takes an initial sequence of characters in JSON format and converts it into a dictionary.

At the beginning of your code, make sure to import the json module.

Example:

import json

json_string = '{"animal": "Dog", "breed": "Labrador", "age": 9}'
result = json.loads(json_string)
print(result)

As a result, we ended up with a dictionary with 3 pairs, demonstrated in the picture below.

Image7

ast.literal_eval()

The next method is ast.literal_eval(). It belongs to the ast module and performs the same function as the previous method.

Let's go straight to the example, remembering to import the required module at the beginning of the code:

import ast

example_string = "{'animal': 'Dog', 'breed': 'Labrador', 'age': 9 }"
result = ast.literal_eval(example_string)
print(result)

Here we have used the same data as in the previous example. As a result, we got exactly the same dictionary as when we used the json.loads() method.

Image7

The only difference between the json.loads() and the ast.literal_eval() methods is that the character sequence the latter accepts must be in dictionary format rather than JSON format.

Conclusion

In this tutorial, we covered seven types of string conversion. We have also provided examples and alternative conversion methods for each of them. We hope the information you got from this article will help you correctly interact with the string data type when writing code.

On our app platform you can deploy Python frameworks, such as Celery, Django, FastAPI and Flask. 

Python
11.12.2023
Reading time: 9 min

Similar

Python

How to Create a Virtual Environment in Python

This article will teach you how to create a Python virtual environment. It is useful for Python developers to avoid issues with different versions of libraries. A simple example: You have two applications that rely on the same library, but each requires a different version. Another example: You want to ensure that your application runs independently of library updates installed in the global Python storage. A third example: You do not have access to this global storage. The solution in all three cases is to create a Python virtual environment.  The module name venv is short for Virtual Environment. It is a great tool for project isolation, functioning like a sandbox. It allows you to run an application with its dependencies without interfering with other applications that use different versions of the same software. As a result, each application runs in its own virtual environment, isolated from others, increasing the overall stability of all applications. How to Create a Virtual Environment in Python 3 Good news: You don’t need to install venv separately on Windows—it is part of the standard Python 3 library and comes with the interpreter. On Linux, however, venv is not always included in the OS package, so you might need to install it. On Ubuntu/Debian, use the following command: sudo apt install -y python3-venv Some Python packages require compilation from source code, so you might also need to install the following dependencies: sudo apt install -y build-essential libssl-dev libffi-dev python3-dev Now, let's see how to create a Python 3 virtual environment in Windows and Linux using venv. Step 1: Creating the Virtual Environment Use the following command for all operating systems: python -m venv venv Here, -m tells Python to run the venv module. The second venv specifies the directory (venv/lib/python3.8/site-packages/, the version may vary) where Python will store all libraries and components required for isolated application execution. Step 2: Activating the Virtual Environment Activation differs between Windows and Linux. On Windows, run: venv\Scripts\activate.bat On Linux (and MacOS), use: source venv/bin/activate If everything is set up correctly, you will see an output like this: (venv) root@purplegate:/var/test# Now you can start working on your project within the isolated environment! Other Tools Of course, venv is the most modern tool for creating virtual environments. However, it was only introduced in Python 3. So what should those working with older versions of Python do? The answer: try other tools that offer additional useful features—otherwise, we wouldn’t mention them at all. Below is a brief overview of these alternatives, followed by a more detailed look at the most popular one. virtualenv – A simple and user-friendly tool that is widely used when deploying applications. It’s useful to learn, and we’ll provide instructions on how to use it below. pyenv – Allows you to isolate different Python versions. This is helpful if you need to run multiple versions of Python, for example, for testing purposes. virtualenvwrapper – A wrapper for virtualenv that helps manage virtual environments by simplifying tasks like creating, copying, and deleting environments. One of its advantages is that it allows easy switching between environments and supports various plugins for extended functionality. Creating a Virtual Environment Using virtualenv Let's go through the process using Linux as an example. However, running Python virtualenv on Windows is almost the same, with differences mainly in file paths and scripts, which we’ll mention separately. Step 1: Install virtualenv You can download the source code and install it manually, but the easiest way is to use pip. Just enter the following command in your terminal: pip install virtualenv Step 2: Create a Virtual Environment This step requires just a simple command: virtualenv myenv This will create a new directory in the current folder. Instead of myenv, you can use any other name for your environment. Directory structure of the virtual environment: /myenv/bin – Contains scripts for managing the environment, a copy of the Python interpreter, pip, and some package management utilities. In Windows, this folder is located at /myenv/Scripts. /myenv/lib and /myenv/include – Store the environment’s core libraries. Any newly installed files will go into /myenv/lib/pythonX.X/site-packages/, where X.X represents your Python version. Step 3: Activate the Virtual Environment Activation differs slightly between Linux and Windows. For Linux, use: source myenv/bin/activate For Windows, run: myenv\Scripts\activate.bat Once activated, you will see the virtual environment’s name in your command line prompt. If you create the virtual environment with the --system-site-packages flag, it will have access to the system-wide package storage: virtualenv --system-site-packages myenv Keep in mind that the system package paths differ: Linux: /usr/lib/python3.8/site-packages Windows: \Python38\Lib\site-packages Version numbers may vary depending on your installation. Step 4: Deactivate the Virtual Environment Once you’re done working in the Python virtual environment, you should exit it properly. For Linux, run: deactivate For Windows, use the batch file: myenv\Scripts\deactivate.bat What's New? In addition to the venv and virtualenv modules we’ve already covered, there are more modern tools that provide greater flexibility in managing Python projects, including virtual environments: Poetry – A package manager that helps manage application dependencies within a virtual environment. It also simplifies testing and deployment by automating many processes. Pipenv – Another package manager that integrates pip and virtualenv, along with several other useful tools. It is designed to make environment and package management easier, as many developers eventually encounter version control issues in their projects. Each of these tools deserves a deep dive, but for now, let’s focus on the key features of both. Poetry: The Essentials Poetry handles all aspects of managing libraries within a virtual environment, including installing, updating, and publishing them. The functionality of pip alone is often insufficient for these tasks. Additionally, Poetry allows you to create and package applications with a single command (replace myproject with your actual project name): poetry new myproject If you want to initialize an existing directory as a Poetry project, use: poetry init Poetry can also: Publish projects to private repositories Track and manage dependencies Enforce version control Simplify working on private virtual servers by ensuring reliable project isolation Pipenv: The Essentials In simple terms, Pipenv is like pip + virtualenv, but with enhanced features. It eliminates the need for the traditional and sometimes cumbersome requirements.txt file. Instead, Pipenv uses: Pipfile.lock – Ensures package version consistency, which enhances security. Pipfile – A more advanced replacement for requirements.txt. Unlike its predecessor, Pipfile updates automatically as package versions change, which is particularly useful for teams, reducing dependency conflicts. Now you have a complete set of tools at your disposal, and managing multiple dependencies with different versions should no longer be a challenge! 
21 March 2025 · 6 min to read
Python

How to Delete Characters from a String in Python

When writing Python code, developers often need to modify string data. Common string modifications include: Removing specific characters from a sequence Replacing characters with others Changing letter case Joining substrings into a single sequence In this guide, we will focus on the first transformation—deleting characters from a string in Python. It’s important to note that strings in Python are immutable, meaning that any method or function that modifies a string will return a new string object with the changes applied. Methods for Deleting Characters from a String This section covers the main methods in Python used for deleting characters from a string. We will explore the following methods: replace() translate() re.sub() For each method, we will explain the syntax and provide practical examples. replace() The first Pyhton method we will discuss is replace(). It is used to replace specific characters in a string with others. Since strings are immutable, replace() returns a new string object with the modifications applied. Syntax: original_string.replace(old, new[, count]) Where: original_string – The string where modifications will take place old – The substring to be replaced new – The substring that will replace old count (optional) – The number of occurrences to replace (if omitted, all occurrences will be replaced) First, let’s remove all spaces from the string "H o s t m a n": example_str = "H o s t m a n" result_str = example_str.replace(" ", "") print(result_str) Output: Hostman We can also use the replace() method to remove newline characters (\n). example_str = "\nHostman\nVPS" print(f'Original string: {example_str}') result_str = example_str.replace("\n", " ") print(f'String after adjustments: {result_str}') Output: Original string: Hostman VPS String after adjustments: Hostman VPS The replace() method has an optional third argument, which specifies the number of replacements to perform. example_str = "Hostman VPS Hostman VPS Hostman VPS" print(f'Original string: {example_str}') result_str = example_str.replace("Hostman VPS", "", 2) print(f'String after adjustments: {result_str}') Output: Original string: Hostman VPS Hostman VPS Hostman VPS String after adjustments: Hostman VPS Here, only two occurrences of "Hostman VPS" were removed, while the third occurrence remained unchanged. We have now explored the replace() method and demonstrated its usage in different situations. Next, let’s see how we can delete and modify characters in a string using translate(). translate( The Python translate() method functions similarly to replace() but with additional flexibility. Instead of replacing characters one at a time, it allows mapping multiple characters using a dictionary or translation table. The method returns a new string object with the modifications applied. Syntax: original_string.translate(mapping_table) In the first example, let’s remove all occurrences of the $ symbol in a string and replace them with spaces: example_str = "Hostman$Cloud$—$Cloud$Service$Provider." print(f'Original string: {example_str}') result_str = example_str.translate({ord('$'): ' '}) print(f'String after adjustments: {result_str}') Output: Original string: Hostman$Cloud$—$Cloud$Service$Provider. String after adjustments: Hostman Cloud — Cloud Service Provider. To improve code readability, we can define the mapping table before calling translate(). This is useful when dealing with multiple replacements: example_str = "\nHostman%Cloud$—$Cloud$Service$Provider.\n" print(f'Original string: {example_str}') # Define translation table example_table = {ord('\n'): None, ord('$'): ' ', ord('%'): ' '} result_str = example_str.translate(example_table) print(f'String after adjustments: {result_str}') Output: Original string: Hostman%Cloud$—$Cloud$Service$Provider. String after adjustments: Hostman Cloud — Cloud Service Provider. re.sub() In addition to replace() and translate(), we can use regular expressions for more advanced character removal and replacement. Python's built-in re module provides the sub() method, which searches for a pattern in a string and replaces it. Syntax: re.sub(pattern, replacement, original_string [, count=0, flags=0]) pattern – The regular expression pattern to match replacement – The string or character that will replace the matched pattern original_string – The string where modifications will take place count (optional) – Limits the number of replacements (default is 0, meaning replace all occurrences) flags (optional) – Used to modify the behavior of the regex search Let's remove all whitespace characters (\s) using the sub() method from the re module: import re example_str = "H o s t m a n" print(f'Original string: {example_str}') result_str = re.sub('\s', '', example_str) print(f'String after adjustments: {result_str}') Output: Original string: H o s t m a nString after adjustments: Hostman Using Slices to Remove Characters In addition to using various methods to delete characters, Python also allows the use of slices. As we know, slices extract a sequence of characters from a string. To delete characters from a string by index in Python, we can use the following slice: example_str = "\nHostman \nVPS" print(f'Original string: {example_str}') result_str = example_str[1:9] + example_str[10:] print(f'String after adjustments: {result_str}') In this example, we used slices to remove newline characters. The output of the code: Original string:HostmanVPSString after adjustments: Hostman VPS Apart from using two slice parameters, you can also use a third one, which specifies the step size for index increments. For example, if we set the step to 2, it will remove every odd-indexed character in the string. Keep in mind that indexing starts at 0. Example: example_str = "Hostman Cloud" print(f'Original string: {example_str}') result_str = example_str[::2] print(f'String after adjustments: {result_str}') Output: Original string: Hostman CloudString after adjustments: HsmnCod Conclusion In this guide, we learned how to delete characters from a string in Python using different methods, including regular expressions and slices. The choice of method depends on the specific task. For example, the replace() method is suitable for simpler cases, while re.sub() is better for more complex situations.
21 March 2025 · 5 min to read
Python

How to Create and Set Up a Telegram Chatbot

Chatbots are software programs that simulate communication with users. Today, we use them for a wide range of purposes, from simple directories to complex services integrated with CRM systems and payment platforms. People create bots for Telegram, Viber, Facebook Messenger, and other messaging platforms. Each platform has its own rules and capabilities—some lack payment integration, while others don't support flexible keyboards. This article focuses on user-friendly Telegram, which has a simple API and an active audience. In this article, we will cover: How to create a Telegram bot on your own When it's convenient to use chatbot builders for development How to integrate a chatbot with external services and APIs What is needed for the bot to function smoothly The key features of Aiogram, a popular Python library for chatbot development Creating a Telegram Chatbot Without Programming Skills Chatbot builders are becoming increasingly popular. These services allow you to create a bot using a simple "drag-and-drop" interface. No programming knowledge is required—you just build logic blocks like in a children's game. However, there are some drawbacks to using chatbot builders: Limited functionality. Most chatbot builders provide only a portion of Telegram API's capabilities. For example, not all of them allow integration with third-party services via HTTP requests. Those that do often have expensive pricing plans. Generic scenarios. The minimal flexibility of builders leads to chatbots that look and function similarly. Dependence on the service. If the platform goes offline or its pricing increases, you may have to migrate your bot elsewhere. Builders are useful for prototyping and simple use cases—such as a welcome message, answering a few questions, or collecting contact information. However, more complex algorithms require knowledge of variables, data processing logic, and the Telegram API. Even when using a builder, you still need to understand how to address users by name, how inline keyboards work, and how to handle bot states. Free versions of chatbot builders often come with limitations: They may include advertising messages. Some prevent integration with essential APIs. Others impose limits on the number of users. These restrictions can reduce audience engagement, making the chatbot ineffective. In the long run, premium versions of these builders can end up costing more than developing a bot from scratch and hosting it on your own server. If you need a chatbot to handle real business tasks, automate processes, or work with databases, builders are often not sufficient. In such cases, hiring a developer is a better solution. A developer can design a flexible architecture, choose optimal technologies, and eliminate technical constraints that might hinder the project's scalability. If you already have a prototype built with a chatbot builder, you can use its logic as a starting point for technical specifications. How to Create a Telegram Chatbot Now, let's discuss how to create a Telegram chatbot using Python. You’ll need basic knowledge of variables, conditional statements, loops, and functions in Python. To create chatbots, you can use a framework which is a set of tools, libraries, and ready-made solutions that simplify software development. You can work with the raw Telegram API and implement functionality using HTTP requests, but even for simple tasks, this approach requires writing thousands of lines of code. In this guide, we’ll use Aiogram, one of the most popular frameworks for building Telegram chatbots in Python. Step 1: Create a Virtual Environment for Your Project Using a virtual environment in any Python project is considered good practice. Additionally, chatbots are often deployed on cloud servers where dependencies need to be installed. A virtual environment makes it easy to export a list of dependencies specific to your project. Install the Python virtual environment: sudo apt install python3-venv -y Create a virtual Python environment in the working directory: python -m venv venv Activate the environment: source ./venv/bin/activate Step 2: Install Required Libraries Install the Aiogram framework using pip: pip install aiogram Add a library for working with environment variables. We recommend this method for handling tokens in any project, even if you don’t plan to make it public. This reduces the risk of accidentally exposing confidential data. pip install python-dotenv You can also install any other dependencies as needed. Step 3: Initialize Your Chatbot via BotFather This is a simple step, but it often causes confusion. We need to interact with a Telegram bot that will generate and provide us with a token for our project. Open Telegram and start a chat with @BotFather. Click the Start button. The bot will send a welcome message. Enter the following command: /newbot BotFather will ask for a name for your bot—this is what users will see in their chat list. Then, enter a username for your bot. It must be unique and end with "bot" (e.g., mycoolbot). Once completed, BotFather will create your chatbot, assign it a username, and provide you with a token. Keep your token secret. Anyone with access to it can send messages on behalf of your chatbot. If your token is compromised, immediately generate a new one via BotFather. Next, open a chat with your newly created bot and configure the following: Click the Edit button. Update the profile picture. Set a welcome message. Add a description. Configure default commands. Step 4: Store Your Token Securely Create an environment file named .env (this file has no name, only an extension). Add the following line: BOT_TOKEN = your_generated_token On Linux and macOS, you can quickly save the token using the following command: echo "BOT_TOKEN = your_generated_token" > .env Step 4: Create the Script In your working directory, create a file called main.py—this will be the main script for your chatbot. Now, import the following test code, which will send a welcome message to the user when they enter the /start command: import asyncio # Library for handling asynchronous code import os # Module for working with environment variables from dotenv import load_dotenv # Function to load environment variables from the .env file from aiogram import Bot, Dispatcher, Router # Import necessary classes from aiogram from aiogram.types import Message # Import Message class for handling incoming messages from aiogram.filters import CommandStart # Import filter for handling the /start command # Create a router to store message handlers router = Router() # Load environment variables from .env load_dotenv() # Handler for the /start command @router.message(CommandStart()) # Filter to check if the message is the /start command async def cmd_start(message: Message) -> None: # Retrieve the user's first name and last name (if available) first_name = message.from_user.first_name last_name = message.from_user.last_name or "" # If no last name, use an empty string # Send a welcome message to the user await message.answer(f"Hello, {first_name} {last_name}!") # Main asynchronous function to start the bot async def main(): # Create a bot instance using the token from environment variables bot = Bot(token=os.getenv("BOT_TOKEN")) # Create a dispatcher to handle messages dp = Dispatcher() # Include the router with command handlers dp.include_router(router) # Start the bot in polling mode await dp.start_polling(bot) # If the script is run directly (not imported as a module), # execute the main() function if __name__ == "__main__": asyncio.run(main()) The script is well-commented to help you understand the essential parts.If you don't want to dive deep, you can simply use Dispatcher and Router as standard components in Aiogram. We will explore their functionality later in this guide. This ready-made structure can serve as a solid starting point for any chatbot project. As you continue development, you will add more handlers, keyboards, and states. Step 5: Run and Test the Chatbot Now, launch your script using the following command: python main.py Now you can open a chat with your bot in Telegram and start interacting with it. Aiogram Framework v3.x Features Overview  You only need to understand a few key components and functions of Aiogram to create a Telegram chatbot. This section covers Aiogram v3.x, which was released on September 1, 2023. Any version starting with 3.x will work. While older projects using Aiogram 2.x still exist, version 2.x is now considered outdated. Key Components of Aiogram Bot The Bot class serves as the interface to the Telegram API. It allows you to send messages, images, and other data to users. bot = Bot(token=os.getenv("TOKEN")) You can pass the token directly when initializing the Bot class, but it's recommended to use environment variables to prevent accidental exposure of your bot token. Dispatcher The Dispatcher is the core of the framework. It receives updates (incoming messages and events) and routes them to the appropriate handlers. dp = Dispatcher() In Aiogram v3, a new structure with Router is used (see below), but the Dispatcher is still required for initialization and launching the bot. Router In Aiogram v3, handlers are grouped within a Router. This is a separate entity that stores the bot's logic—command handlers, message handlers, callback handlers, and more. from aiogram import Router router = Router() After defining handlers inside the router, developers register it with the Dispatcher: dp.include_router(router) Handling Commands The most common scenario is responding to commands like /start or /help. from aiogram import F from aiogram.types import Message @router.message(F.text == "/start") async def cmd_start(message: Message): await message.answer("Hello! I'm a bot running on Aiogram.") F.text == "/start" is a new filtering method in Aiogram v3. message.answer(...) sends a reply to the user. Handling Regular Messages To react to any message, simply remove the filter or define a different condition: @router.message() async def echo_all(message: Message): await message.answer(f"You wrote: {message.text}") In this example, the bot echoes whatever text the user sends. Inline Buttons and Keyboards from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup inline_kb = InlineKeyboardMarkup( inline_keyboard=[ [InlineKeyboardButton(text="Click me!", callback_data="press_button")] ] ) @router.message(F.text == "/buttons") async def show_buttons(message: Message): await message.answer("Here are my buttons:", reply_markup=inline_kb) When the user clicks the button, the bot receives callback_data="press_button", which can be handled separately: from aiogram.types import CallbackQuery @router.callback_query(F.data == "press_button") async def handle_press_button(callback: CallbackQuery): await callback.message.answer("You clicked the button!") await callback.answer() # Removes the "loading" animation in the chat Regular Buttons (Reply Keyboard) Regular buttons differ from inline buttons in that they replace the keyboard. The user immediately sees a list of available response options. These buttons are tracked by the message text, not callback_data. from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove # Creating a reply keyboard reply_kb = ReplyKeyboardMarkup( keyboard=[ [ KeyboardButton(text="View Menu"), KeyboardButton(text="Place Order") ] ], resize_keyboard=True # Automatically adjusts button size ) # Handling the /start command and showing the reply keyboard @router.message(F.text == "/start") async def start_cmd(message: Message): await message.answer( "Welcome! Choose an action:", reply_markup=reply_kb ) # Handling "View Menu" button press @router.message(F.text == "View Menu") async def show_menu(message: Message): await message.answer("We have pizza and drinks.") # Handling "Place Order" button press @router.message(F.text == "Place Order") async def make_order(message: Message): await message.answer("What would you like to order?") # Command to hide the keyboard @router.message(F.text == "/hide") async def hide_keyboard(message: Message): await message.answer("Hiding the keyboard", reply_markup=ReplyKeyboardRemove()) Filters and Middlewares Filters Filters help define which messages should be processed. You can also create custom filters. from aiogram.filters import Filter # Custom filter to check if a user is an admin class IsAdmin(Filter): def __init__(self, admin_id: int): self.admin_id = admin_id async def __call__(self, message: Message) -> bool: return message.from_user.id == self.admin_id # Using the filter to restrict a command to the admin @router.message(IsAdmin(admin_id=12345678), F.text == "/admin") async def admin_cmd(message: Message): await message.answer("Hello, Admin! You have special privileges.") Middlewares Middlewares act as intermediary layers between an incoming request and its handler. You can use them to intercept, modify, validate, or log messages before they reach their respective handlers. import logging from aiogram.types import CallbackQuery, Message from aiogram.dispatcher.middlewares.base import BaseMiddleware # Custom middleware to log incoming messages and callbacks class LoggingMiddleware(BaseMiddleware): async def __call__(self, handler, event, data): if isinstance(event, Message): logging.info(f"[Message] from {event.from_user.id}: {event.text}") elif isinstance(event, CallbackQuery): logging.info(f"[CallbackQuery] from {event.from_user.id}: {event.data}") # Pass the event to the next handler return await handler(event, data) async def main(): load_dotenv() logging.basicConfig(level=logging.INFO) bot = Bot(token=os.getenv("BOT_TOKEN")) dp = Dispatcher() # Attaching the middleware dp.update.middleware(LoggingMiddleware()) dp.include_router(router) await dp.start_polling(bot) Working with States (FSM) in Aiogram 3 Aiogram 3 supports Finite State Machine (FSM), which is useful for step-by-step data collection (e.g., user registration, order processing). FSM is crucial for implementing multi-step workflows where users must complete one step before moving to the next. For example, in a pizza ordering bot, we need to ask the user for pizza size and delivery address, ensuring the process is sequential. We must save each step's data until the order is complete. Step 1: Declare States from aiogram.fsm.state import State, StatesGroup class OrderPizza(StatesGroup): waiting_for_size = State() waiting_for_address = State() These states define different stages in the ordering process. Step 2: Switch between states from aiogram.fsm.context import FSMContext @router.message(F.text == "/order") async def cmd_order(message: Message, state: FSMContext): # Create inline buttons for selecting pizza size size_keyboard = InlineKeyboardMarkup( inline_keyboard=[ [ InlineKeyboardButton(text="Large", callback_data="size_big"), InlineKeyboardButton(text="Medium", callback_data="size_medium"), InlineKeyboardButton(text="Small", callback_data="size_small") ] ] ) await message.answer( "What size pizza would you like? Click one of the buttons:", reply_markup=size_keyboard ) # Set the state to wait for the user to choose a size await state.set_state(OrderPizza.waiting_for_size) # Step 2: Handle button click for size selection @router.callback_query(OrderPizza.waiting_for_size, F.data.startswith("size_")) async def choose_size_callback(callback: CallbackQuery, state: FSMContext): # Callback data can be size_big / size_medium / size_small size_data = callback.data.split("_")[1] # e.g., "big", "medium", or "small" # Save the selected pizza size in the temporary state storage await state.update_data(pizza_size=size_data) # Confirm the button press (removes "loading clock" in Telegram's UI) await callback.answer() await callback.message.answer("Please enter your delivery address:") await state.set_state(OrderPizza.waiting_for_address) # Step 2a: If the user sends a message instead of clicking a button (in waiting_for_size state), # we can handle it separately. For example, prompt them to use the buttons. @router.message(OrderPizza.waiting_for_size) async def handle_text_during_waiting_for_size(message: Message, state: FSMContext): await message.answer( "Please select a pizza size using the buttons above. " "We cannot proceed without this information." ) # Step 3: User sends the delivery address @router.message(OrderPizza.waiting_for_address) async def set_address(message: Message, state: FSMContext): address = message.text user_data = await state.get_data() pizza_size = user_data["pizza_size"] size_text = { "big": "large", "medium": "medium", "small": "small" }.get(pizza_size, "undefined") await message.answer(f"You have ordered a {size_text} pizza to be delivered at: {address}") # Clear the state — the process is complete await state.clear() Notice how the temporary storage keeps track of user responses at each step. This storage is user-specific and does not require a database. The user progresses through a chain of questions, and at the end, the order details can be sent to an internal API.  Deploying the Bot: Running on a Server Let's go through two main deployment methods. Quick Method: Docker + Hostman App Platform This method does not require any system administration knowledge; the entire deployment process is automated. Additionally, it helps save costs. Follow these steps: Export all project dependencies to a requirements.txt file. Using a virtual environment is recommended to avoid pulling in libraries from the entire system. Run the following command in the project directory terminal: pip freeze > requirements.txt Add a deployment file to the project directory — Dockerfile. This file has no extension, just the name. Insert the following content: FROM python:3.11 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 9999 CMD ["python", "main.py"] Create a Git repository and push it to GitHub. You can use a minimal set of Git commands from our guide by running these commands in sequence. Add the environment variables file (.env) to .gitignore to prevent it from being exposed publicly. Go to the Hostman control panel, select the App platform section, and click Create app. Go to the Docker tab and select Dockerfile. Link your GitHub account or connect your Git repository via URL. Select the repository from the list after linking your GitHub account. Choose a configuration. Hostman Apps offers a configuration of 1 CPU x 3.3GHz, 1GB RAM, NVMe storage, which is ideal for simple text-based bots, projects with small inline keyboards, basic FSM logic, low-demand API requests, working with SQLite, or lightweight JSON files. This configuration can handle 50-100 users per minute. Add the bot token to environment variables. In the App settings, click + Add, enter BOT_TOKEN as the key, and paste the token obtained from BotFather as the value. Start the deployment and wait for it to complete. Once finished, the bot will be up and running. Standard Method: Ubuntu + systemd Export all project dependencies to the requirements.txt file. Run the following command in the Terminal while in the project directory: pip freeze > requirements.txt Create a cloud server in the Hostman panel with the desired configuration and Ubuntu OS. Transfer project files to the directory on the remote server. The easiest way to do this is using the rsync utility if you're using Ubuntu/MacOS: rsync -av --exclude="venv" --exclude=".idea" --exclude=".git" ./ root@176.53.160.13:/root/project Don’t forget to replace the server IP and correct the destination directory.  Windows users can use FileZilla to transfer files.  Connect to the server via SSH. Install the package for virtual environments: sudo apt install python3.10-venv Navigate to the project directory where you transferred the files. Create a virtual environment and install the dependencies: python -m venv venvsource venv/bin/activatepip install -r requirements.txt Test the bot functionality by running it: python main.py If everything works, proceed to the next step. Create the unit file /etc/systemd/system/telegram-bot.service: sudo nano /etc/systemd/system/telegram-bot.service Add the following content to the file: [Unit] Description=Telegram Bot Service After=network.target [Service] User=root WorkingDirectory=/root/project ExecStart=/root/proj/venv/bin/python /root/proj/main.py Restart=always RestartSec=5 [Install] WantedBy=multi-user.target WorkingDirectory — the project directory ExecStart — the command to start the chatbot in the format <interpreter> <full path to the file>. If using a virtual environment, the path to the interpreter will be as in the example. If working without venv, use /usr/local/bin/python3. Reload systemd and enable the service: sudo systemctl daemon-reloadsudo systemctl enable telegram-bot.servicesudo systemctl start telegram-bot.service Check the status of the service and view logs if necessary: sudo systemctl status telegram-bot.service If the bot is running correctly, the Active field should show active (running). View bot logs: sudo journalctl -u telegram-bot.service -f Manage the service with the following commands: Restart the bot: sudo systemctl restart telegram-bot.service Stop the bot: sudo systemctl stop telegram-bot.service Remove the service (if needed): sudo systemctl disable telegram-bot.servicesudo rm /etc/systemd/system/telegram-bot.servicesudo systemctl daemon-reload Conclusion Creating a Telegram chatbot in Python is a task that can be accomplished even without programming experience using bot builders. However, if you need flexibility and more options, it's better to master the aiogram framework and deploy your own project. This gives you full control over the code, the ability to enhance functionality, manage integrations, and avoid the limitations of paid plans. To run the bot in production, simply choose an appropriate configuration on the Hostman App Platform and set up automatic deployment. Pay attention to security by storing the token in an environment variable and encrypting sensitive data. In the future, you can scale the bot, add webhook support, integrate payment systems and analytics systems, and work with ML models if AI features are required.
12 March 2025 · 18 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support