telegather 0.1.1__py3-none-any.whl
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.
- telegather/__init__.py +0 -0
- telegather/cli.py +66 -0
- telegather/scraper.py +103 -0
- telegather-0.1.1.dist-info/METADATA +15 -0
- telegather-0.1.1.dist-info/RECORD +9 -0
- telegather-0.1.1.dist-info/WHEEL +5 -0
- telegather-0.1.1.dist-info/entry_points.txt +2 -0
- telegather-0.1.1.dist-info/licenses/LICENSE +21 -0
- telegather-0.1.1.dist-info/top_level.txt +1 -0
telegather/__init__.py
ADDED
|
File without changes
|
telegather/cli.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import argparse
|
|
3
|
+
from colorama import Fore, Style, init as colorama_init
|
|
4
|
+
from telegather.scraper import scrape_channel, TelegramScraperError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def main():
|
|
8
|
+
# Initialize colorama (so colors work on Windows too)
|
|
9
|
+
colorama_init(autoreset=True)
|
|
10
|
+
|
|
11
|
+
parser = argparse.ArgumentParser(
|
|
12
|
+
prog="telegram-scraper-cli",
|
|
13
|
+
description="Scrape messages from a public Telegram channel and save to CSV.",
|
|
14
|
+
)
|
|
15
|
+
parser.add_argument(
|
|
16
|
+
"--api-id",
|
|
17
|
+
type=int,
|
|
18
|
+
required=True,
|
|
19
|
+
help="Your Telegram API_ID (integer).",
|
|
20
|
+
)
|
|
21
|
+
parser.add_argument(
|
|
22
|
+
"--api-hash",
|
|
23
|
+
type=str,
|
|
24
|
+
required=True,
|
|
25
|
+
help="Your Telegram API_HASH (string).",
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"--channel",
|
|
29
|
+
type=str,
|
|
30
|
+
required=True,
|
|
31
|
+
help="Target channel username (without t.me/).",
|
|
32
|
+
)
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--limit",
|
|
35
|
+
type=int,
|
|
36
|
+
default=None,
|
|
37
|
+
help="Number of messages to scrape (omit or 0 for all).",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--output",
|
|
41
|
+
type=str,
|
|
42
|
+
default="msgs.csv",
|
|
43
|
+
help="Output CSV file path (default: msgs.csv).",
|
|
44
|
+
)
|
|
45
|
+
args = parser.parse_args()
|
|
46
|
+
|
|
47
|
+
# Echo back the provided options (in cyan)
|
|
48
|
+
print(f"{Fore.CYAN}→ Starting scrape: channel='{args.channel}', limit={args.limit or 'ALL'}, output='{args.output}'{Style.RESET_ALL}")
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
count = scrape_channel(
|
|
52
|
+
api_id=args.api_id,
|
|
53
|
+
api_hash=args.api_hash,
|
|
54
|
+
channel=args.channel,
|
|
55
|
+
limit=args.limit,
|
|
56
|
+
output_csv=args.output,
|
|
57
|
+
)
|
|
58
|
+
print(f"{Fore.GREEN}✅ Successfully saved {count} messages to '{args.output}'.{Style.RESET_ALL}")
|
|
59
|
+
sys.exit(0)
|
|
60
|
+
except TelegramScraperError as e:
|
|
61
|
+
print(f"{Fore.RED}❌ Error: {e}{Style.RESET_ALL}", file=sys.stderr)
|
|
62
|
+
sys.exit(1)
|
|
63
|
+
except Exception as e:
|
|
64
|
+
# Catch‐all, should be rare
|
|
65
|
+
print(f"{Fore.RED}❌ Unexpected error: {e}{Style.RESET_ALL}", file=sys.stderr)
|
|
66
|
+
sys.exit(1)
|
telegather/scraper.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import asyncio
|
|
3
|
+
from telethon import TelegramClient
|
|
4
|
+
from telethon.errors import (
|
|
5
|
+
SessionPasswordNeededError,
|
|
6
|
+
ChannelInvalidError,
|
|
7
|
+
ChannelPrivateError,
|
|
8
|
+
RPCError,
|
|
9
|
+
FloodWaitError,
|
|
10
|
+
)
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from typing import Optional
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class TelegramScraperError(Exception):
|
|
16
|
+
"""Base exception for scraper errors."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def _collect_messages(
|
|
20
|
+
api_id: int,
|
|
21
|
+
api_hash: str,
|
|
22
|
+
channel: str,
|
|
23
|
+
limit: Optional[int],
|
|
24
|
+
) -> list[dict]:
|
|
25
|
+
"""
|
|
26
|
+
Connects to Telegram, iterates through messages in `channel`,
|
|
27
|
+
and returns a list of dicts: [{'id': ..., 'date': ..., 'text': ...}, ...].
|
|
28
|
+
"""
|
|
29
|
+
client = TelegramClient("telegram_scraper_session", api_id, api_hash)
|
|
30
|
+
try:
|
|
31
|
+
await client.start()
|
|
32
|
+
except SessionPasswordNeededError:
|
|
33
|
+
raise TelegramScraperError("Two‐factor authentication is enabled. Please disable or handle separately.")
|
|
34
|
+
except RPCError as e:
|
|
35
|
+
raise TelegramScraperError(f"Failed to start Telegram client: {e}")
|
|
36
|
+
|
|
37
|
+
msgs: list[dict] = []
|
|
38
|
+
try:
|
|
39
|
+
# Telethon uses `limit=None` to fetch all messages
|
|
40
|
+
async for msg in client.iter_messages(channel, limit=limit):
|
|
41
|
+
if msg.message:
|
|
42
|
+
msgs.append({
|
|
43
|
+
"id": msg.id,
|
|
44
|
+
"date": msg.date.isoformat(),
|
|
45
|
+
"text": msg.message.replace("\n", " "),
|
|
46
|
+
})
|
|
47
|
+
except ChannelInvalidError:
|
|
48
|
+
raise TelegramScraperError(f"Channel '{channel}' does not exist.")
|
|
49
|
+
except ChannelPrivateError:
|
|
50
|
+
raise TelegramScraperError(f"Channel '{channel}' is private or you have no access.")
|
|
51
|
+
except FloodWaitError as e:
|
|
52
|
+
raise TelegramScraperError(f"Too many requests: must wait {e.seconds} seconds.")
|
|
53
|
+
except RPCError as e:
|
|
54
|
+
raise TelegramScraperError(f"Error while fetching messages: {e}")
|
|
55
|
+
finally:
|
|
56
|
+
await client.disconnect()
|
|
57
|
+
|
|
58
|
+
return msgs
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def scrape_channel(
|
|
62
|
+
api_id: int,
|
|
63
|
+
api_hash: str,
|
|
64
|
+
channel: str,
|
|
65
|
+
limit: Optional[int],
|
|
66
|
+
output_csv: str,
|
|
67
|
+
) -> int:
|
|
68
|
+
"""
|
|
69
|
+
High‐level function to fetch messages and write them to CSV.
|
|
70
|
+
Returns the number of messages saved.
|
|
71
|
+
Raises TelegramScraperError on any failure.
|
|
72
|
+
"""
|
|
73
|
+
if limit is not None and limit <= 0:
|
|
74
|
+
raise TelegramScraperError("`limit` must be a positive integer or omitted for all messages.")
|
|
75
|
+
|
|
76
|
+
# Validate that api_id is an integer
|
|
77
|
+
if not isinstance(api_id, int):
|
|
78
|
+
raise TelegramScraperError("`api_id` must be an integer.")
|
|
79
|
+
|
|
80
|
+
# Kick off the asyncio loop and collect messages
|
|
81
|
+
try:
|
|
82
|
+
msgs = asyncio.get_event_loop().run_until_complete(
|
|
83
|
+
_collect_messages(api_id, api_hash, channel, limit)
|
|
84
|
+
)
|
|
85
|
+
except TelegramScraperError:
|
|
86
|
+
raise
|
|
87
|
+
except Exception as e:
|
|
88
|
+
raise TelegramScraperError(f"Unexpected error: {e}")
|
|
89
|
+
|
|
90
|
+
if not msgs:
|
|
91
|
+
# Could be empty if channel has no messages or we had an access issue
|
|
92
|
+
raise TelegramScraperError(f"No messages found in channel '{channel}' or access denied.")
|
|
93
|
+
|
|
94
|
+
# Write to CSV (with BOM for Excel compatibility)
|
|
95
|
+
try:
|
|
96
|
+
with open(output_csv, "w", newline="", encoding="utf-8-sig") as f:
|
|
97
|
+
writer = csv.DictWriter(f, fieldnames=["id", "date", "text"])
|
|
98
|
+
writer.writeheader()
|
|
99
|
+
writer.writerows(msgs)
|
|
100
|
+
except Exception as e:
|
|
101
|
+
raise TelegramScraperError(f"Failed to write CSV '{output_csv}': {e}")
|
|
102
|
+
|
|
103
|
+
return len(msgs)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: telegather
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: CLI tool to scrape messages from a Telegram channel into CSV.
|
|
5
|
+
Home-page: https://github.com/Endale2/telegather
|
|
6
|
+
Author: Endale Shimelis
|
|
7
|
+
Author-email: endale406@gmail.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.7
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
Requires-Dist: telethon>=1.28.0
|
|
15
|
+
Requires-Dist: colorama>=0.4.6
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
telegather/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
telegather/cli.py,sha256=dPyOTtWxDrcen_xeJujpG-obQLuwGTBR7zZNg0NmsyM,2111
|
|
3
|
+
telegather/scraper.py,sha256=P0pwCNPGPE23EVIalQBM8pRbOC76sgtuaTC1-SJNn-c,3545
|
|
4
|
+
telegather-0.1.1.dist-info/licenses/LICENSE,sha256=tvPFR82gDzs7BDZfqVEc9z5B7FeIkfDEZUp9jJY5o0I,1103
|
|
5
|
+
telegather-0.1.1.dist-info/METADATA,sha256=evSvgXNbjUv_OKEx7Ear45v6ZfAw6K_ND6eK-5tPhh8,780
|
|
6
|
+
telegather-0.1.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
7
|
+
telegather-0.1.1.dist-info/entry_points.txt,sha256=venL9uaBg4uVk7Y2jmLvC5isFxSAkclSaNC1m8Qe4oc,51
|
|
8
|
+
telegather-0.1.1.dist-info/top_level.txt,sha256=F_T_0u6w8V1TL79Dn7Jaf3nKw28eosgmEG6Z2VUR8Ak,11
|
|
9
|
+
telegather-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Endale Shimelis
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the “Software”), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
telegather
|