Contents:

Placement course: "Python Developer"
Learn MoreToday we'll look at how to parse Telegram chats, exploring the necessary modules and settings for collecting messages. For this task, we'll use the Telethon library for Python. This tool allows you to effectively interact with the Telegram API, making it an ideal choice for extracting data from chats. We'll cover in detail how to install the library, set up a connection, and access messages from the chats we're interested in.
This is the second lesson on parsing in Telegram. In the first lesson, we developed a parser for obtaining a list of channel and chat participants and also mastered using the messenger's API developer tools. If you haven't yet read the first part, we highly recommend starting with it. In this lesson, we'll deepen our knowledge and explore new aspects of Telegram parsing, helping you effectively extract data and interact with various platform elements.
What do we have now?
In the first part of the lesson, we'll cover basic concepts and principles to help you better understand the topic. We'll discuss key aspects necessary for further study and answer frequently asked questions. We'll also provide examples and practical tasks to help reinforce your new knowledge. The focus will be on theory and its practical application, which will ensure a deep understanding of the material being studied.
- we set up Telegram API developer tools and learned how to use them to connect to the messenger client;
- we installed and imported the Telethon library, which allows us to work with the Telegram API, selecting the classes, functions, and types we need;
- we learned how to parse a list of groups and chats from a messenger;
- we wrote code to parse a list of users in a chat or messenger, saving them in an easy-to-read and subsequently analyze form.
Our main task is to parse messages from chats. We will save only text data without taking into account the sending time and information about the sender. This data can subsequently be used to analyze the correspondence, allowing us to identify the most frequently used words and determine popular discussion topics. This approach will help us better understand user interactions and improve the quality of communication in chats.
Adding New Imports
Open the code from the first part of the tutorial in the integrated development environment (IDE). We'll continue to use it instead of writing everything from scratch. To parse messages from chats, we need to import a new method and function at the beginning of the code. This will allow us to efficiently extract data from chats and optimize the information processing. Make sure all necessary libraries are loaded to avoid errors when running the code.
In this section, we present information about imported products. Our imported products include a wide range of items that meet a variety of consumer needs and preferences. We carefully select our products to ensure their high quality and compliance with modern standards. Our company strives to offer the best choice to our customers, ensuring access to unique and sought-after products. We continue to expand our product range to meet growing market demand.
- GetHistoryRequest is a method for retrieving user messages from a chat and working with them;
- PeerChannel is a special type that defines objects of the "channel/chat" type, which can be used to access the desired channel for message parsing.
Writing the message parser code
Let's start by creating an empty list for storing messages and initializing several variables that will be useful later.
The all_messages list is used to store parsed messages. The limit variable sets a limit on the number of messages that will be parsed in one cycle, while only 100 messages will be stored. This allows for efficient data volume management and optimizes the parsing process.
In addition to the main variables, our code uses two additional variables: total_messages and total_count_limit. The former counts the number of parsed messages, while the latter allows you to set a limit on the total number of received messages. In the example provided, total_count_limit is set to 0, meaning all messages will be processed. However, if the chat history is extensive, the parsing process may take a significant amount of time. In such cases, it is advisable to manually set a limit on the number of parsed messages, which will significantly speed up data processing.
offset_id is a key variable used in the GetHistoryRequest method to determine the starting point for message parsing. Initially, it is assigned a value of 0, which allows processing to begin from the very first message in the channel. If we set a value of, say, 100, the parser would skip the first 100 messages, which could negatively impact the completeness of the data. Proper use of offset_id allows you to effectively manage the parsing process and retrieve the necessary information without data loss.
In this section, we will implement the message parser code and analyze it in detail. The message parser performs an important function, allowing you to extract and process data from text messages. It can be used for various purposes, such as data analysis, keyword extraction, or automation of information processing. We will consider the main components of the parser, its structure, and operating algorithms. This will help you better understand how it functions and how it can be adapted to specific tasks.
Parsing is performed using a while loop. This loop continues as long as there are messages in the chat that have not yet been parsed, or until the specified limit on the number of collected messages is reached. This approach ensures efficient data extraction and allows you to control the information collection process, ensuring that all necessary messages are processed within the established limits.
To retrieve messages in Telegram, we use the standard Telethon library method, GetHistoryRequest. This method must be passed in our client's request to the Telegram API. The peer parameter is used to specify the group from which we want to retrieve messages. It is assigned the value of the target group that we defined at the beginning of the parser. In this case, it is the target_group variable. This approach ensures efficient and fast access to the message history in the selected group, which is an important aspect when developing applications for data analysis in Telegram.
The offset_date and offset_peer parameters are passed with empty values. They are typically used to filter the received data, but in this case, our goal is to retrieve the full list of messages. We set a limit on the number of elements in the response by setting the limit parameter to 100. Three mandatory parameters for executing the GetHistoryRequest request must also be taken into account: min_id, max_id, and hash. We pass these parameters with zero values, since they will not be used in this context. However, specifying these parameters is required, since omitting them will cause the method to fail.
The main loop functions as follows: it continuously executes the specified operations until a certain condition is reached or until execution needs to be interrupted. This process provides efficient task management, allowing you to process data and respond to events in real time. Using the main loop in programming allows you to optimize application performance and improve user experience.
- We check if there are any messages left to parse. If not, the loop ends. If there are messages, we save them in the messages list.
- We save each message from the message list to the all_messages list.
- If the number of received messages is greater than the number in the chat or we have reached the parsing limit, the loop ends.
GetHistoryRequest receives the offset_id parameter, which indicates which message to start loading the chat history from. Properly setting this offset is critical to ensuring the uniqueness of each received message. Therefore, for the next cycle, the offset_id value is set to an offset of one message. This avoids duplication and ensures that the entire chat history is loaded correctly and sequentially.
Saving received messages to a file
Received messages are saved in CSV format, similar to the user parsing process. This method provides convenient storage and subsequent data analysis. The CSV format allows for easy import of information into various data processing and visualization programs, making it ideal for working with large volumes of information. Saving messages in this format simplifies further work with them and promotes more efficient analysis of the received data.
Next, we move on to the process of saving the data to a CSV file using the standard csv module. To do this, we open the file in write mode, specifying the UTF-8 encoding. This will ensure the correct storage of the information and avoid problems with the display of characters. Saving data in CSV format is an important step for further processing and analysis of the information.
If the file doesn't exist in the directory, it will be created automatically. We then create a CSV writer object and write messages from the all_messages list to it. This allows you to effectively manage data and save information in CSV format for further analysis or use.
Run the parser and select the desired group from the list provided.

We've successfully completed the process. Our directory now contains two CSV files: members.csv and chats.csv. Let's open chats.csv for further analysis.

We observe that not only text messages but also technical data, such as message and request identifiers, have been preserved. This result doesn't meet our expectations. To fix this, we'll return to the while loop and add a message parameter to the message method. This change will allow us to store only the message text, excluding unnecessary technical information.
Let's rerun the code and analyze the results. This will allow us to evaluate the changes and ensure their effectiveness.

Now everything functions correctly. Only messages are left, without service information about requests.
The complete parser code for Telegram in Python
In this lesson on parsing information from Telegram, we developed a significant amount of code. Let's look at it in full.
What's next?
The Telethon library is designed not only for extracting data about users and messages in channels and chats, but also for automating various processes in Telegram. Channel administrators can use Telethon to develop bots that will send messages, share stickers, and manage member lists. These functions and capabilities are described in detail in the official library documentation, which makes it a useful tool for developers and administrators.
Read also:
- Parsing data in Telegram in Python. Part 1. Choosing a library and studying subscribers
- Test: guess where esoteric programming languages are and where they are not
- Python for beginners: areas of application and capabilities

