tgdata 0.0.1__tar.gz → 0.0.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {tgdata-0.0.1 → tgdata-0.0.2}/PKG-INFO +133 -18
- tgdata-0.0.2/README.md +349 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/setup.py +27 -3
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/__init__.py +1 -1
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/connection_engine.py +71 -33
- tgdata-0.0.2/tgdata/message_engine.py +605 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/models.py +14 -2
- tgdata-0.0.2/tgdata/smoke_tests/test_username_support.py +96 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/tgdata.py +74 -21
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/utils.py +8 -5
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata.egg-info/PKG-INFO +133 -18
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata.egg-info/SOURCES.txt +2 -1
- tgdata-0.0.2/tgdata.egg-info/requires.txt +2 -0
- tgdata-0.0.1/README.md +0 -234
- tgdata-0.0.1/tgdata/message_engine.py +0 -332
- tgdata-0.0.1/tgdata.egg-info/requires.txt +0 -2
- {tgdata-0.0.1 → tgdata-0.0.2}/setup.cfg +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/progress.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/__init__.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/my_test.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_00_connection.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_01_list_group_chats.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_02_get_message_count.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_03_get_all_messages.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_04_get_all_messages_in_batches.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_05_with_progress_feature.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_06_polling_simple.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_07_on_new_message_simple.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_07_real_time_event_handler.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_08_batch_callback.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_08_polling.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_10_advanced_features.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_debug_min_id.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata/smoke_tests/test_polling_debug.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata.egg-info/dependency_links.txt +0 -0
- {tgdata-0.0.1 → tgdata-0.0.2}/tgdata.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: tgdata
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.2
|
|
4
4
|
Summary: A production-grade Python library for extracting and processing Telegram group and channel messages
|
|
5
5
|
Author: enes kuzucu
|
|
6
6
|
Classifier: Development Status :: 3 - Alpha
|
|
@@ -14,8 +14,8 @@ Classifier: Programming Language :: Python :: 3.10
|
|
|
14
14
|
Classifier: Operating System :: OS Independent
|
|
15
15
|
Requires-Python: >=3.7
|
|
16
16
|
Description-Content-Type: text/markdown
|
|
17
|
-
Requires-Dist: Telethon
|
|
18
|
-
Requires-Dist: pandas
|
|
17
|
+
Requires-Dist: Telethon<2.0,>=1.24
|
|
18
|
+
Requires-Dist: pandas>=1.0
|
|
19
19
|
Dynamic: author
|
|
20
20
|
Dynamic: classifier
|
|
21
21
|
Dynamic: description
|
|
@@ -31,7 +31,8 @@ A production-grade Python library for extracting and processing Telegram group a
|
|
|
31
31
|
## Features
|
|
32
32
|
|
|
33
33
|
- 🚀 **Production-Ready**: Built for reliability and scale in ETL pipelines
|
|
34
|
-
-
|
|
34
|
+
- 🆔 **Flexible Identification**: Use numeric IDs or usernames (@channelname) for all operations
|
|
35
|
+
- 📊 **Efficient Data Extraction**: Fetch messages with automatic rate limit handling
|
|
35
36
|
- 🔄 **Incremental Updates**: Fetch only new messages with `after_id` parameter
|
|
36
37
|
- 📈 **Progress Tracking**: Monitor long-running operations with real-time progress
|
|
37
38
|
- 🔌 **Clean Architecture**: Focused on data extraction with minimal dependencies
|
|
@@ -39,6 +40,8 @@ A production-grade Python library for extracting and processing Telegram group a
|
|
|
39
40
|
- 📁 **Multiple Export Formats**: Export to CSV, JSON, or integrate with your data pipeline
|
|
40
41
|
- 🔔 **Real-time Updates**: Listen for new messages with event handlers
|
|
41
42
|
- ⏱️ **Polling Support**: Poll for new messages at configurable intervals
|
|
43
|
+
- 🎯 **Batch Processing**: Handle large groups with configurable batch sizes and delays
|
|
44
|
+
- 🖼️ **Media Detection & Download**: Flag photos/videos per message (no download needed) and pull the files on demand or during the fetch
|
|
42
45
|
|
|
43
46
|
## Installation
|
|
44
47
|
|
|
@@ -99,9 +102,9 @@ Python Devs 10012312313
|
|
|
99
102
|
|
|
100
103
|
### Get all messages of a chat
|
|
101
104
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
+
You can use either the numeric chat ID or the username (if the chat has one).
|
|
106
|
+
|
|
107
|
+
**Note:** For large groups (2500+ messages), use batch processing with rate limit protection.
|
|
105
108
|
|
|
106
109
|
|
|
107
110
|
```python
|
|
@@ -112,9 +115,16 @@ async def main():
|
|
|
112
115
|
# Initialize the client
|
|
113
116
|
tg = TgData("config.ini")
|
|
114
117
|
|
|
115
|
-
# Fetch messages
|
|
118
|
+
# Fetch messages using numeric ID
|
|
119
|
+
messages = await tg.get_messages(
|
|
120
|
+
group_id=-1001234567890, # Numeric ID
|
|
121
|
+
limit=1000,
|
|
122
|
+
with_progress=True
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# OR using username (if the chat has one)
|
|
116
126
|
messages = await tg.get_messages(
|
|
117
|
-
group_id
|
|
127
|
+
group_id="@channelname", # Username with @
|
|
118
128
|
limit=1000,
|
|
119
129
|
with_progress=True
|
|
120
130
|
)
|
|
@@ -137,10 +147,10 @@ async def main():
|
|
|
137
147
|
# Initialize the client
|
|
138
148
|
tg = TgData("config.ini")
|
|
139
149
|
|
|
140
|
-
#
|
|
150
|
+
# Get count using numeric ID or username
|
|
141
151
|
message_count = await tg.get_message_count(
|
|
142
|
-
group_id=-1001234567890, #
|
|
143
|
-
|
|
152
|
+
group_id=-1001234567890, # Numeric ID
|
|
153
|
+
# OR: group_id="@channelname" # Username
|
|
144
154
|
)
|
|
145
155
|
|
|
146
156
|
print(message_count)
|
|
@@ -153,15 +163,32 @@ asyncio.run(main())
|
|
|
153
163
|
|
|
154
164
|
## Advanced Usage
|
|
155
165
|
|
|
156
|
-
###
|
|
166
|
+
### Using Usernames vs Numeric IDs
|
|
157
167
|
|
|
158
168
|
```python
|
|
169
|
+
# Both approaches work identically:
|
|
170
|
+
|
|
171
|
+
# Option 1: Using username (recommended if available)
|
|
172
|
+
messages = await tg.get_messages(
|
|
173
|
+
group_id="@channelname",
|
|
174
|
+
limit=100
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
# Option 2: Using numeric ID
|
|
178
|
+
messages = await tg.get_messages(
|
|
179
|
+
group_id=-1001234567890,
|
|
180
|
+
limit=100
|
|
181
|
+
)
|
|
182
|
+
```
|
|
159
183
|
|
|
184
|
+
### get_messages with start_date parameter
|
|
185
|
+
|
|
186
|
+
```python
|
|
160
187
|
tg = TgData("config.ini")
|
|
161
188
|
# Fetch recent messages for ETL processing
|
|
162
189
|
yesterday = datetime.now() - timedelta(days=1)
|
|
163
190
|
messages = await tg.get_messages(
|
|
164
|
-
group_id
|
|
191
|
+
group_id="@channelname", # Can use username
|
|
165
192
|
start_date=yesterday,
|
|
166
193
|
with_progress=True
|
|
167
194
|
)
|
|
@@ -182,7 +209,7 @@ async def incremental_fetch():
|
|
|
182
209
|
|
|
183
210
|
# Fetch only messages after that ID
|
|
184
211
|
new_messages = await tg.get_messages(
|
|
185
|
-
group_id
|
|
212
|
+
group_id="@channelname", # Can use username or numeric ID
|
|
186
213
|
after_id=last_processed_id
|
|
187
214
|
)
|
|
188
215
|
|
|
@@ -192,6 +219,60 @@ async def incremental_fetch():
|
|
|
192
219
|
asyncio.run(incremental_fetch())
|
|
193
220
|
```
|
|
194
221
|
|
|
222
|
+
### Detecting & Downloading Media (photos / videos)
|
|
223
|
+
|
|
224
|
+
Every fetched message carries media-reference columns, so you can tell whether a
|
|
225
|
+
message has a photo **without downloading anything**:
|
|
226
|
+
|
|
227
|
+
| Column | Meaning |
|
|
228
|
+
|---|---|
|
|
229
|
+
| `MediaType` | `'photo'`, `'video'`, `'document'`, `'webpage'`, … or `None` (text-only) |
|
|
230
|
+
| `GroupedId` | album tag — rows sharing the same value are one multi-photo post (else `None`) |
|
|
231
|
+
| `MessageLink` | `t.me` deep link to the original message |
|
|
232
|
+
| `MediaPath` | local file path once media is downloaded (else `None`) |
|
|
233
|
+
|
|
234
|
+
> ⚠️ **`'webpage'` is NOT a real photo.** It is a link-preview thumbnail, not an
|
|
235
|
+
> attached image. Filter on the actual attachment type (`'photo'` / `'video'`) —
|
|
236
|
+
> **never** on "`MediaType` is not null" — or you will count URL previews as media.
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
messages = await tg.get_messages(group_id="@channelname", limit=100)
|
|
240
|
+
|
|
241
|
+
# ✅ correct — real attached photos only
|
|
242
|
+
photos = messages[messages['MediaType'] == 'photo']
|
|
243
|
+
|
|
244
|
+
# ❌ wrong — also catches 'webpage' link previews, which are NOT real images
|
|
245
|
+
# media = messages[messages['MediaType'].notna()]
|
|
246
|
+
|
|
247
|
+
# how many photos each album/listing has
|
|
248
|
+
photos.groupby('GroupedId').size()
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
Get the actual media in one of three ways:
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
# A) On demand — fetch references cheaply, then download only what you keep.
|
|
255
|
+
# Pass every MessageId sharing a GroupedId to grab a whole album.
|
|
256
|
+
paths = await tg.download_media_by_id("@channelname", [12345, 12346], output_dir="media")
|
|
257
|
+
# -> {12345: "media/photo_....jpg", 12346: None} (None = nothing downloadable, e.g. a webpage)
|
|
258
|
+
|
|
259
|
+
# B) During the fetch, to disk — one call returns the data AND writes the files.
|
|
260
|
+
messages = await tg.get_messages(
|
|
261
|
+
group_id="@channelname",
|
|
262
|
+
limit=100,
|
|
263
|
+
download_media_to="media", # each file's path is recorded in the MediaPath column
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
# C) During the fetch, in memory — bytes land in the DataFrame itself (MediaData column).
|
|
267
|
+
# Great for small scrapes; holds every file in RAM, so scope it.
|
|
268
|
+
messages = await tg.get_messages(
|
|
269
|
+
group_id="@channelname",
|
|
270
|
+
limit=100,
|
|
271
|
+
include_media=True, # MediaData = raw bytes per row (None for text/webpage)
|
|
272
|
+
)
|
|
273
|
+
# Note: CSV export drops MediaData; JSON stores a "[Binary data]" placeholder.
|
|
274
|
+
```
|
|
275
|
+
|
|
195
276
|
### Progress Monitoring
|
|
196
277
|
|
|
197
278
|
```python
|
|
@@ -209,6 +290,27 @@ async def monitor_extraction():
|
|
|
209
290
|
)
|
|
210
291
|
```
|
|
211
292
|
|
|
293
|
+
### Batch Processing for Large Groups
|
|
294
|
+
|
|
295
|
+
```python
|
|
296
|
+
# For groups with 100k+ messages, use batch processing with rate limit protection
|
|
297
|
+
async def process_large_group():
|
|
298
|
+
tg = TgData("config.ini")
|
|
299
|
+
|
|
300
|
+
async def save_batch(batch_df, batch_info):
|
|
301
|
+
# Process each batch (e.g., save to database)
|
|
302
|
+
print(f"Batch {batch_info['batch_num']}: {len(batch_df)} messages")
|
|
303
|
+
batch_df.to_csv(f"batch_{batch_info['batch_num']}.csv")
|
|
304
|
+
|
|
305
|
+
await tg.get_messages(
|
|
306
|
+
group_id="@largechannel", # Works with username
|
|
307
|
+
batch_size=500, # Process 500 messages at a time
|
|
308
|
+
batch_callback=save_batch,
|
|
309
|
+
batch_delay=2.0, # Wait 2 seconds between batches
|
|
310
|
+
rate_limit_strategy='exponential' # Handle rate limits gracefully
|
|
311
|
+
)
|
|
312
|
+
```
|
|
313
|
+
|
|
212
314
|
### Custom callback
|
|
213
315
|
|
|
214
316
|
|
|
@@ -227,7 +329,7 @@ async def poll_messages():
|
|
|
227
329
|
|
|
228
330
|
# Poll every 30 seconds
|
|
229
331
|
await tg.poll_for_messages(
|
|
230
|
-
group_id
|
|
332
|
+
group_id="@channelname", # Works with username
|
|
231
333
|
interval=30,
|
|
232
334
|
callback=process_batch,
|
|
233
335
|
max_iterations=10 # Stop after 10 polls
|
|
@@ -235,12 +337,25 @@ async def poll_messages():
|
|
|
235
337
|
```
|
|
236
338
|
|
|
237
339
|
|
|
238
|
-
###
|
|
340
|
+
### Real-time Message Events
|
|
341
|
+
|
|
342
|
+
```python
|
|
343
|
+
# Monitor messages in real-time
|
|
344
|
+
tg = TgData("config.ini")
|
|
345
|
+
|
|
346
|
+
@tg.on_new_message(group_id="@channelname") # Works with username
|
|
347
|
+
async def handle_message(event):
|
|
348
|
+
print(f"New message: {event.message.text}")
|
|
349
|
+
|
|
350
|
+
await tg.run_with_event_loop()
|
|
351
|
+
```
|
|
239
352
|
|
|
240
353
|
|
|
241
354
|
### Performance Tips
|
|
242
355
|
|
|
243
|
-
-
|
|
356
|
+
- The client authenticates once and keeps a single **persistent connection**,
|
|
357
|
+
reused across all calls; release it with `await tg.close()` or use
|
|
358
|
+
`async with TgData("config.ini") as tg:`
|
|
244
359
|
- Implement checkpoint logic for incremental processing
|
|
245
360
|
- Implement progress callbacks for visibility
|
|
246
361
|
- Export data incrementally for large datasets
|
tgdata-0.0.2/README.md
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
# tgdata
|
|
2
|
+
|
|
3
|
+
A production-grade Python library for extracting and processing Telegram group and channel messages. Designed for ETL pipelines, data analysis, and archival purposes.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🚀 **Production-Ready**: Built for reliability and scale in ETL pipelines
|
|
8
|
+
- 🆔 **Flexible Identification**: Use numeric IDs or usernames (@channelname) for all operations
|
|
9
|
+
- 📊 **Efficient Data Extraction**: Fetch messages with automatic rate limit handling
|
|
10
|
+
- 🔄 **Incremental Updates**: Fetch only new messages with `after_id` parameter
|
|
11
|
+
- 📈 **Progress Tracking**: Monitor long-running operations with real-time progress
|
|
12
|
+
- 🔌 **Clean Architecture**: Focused on data extraction with minimal dependencies
|
|
13
|
+
- 🛡️ **Robust Error Handling**: Automatic retries with exponential backoff
|
|
14
|
+
- 📁 **Multiple Export Formats**: Export to CSV, JSON, or integrate with your data pipeline
|
|
15
|
+
- 🔔 **Real-time Updates**: Listen for new messages with event handlers
|
|
16
|
+
- ⏱️ **Polling Support**: Poll for new messages at configurable intervals
|
|
17
|
+
- 🎯 **Batch Processing**: Handle large groups with configurable batch sizes and delays
|
|
18
|
+
- 🖼️ **Media Detection & Download**: Flag photos/videos per message (no download needed) and pull the files on demand or during the fetch
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install tgdata
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
## Authentication
|
|
28
|
+
|
|
29
|
+
tgdata supports 1 authentication at the moment.
|
|
30
|
+
|
|
31
|
+
(2 other are being implemented)
|
|
32
|
+
|
|
33
|
+
1. get telegram development credentials in telegram API Development Tools from [https://my.telegram.org/apps](https://my.telegram.org/apps)
|
|
34
|
+
|
|
35
|
+
2. Create a `config.ini` file with your Telegram API credentials like this:
|
|
36
|
+
|
|
37
|
+
```ini
|
|
38
|
+
[Telegram]
|
|
39
|
+
|
|
40
|
+
# you can get telegram development credentials in telegram API Development Tools
|
|
41
|
+
api_id = 1234566
|
|
42
|
+
api_hash = a24adjfakjdfakjshdflkajsbdflk
|
|
43
|
+
phone = +905064004949 # use full phone number including + and country code
|
|
44
|
+
username = 'powerpuffdude'
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
### List All Group Chats
|
|
52
|
+
|
|
53
|
+
This is required for finding chat id for the chat of interest.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from tgdata import TgData
|
|
57
|
+
import asyncio
|
|
58
|
+
|
|
59
|
+
async def main():
|
|
60
|
+
# Initialize the client
|
|
61
|
+
tg = TgData("config.ini")
|
|
62
|
+
|
|
63
|
+
# List available groups and channels
|
|
64
|
+
groups = await tg.list_groups()
|
|
65
|
+
|
|
66
|
+
print(groups)
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Outputs:
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
Python Devs 10012312313
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
### Get all messages of a chat
|
|
78
|
+
|
|
79
|
+
You can use either the numeric chat ID or the username (if the chat has one).
|
|
80
|
+
|
|
81
|
+
**Note:** For large groups (2500+ messages), use batch processing with rate limit protection.
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from tgdata import TgData
|
|
86
|
+
import asyncio
|
|
87
|
+
|
|
88
|
+
async def main():
|
|
89
|
+
# Initialize the client
|
|
90
|
+
tg = TgData("config.ini")
|
|
91
|
+
|
|
92
|
+
# Fetch messages using numeric ID
|
|
93
|
+
messages = await tg.get_messages(
|
|
94
|
+
group_id=-1001234567890, # Numeric ID
|
|
95
|
+
limit=1000,
|
|
96
|
+
with_progress=True
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
# OR using username (if the chat has one)
|
|
100
|
+
messages = await tg.get_messages(
|
|
101
|
+
group_id="@channelname", # Username with @
|
|
102
|
+
limit=1000,
|
|
103
|
+
with_progress=True
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
# Export to CSV
|
|
107
|
+
tg.export_messages(messages, "messages.csv")
|
|
108
|
+
|
|
109
|
+
asyncio.run(main())
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
### Get message count of a chat
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
```python
|
|
117
|
+
from tgdata import TgData
|
|
118
|
+
import asyncio
|
|
119
|
+
|
|
120
|
+
async def main():
|
|
121
|
+
# Initialize the client
|
|
122
|
+
tg = TgData("config.ini")
|
|
123
|
+
|
|
124
|
+
# Get count using numeric ID or username
|
|
125
|
+
message_count = await tg.get_message_count(
|
|
126
|
+
group_id=-1001234567890, # Numeric ID
|
|
127
|
+
# OR: group_id="@channelname" # Username
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
print(message_count)
|
|
131
|
+
|
|
132
|
+
asyncio.run(main())
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
## Advanced Usage
|
|
139
|
+
|
|
140
|
+
### Using Usernames vs Numeric IDs
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
# Both approaches work identically:
|
|
144
|
+
|
|
145
|
+
# Option 1: Using username (recommended if available)
|
|
146
|
+
messages = await tg.get_messages(
|
|
147
|
+
group_id="@channelname",
|
|
148
|
+
limit=100
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
# Option 2: Using numeric ID
|
|
152
|
+
messages = await tg.get_messages(
|
|
153
|
+
group_id=-1001234567890,
|
|
154
|
+
limit=100
|
|
155
|
+
)
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### get_messages with start_date parameter
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
tg = TgData("config.ini")
|
|
162
|
+
# Fetch recent messages for ETL processing
|
|
163
|
+
yesterday = datetime.now() - timedelta(days=1)
|
|
164
|
+
messages = await tg.get_messages(
|
|
165
|
+
group_id="@channelname", # Can use username
|
|
166
|
+
start_date=yesterday,
|
|
167
|
+
with_progress=True
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### Incremental Message Fetching
|
|
174
|
+
|
|
175
|
+
```python
|
|
176
|
+
from tgdata import TgData
|
|
177
|
+
|
|
178
|
+
async def incremental_fetch():
|
|
179
|
+
tg = TgData("config.ini")
|
|
180
|
+
|
|
181
|
+
# Get the latest message ID from your storage, or db
|
|
182
|
+
last_processed_id = load_checkpoint() # Your implementation
|
|
183
|
+
|
|
184
|
+
# Fetch only messages after that ID
|
|
185
|
+
new_messages = await tg.get_messages(
|
|
186
|
+
group_id="@channelname", # Can use username or numeric ID
|
|
187
|
+
after_id=last_processed_id
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
save_checkpoint(new_messages['MessageId'].max()) # Your implementation
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
asyncio.run(incremental_fetch())
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### Detecting & Downloading Media (photos / videos)
|
|
197
|
+
|
|
198
|
+
Every fetched message carries media-reference columns, so you can tell whether a
|
|
199
|
+
message has a photo **without downloading anything**:
|
|
200
|
+
|
|
201
|
+
| Column | Meaning |
|
|
202
|
+
|---|---|
|
|
203
|
+
| `MediaType` | `'photo'`, `'video'`, `'document'`, `'webpage'`, … or `None` (text-only) |
|
|
204
|
+
| `GroupedId` | album tag — rows sharing the same value are one multi-photo post (else `None`) |
|
|
205
|
+
| `MessageLink` | `t.me` deep link to the original message |
|
|
206
|
+
| `MediaPath` | local file path once media is downloaded (else `None`) |
|
|
207
|
+
|
|
208
|
+
> ⚠️ **`'webpage'` is NOT a real photo.** It is a link-preview thumbnail, not an
|
|
209
|
+
> attached image. Filter on the actual attachment type (`'photo'` / `'video'`) —
|
|
210
|
+
> **never** on "`MediaType` is not null" — or you will count URL previews as media.
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
messages = await tg.get_messages(group_id="@channelname", limit=100)
|
|
214
|
+
|
|
215
|
+
# ✅ correct — real attached photos only
|
|
216
|
+
photos = messages[messages['MediaType'] == 'photo']
|
|
217
|
+
|
|
218
|
+
# ❌ wrong — also catches 'webpage' link previews, which are NOT real images
|
|
219
|
+
# media = messages[messages['MediaType'].notna()]
|
|
220
|
+
|
|
221
|
+
# how many photos each album/listing has
|
|
222
|
+
photos.groupby('GroupedId').size()
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Get the actual media in one of three ways:
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
# A) On demand — fetch references cheaply, then download only what you keep.
|
|
229
|
+
# Pass every MessageId sharing a GroupedId to grab a whole album.
|
|
230
|
+
paths = await tg.download_media_by_id("@channelname", [12345, 12346], output_dir="media")
|
|
231
|
+
# -> {12345: "media/photo_....jpg", 12346: None} (None = nothing downloadable, e.g. a webpage)
|
|
232
|
+
|
|
233
|
+
# B) During the fetch, to disk — one call returns the data AND writes the files.
|
|
234
|
+
messages = await tg.get_messages(
|
|
235
|
+
group_id="@channelname",
|
|
236
|
+
limit=100,
|
|
237
|
+
download_media_to="media", # each file's path is recorded in the MediaPath column
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
# C) During the fetch, in memory — bytes land in the DataFrame itself (MediaData column).
|
|
241
|
+
# Great for small scrapes; holds every file in RAM, so scope it.
|
|
242
|
+
messages = await tg.get_messages(
|
|
243
|
+
group_id="@channelname",
|
|
244
|
+
limit=100,
|
|
245
|
+
include_media=True, # MediaData = raw bytes per row (None for text/webpage)
|
|
246
|
+
)
|
|
247
|
+
# Note: CSV export drops MediaData; JSON stores a "[Binary data]" placeholder.
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### Progress Monitoring
|
|
251
|
+
|
|
252
|
+
```python
|
|
253
|
+
async def monitor_extraction():
|
|
254
|
+
tg = TgData()
|
|
255
|
+
|
|
256
|
+
def progress_callback(current, total, rate):
|
|
257
|
+
percent = (current / total * 100) if total else 0
|
|
258
|
+
print(f"Progress: {current}/{total} ({percent:.1f}%) - {rate:.1f} msg/s")
|
|
259
|
+
|
|
260
|
+
messages = await tg.get_messages(
|
|
261
|
+
group_id=-1001234567890,
|
|
262
|
+
limit=10000,
|
|
263
|
+
progress_callback=progress_callback
|
|
264
|
+
)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### Batch Processing for Large Groups
|
|
268
|
+
|
|
269
|
+
```python
|
|
270
|
+
# For groups with 100k+ messages, use batch processing with rate limit protection
|
|
271
|
+
async def process_large_group():
|
|
272
|
+
tg = TgData("config.ini")
|
|
273
|
+
|
|
274
|
+
async def save_batch(batch_df, batch_info):
|
|
275
|
+
# Process each batch (e.g., save to database)
|
|
276
|
+
print(f"Batch {batch_info['batch_num']}: {len(batch_df)} messages")
|
|
277
|
+
batch_df.to_csv(f"batch_{batch_info['batch_num']}.csv")
|
|
278
|
+
|
|
279
|
+
await tg.get_messages(
|
|
280
|
+
group_id="@largechannel", # Works with username
|
|
281
|
+
batch_size=500, # Process 500 messages at a time
|
|
282
|
+
batch_callback=save_batch,
|
|
283
|
+
batch_delay=2.0, # Wait 2 seconds between batches
|
|
284
|
+
rate_limit_strategy='exponential' # Handle rate limits gracefully
|
|
285
|
+
)
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### Custom callback
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
### Polling for New Messages
|
|
294
|
+
|
|
295
|
+
```python
|
|
296
|
+
async def poll_messages():
|
|
297
|
+
tg = TgData()
|
|
298
|
+
|
|
299
|
+
# Define callback for new messages
|
|
300
|
+
async def process_batch(messages_df):
|
|
301
|
+
print(f"Got {len(messages_df)} new messages")
|
|
302
|
+
# Process messages here
|
|
303
|
+
|
|
304
|
+
# Poll every 30 seconds
|
|
305
|
+
await tg.poll_for_messages(
|
|
306
|
+
group_id="@channelname", # Works with username
|
|
307
|
+
interval=30,
|
|
308
|
+
callback=process_batch,
|
|
309
|
+
max_iterations=10 # Stop after 10 polls
|
|
310
|
+
)
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
### Real-time Message Events
|
|
315
|
+
|
|
316
|
+
```python
|
|
317
|
+
# Monitor messages in real-time
|
|
318
|
+
tg = TgData("config.ini")
|
|
319
|
+
|
|
320
|
+
@tg.on_new_message(group_id="@channelname") # Works with username
|
|
321
|
+
async def handle_message(event):
|
|
322
|
+
print(f"New message: {event.message.text}")
|
|
323
|
+
|
|
324
|
+
await tg.run_with_event_loop()
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
### Performance Tips
|
|
329
|
+
|
|
330
|
+
- The client authenticates once and keeps a single **persistent connection**,
|
|
331
|
+
reused across all calls; release it with `await tg.close()` or use
|
|
332
|
+
`async with TgData("config.ini") as tg:`
|
|
333
|
+
- Implement checkpoint logic for incremental processing
|
|
334
|
+
- Implement progress callbacks for visibility
|
|
335
|
+
- Export data incrementally for large datasets
|
|
336
|
+
|
|
337
|
+
## Requirements
|
|
338
|
+
|
|
339
|
+
- Python 3.7+
|
|
340
|
+
- Telegram API credentials (not bot tokens)
|
|
341
|
+
- Group/channel membership
|
|
342
|
+
|
|
343
|
+
## License
|
|
344
|
+
|
|
345
|
+
MIT License - see LICENSE file for details
|
|
346
|
+
|
|
347
|
+
## Contributing
|
|
348
|
+
|
|
349
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
@@ -1,8 +1,28 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
1
4
|
from setuptools import setup, find_packages
|
|
2
5
|
|
|
6
|
+
|
|
7
|
+
def read_version():
|
|
8
|
+
"""Single source of truth: parse __version__ from tgdata/__init__.py.
|
|
9
|
+
|
|
10
|
+
Parsed (not imported) so it works before dependencies are installed.
|
|
11
|
+
"""
|
|
12
|
+
init_py = Path(__file__).parent / 'tgdata' / '__init__.py'
|
|
13
|
+
match = re.search(
|
|
14
|
+
r'^__version__\s*=\s*["\']([^"\']+)["\']',
|
|
15
|
+
init_py.read_text(encoding='utf-8'),
|
|
16
|
+
re.MULTILINE,
|
|
17
|
+
)
|
|
18
|
+
if not match:
|
|
19
|
+
raise RuntimeError('Unable to find __version__ in tgdata/__init__.py')
|
|
20
|
+
return match.group(1)
|
|
21
|
+
|
|
22
|
+
|
|
3
23
|
setup(
|
|
4
24
|
name='tgdata', # Package name
|
|
5
|
-
version=
|
|
25
|
+
version=read_version(), # Single source of truth: tgdata/__init__.py
|
|
6
26
|
author='enes kuzucu', # Your name
|
|
7
27
|
|
|
8
28
|
description='A production-grade Python library for extracting and processing Telegram group and channel messages',
|
|
@@ -11,8 +31,12 @@ setup(
|
|
|
11
31
|
|
|
12
32
|
packages=find_packages(), # Automatically find packages in the directory
|
|
13
33
|
install_requires=[
|
|
14
|
-
|
|
15
|
-
|
|
34
|
+
# min_id is exclusive in Telethon 1.x (the off-by-one fix relies on it);
|
|
35
|
+
# 2.0 is a breaking API rewrite, so cap below it. Verified on 1.40.
|
|
36
|
+
'Telethon>=1.24,<2.0',
|
|
37
|
+
# Required, not optional: everything returns DataFrames. Nullable Int64
|
|
38
|
+
# (used for GroupedId album ids > 2^53) needs pandas >= 1.0.
|
|
39
|
+
'pandas>=1.0',
|
|
16
40
|
],
|
|
17
41
|
|
|
18
42
|
classifiers=[
|