tgdata 0.0.1__tar.gz → 0.0.3__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.3/PKG-INFO +384 -0
- tgdata-0.0.3/README.md +358 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/setup.py +27 -3
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/__init__.py +1 -1
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/connection_engine.py +71 -33
- tgdata-0.0.3/tgdata/message_engine.py +642 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/models.py +14 -2
- tgdata-0.0.3/tgdata/smoke_tests/test_username_support.py +96 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/tgdata.py +74 -21
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/utils.py +8 -5
- tgdata-0.0.3/tgdata.egg-info/PKG-INFO +384 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata.egg-info/SOURCES.txt +2 -1
- tgdata-0.0.3/tgdata.egg-info/requires.txt +2 -0
- tgdata-0.0.1/PKG-INFO +0 -260
- 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/PKG-INFO +0 -260
- tgdata-0.0.1/tgdata.egg-info/requires.txt +0 -2
- {tgdata-0.0.1 → tgdata-0.0.3}/setup.cfg +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/progress.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/__init__.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/my_test.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_00_connection.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_01_list_group_chats.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_02_get_message_count.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_03_get_all_messages.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_04_get_all_messages_in_batches.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_05_with_progress_feature.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_06_polling_simple.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_07_on_new_message_simple.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_07_real_time_event_handler.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_08_batch_callback.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_08_polling.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_10_advanced_features.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_debug_min_id.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata/smoke_tests/test_polling_debug.py +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata.egg-info/dependency_links.txt +0 -0
- {tgdata-0.0.1 → tgdata-0.0.3}/tgdata.egg-info/top_level.txt +0 -0
tgdata-0.0.3/PKG-INFO
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tgdata
|
|
3
|
+
Version: 0.0.3
|
|
4
|
+
Summary: A production-grade Python library for extracting and processing Telegram group and channel messages
|
|
5
|
+
Author: enes kuzucu
|
|
6
|
+
Classifier: Development Status :: 3 - Alpha
|
|
7
|
+
Classifier: Intended Audience :: Developers
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Requires-Python: >=3.7
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
Requires-Dist: Telethon<2.0,>=1.24
|
|
18
|
+
Requires-Dist: pandas>=1.0
|
|
19
|
+
Dynamic: author
|
|
20
|
+
Dynamic: classifier
|
|
21
|
+
Dynamic: description
|
|
22
|
+
Dynamic: description-content-type
|
|
23
|
+
Dynamic: requires-dist
|
|
24
|
+
Dynamic: requires-python
|
|
25
|
+
Dynamic: summary
|
|
26
|
+
|
|
27
|
+
# tgdata
|
|
28
|
+
|
|
29
|
+
A production-grade Python library for extracting and processing Telegram group and channel messages. Designed for ETL pipelines, data analysis, and archival purposes.
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
- 🚀 **Production-Ready**: Built for reliability and scale in ETL pipelines
|
|
34
|
+
- 🆔 **Flexible Identification**: Use numeric IDs or usernames (@channelname) for all operations
|
|
35
|
+
- 📊 **Efficient Data Extraction**: Fetch messages with automatic rate limit handling
|
|
36
|
+
- 🔄 **Incremental Updates**: Fetch only new messages with `after_id` parameter
|
|
37
|
+
- 📈 **Progress Tracking**: Monitor long-running operations with real-time progress
|
|
38
|
+
- 🔌 **Clean Architecture**: Focused on data extraction with minimal dependencies
|
|
39
|
+
- 🛡️ **Robust Error Handling**: Automatic retries with exponential backoff
|
|
40
|
+
- 📁 **Multiple Export Formats**: Export to CSV, JSON, or integrate with your data pipeline
|
|
41
|
+
- 🔔 **Real-time Updates**: Listen for new messages with event handlers
|
|
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
|
|
45
|
+
|
|
46
|
+
## Installation
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install tgdata
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
## Authentication
|
|
54
|
+
|
|
55
|
+
tgdata supports 1 authentication at the moment.
|
|
56
|
+
|
|
57
|
+
(2 other are being implemented)
|
|
58
|
+
|
|
59
|
+
1. get telegram development credentials in telegram API Development Tools from [https://my.telegram.org/apps](https://my.telegram.org/apps)
|
|
60
|
+
|
|
61
|
+
2. Create a `config.ini` file with your Telegram API credentials like this:
|
|
62
|
+
|
|
63
|
+
```ini
|
|
64
|
+
[Telegram]
|
|
65
|
+
|
|
66
|
+
# you can get telegram development credentials in telegram API Development Tools
|
|
67
|
+
api_id = 1234566
|
|
68
|
+
api_hash = a24adjfakjdfakjshdflkajsbdflk
|
|
69
|
+
phone = +905064004949 # use full phone number including + and country code
|
|
70
|
+
username = 'powerpuffdude'
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
## Quick Start
|
|
76
|
+
|
|
77
|
+
### List All Group Chats
|
|
78
|
+
|
|
79
|
+
This is required for finding chat id for the chat of interest.
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from tgdata import TgData
|
|
83
|
+
import asyncio
|
|
84
|
+
|
|
85
|
+
async def main():
|
|
86
|
+
# Initialize the client
|
|
87
|
+
tg = TgData("config.ini")
|
|
88
|
+
|
|
89
|
+
# List available groups and channels
|
|
90
|
+
groups = await tg.list_groups()
|
|
91
|
+
|
|
92
|
+
print(groups)
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Outputs:
|
|
97
|
+
|
|
98
|
+
```
|
|
99
|
+
Python Devs 10012312313
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
### Get all messages of a chat
|
|
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.
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from tgdata import TgData
|
|
112
|
+
import asyncio
|
|
113
|
+
|
|
114
|
+
async def main():
|
|
115
|
+
# Initialize the client
|
|
116
|
+
tg = TgData("config.ini")
|
|
117
|
+
|
|
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)
|
|
126
|
+
messages = await tg.get_messages(
|
|
127
|
+
group_id="@channelname", # Username with @
|
|
128
|
+
limit=1000,
|
|
129
|
+
with_progress=True
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# Export to CSV
|
|
133
|
+
tg.export_messages(messages, "messages.csv")
|
|
134
|
+
|
|
135
|
+
asyncio.run(main())
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### Get message count of a chat
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from tgdata import TgData
|
|
144
|
+
import asyncio
|
|
145
|
+
|
|
146
|
+
async def main():
|
|
147
|
+
# Initialize the client
|
|
148
|
+
tg = TgData("config.ini")
|
|
149
|
+
|
|
150
|
+
# Get count using numeric ID or username
|
|
151
|
+
message_count = await tg.get_message_count(
|
|
152
|
+
group_id=-1001234567890, # Numeric ID
|
|
153
|
+
# OR: group_id="@channelname" # Username
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
print(message_count)
|
|
157
|
+
|
|
158
|
+
asyncio.run(main())
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
## Advanced Usage
|
|
165
|
+
|
|
166
|
+
### Using Usernames vs Numeric IDs
|
|
167
|
+
|
|
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
|
+
```
|
|
183
|
+
|
|
184
|
+
### get_messages with start_date parameter
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
tg = TgData("config.ini")
|
|
188
|
+
# Fetch recent messages for ETL processing
|
|
189
|
+
yesterday = datetime.now() - timedelta(days=1)
|
|
190
|
+
messages = await tg.get_messages(
|
|
191
|
+
group_id="@channelname", # Can use username
|
|
192
|
+
start_date=yesterday,
|
|
193
|
+
with_progress=True
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
### Incremental Message Fetching
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
from tgdata import TgData
|
|
203
|
+
|
|
204
|
+
async def incremental_fetch():
|
|
205
|
+
tg = TgData("config.ini")
|
|
206
|
+
|
|
207
|
+
# Get the latest message ID from your storage, or db
|
|
208
|
+
last_processed_id = load_checkpoint() # Your implementation
|
|
209
|
+
|
|
210
|
+
# Fetch only messages after that ID
|
|
211
|
+
new_messages = await tg.get_messages(
|
|
212
|
+
group_id="@channelname", # Can use username or numeric ID
|
|
213
|
+
after_id=last_processed_id
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
save_checkpoint(new_messages['MessageId'].max()) # Your implementation
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
asyncio.run(incremental_fetch())
|
|
220
|
+
```
|
|
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
|
+
|
|
276
|
+
Downloaded files (modes A and B) are named `<ChatId>_<MessageId>.<ext>` — e.g.
|
|
277
|
+
`1707717812_183019.jpg` — so every file is traceable to its exact message and
|
|
278
|
+
group from the filename alone (and won't collide across groups sharing a folder).
|
|
279
|
+
The precise path is also recorded per row in the `MediaPath` column.
|
|
280
|
+
|
|
281
|
+
**Re-scraping is idempotent:** if a message's file is already on disk, it is
|
|
282
|
+
reused, not re-downloaded — so pulling the same (or an overlapping) range again
|
|
283
|
+
never duplicates files or re-fetches bytes. Each message maps to exactly one file.
|
|
284
|
+
|
|
285
|
+
### Progress Monitoring
|
|
286
|
+
|
|
287
|
+
```python
|
|
288
|
+
async def monitor_extraction():
|
|
289
|
+
tg = TgData()
|
|
290
|
+
|
|
291
|
+
def progress_callback(current, total, rate):
|
|
292
|
+
percent = (current / total * 100) if total else 0
|
|
293
|
+
print(f"Progress: {current}/{total} ({percent:.1f}%) - {rate:.1f} msg/s")
|
|
294
|
+
|
|
295
|
+
messages = await tg.get_messages(
|
|
296
|
+
group_id=-1001234567890,
|
|
297
|
+
limit=10000,
|
|
298
|
+
progress_callback=progress_callback
|
|
299
|
+
)
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
### Batch Processing for Large Groups
|
|
303
|
+
|
|
304
|
+
```python
|
|
305
|
+
# For groups with 100k+ messages, use batch processing with rate limit protection
|
|
306
|
+
async def process_large_group():
|
|
307
|
+
tg = TgData("config.ini")
|
|
308
|
+
|
|
309
|
+
async def save_batch(batch_df, batch_info):
|
|
310
|
+
# Process each batch (e.g., save to database)
|
|
311
|
+
print(f"Batch {batch_info['batch_num']}: {len(batch_df)} messages")
|
|
312
|
+
batch_df.to_csv(f"batch_{batch_info['batch_num']}.csv")
|
|
313
|
+
|
|
314
|
+
await tg.get_messages(
|
|
315
|
+
group_id="@largechannel", # Works with username
|
|
316
|
+
batch_size=500, # Process 500 messages at a time
|
|
317
|
+
batch_callback=save_batch,
|
|
318
|
+
batch_delay=2.0, # Wait 2 seconds between batches
|
|
319
|
+
rate_limit_strategy='exponential' # Handle rate limits gracefully
|
|
320
|
+
)
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
### Custom callback
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
### Polling for New Messages
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
async def poll_messages():
|
|
332
|
+
tg = TgData()
|
|
333
|
+
|
|
334
|
+
# Define callback for new messages
|
|
335
|
+
async def process_batch(messages_df):
|
|
336
|
+
print(f"Got {len(messages_df)} new messages")
|
|
337
|
+
# Process messages here
|
|
338
|
+
|
|
339
|
+
# Poll every 30 seconds
|
|
340
|
+
await tg.poll_for_messages(
|
|
341
|
+
group_id="@channelname", # Works with username
|
|
342
|
+
interval=30,
|
|
343
|
+
callback=process_batch,
|
|
344
|
+
max_iterations=10 # Stop after 10 polls
|
|
345
|
+
)
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
### Real-time Message Events
|
|
350
|
+
|
|
351
|
+
```python
|
|
352
|
+
# Monitor messages in real-time
|
|
353
|
+
tg = TgData("config.ini")
|
|
354
|
+
|
|
355
|
+
@tg.on_new_message(group_id="@channelname") # Works with username
|
|
356
|
+
async def handle_message(event):
|
|
357
|
+
print(f"New message: {event.message.text}")
|
|
358
|
+
|
|
359
|
+
await tg.run_with_event_loop()
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
### Performance Tips
|
|
364
|
+
|
|
365
|
+
- The client authenticates once and keeps a single **persistent connection**,
|
|
366
|
+
reused across all calls; release it with `await tg.close()` or use
|
|
367
|
+
`async with TgData("config.ini") as tg:`
|
|
368
|
+
- Implement checkpoint logic for incremental processing
|
|
369
|
+
- Implement progress callbacks for visibility
|
|
370
|
+
- Export data incrementally for large datasets
|
|
371
|
+
|
|
372
|
+
## Requirements
|
|
373
|
+
|
|
374
|
+
- Python 3.7+
|
|
375
|
+
- Telegram API credentials (not bot tokens)
|
|
376
|
+
- Group/channel membership
|
|
377
|
+
|
|
378
|
+
## License
|
|
379
|
+
|
|
380
|
+
MIT License - see LICENSE file for details
|
|
381
|
+
|
|
382
|
+
## Contributing
|
|
383
|
+
|
|
384
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|