telegather 0.2.0__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.
@@ -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,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: telegather
3
+ Version: 0.2.0
4
+ Summary: Export text messages from Telegram channels to CSV.
5
+ Author-email: Endale Shimelis <endale406@gmail.com>
6
+ Requires-Python: >=3.7
7
+ Description-Content-Type: text/markdown
8
+ License-Expression: MIT
9
+ Classifier: Environment :: Console
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ License-File: LICENSE
13
+ Requires-Dist: Telethon>=1.28,<2
14
+ Project-URL: Issues, https://github.com/endale-dev/telegather/issues
15
+ Project-URL: Source, https://github.com/endale-dev/telegather
16
+
17
+ # Telegather
18
+
19
+ Export text messages from a Telegram channel to CSV. Telegather uses [Telethon](https://docs.telethon.dev/) and keeps the same `id,date,text` columns as earlier releases. Messages are exported newest first, with line breaks in message text replaced by spaces.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install telegather
25
+ ```
26
+
27
+ Get an API ID and API hash from [my.telegram.org](https://my.telegram.org/), then run:
28
+
29
+ ```bash
30
+ telegather --api-id 123456 --api-hash YOUR_API_HASH --channel example --limit 50 --output messages.csv
31
+ ```
32
+
33
+ Run `telegather` in a terminal to enter the details through prompts. The API hash prompt hides your input. You can also set `TELEGRAM_API_ID` and `TELEGRAM_API_HASH` in the environment. Telegram may ask you to sign in on the first run. The session is saved as `telegram_scraper_session.session` by default. Use `--session PATH` to choose another location.
34
+
35
+ `--limit` counts messages inspected. Messages without text are skipped. Omit it or pass `0` to inspect the full channel history. The default output file is `msgs.csv`. The destination file is replaced only after an export succeeds.
36
+
37
+ ## Use from Python
38
+
39
+ ```python
40
+ from telegather import scrape_channel
41
+
42
+ count = scrape_channel(123456, "YOUR_API_HASH", "example", limit=50, output_csv="messages.csv")
43
+ ```
44
+
45
+ In an async program:
46
+
47
+ ```python
48
+ from telegather import scrape_channel_async
49
+
50
+ count = await scrape_channel_async(123456, "YOUR_API_HASH", "example", limit=50)
51
+ ```
52
+
53
+ Both functions return the number of CSV rows written and raise `TelegramScraperError` for export failures.
54
+
55
+ ## Development
56
+
57
+ ```bash
58
+ python -m pip install -e .
59
+ python -m unittest discover -s tests
60
+ python -m build
61
+ python -m twine check dist/*
62
+ ```
63
+
64
+ The license text is in [LICENSE](LICENSE).
65
+
@@ -0,0 +1,48 @@
1
+ # Telegather
2
+
3
+ Export text messages from a Telegram channel to CSV. Telegather uses [Telethon](https://docs.telethon.dev/) and keeps the same `id,date,text` columns as earlier releases. Messages are exported newest first, with line breaks in message text replaced by spaces.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pip install telegather
9
+ ```
10
+
11
+ Get an API ID and API hash from [my.telegram.org](https://my.telegram.org/), then run:
12
+
13
+ ```bash
14
+ telegather --api-id 123456 --api-hash YOUR_API_HASH --channel example --limit 50 --output messages.csv
15
+ ```
16
+
17
+ Run `telegather` in a terminal to enter the details through prompts. The API hash prompt hides your input. You can also set `TELEGRAM_API_ID` and `TELEGRAM_API_HASH` in the environment. Telegram may ask you to sign in on the first run. The session is saved as `telegram_scraper_session.session` by default. Use `--session PATH` to choose another location.
18
+
19
+ `--limit` counts messages inspected. Messages without text are skipped. Omit it or pass `0` to inspect the full channel history. The default output file is `msgs.csv`. The destination file is replaced only after an export succeeds.
20
+
21
+ ## Use from Python
22
+
23
+ ```python
24
+ from telegather import scrape_channel
25
+
26
+ count = scrape_channel(123456, "YOUR_API_HASH", "example", limit=50, output_csv="messages.csv")
27
+ ```
28
+
29
+ In an async program:
30
+
31
+ ```python
32
+ from telegather import scrape_channel_async
33
+
34
+ count = await scrape_channel_async(123456, "YOUR_API_HASH", "example", limit=50)
35
+ ```
36
+
37
+ Both functions return the number of CSV rows written and raise `TelegramScraperError` for export failures.
38
+
39
+ ## Development
40
+
41
+ ```bash
42
+ python -m pip install -e .
43
+ python -m unittest discover -s tests
44
+ python -m build
45
+ python -m twine check dist/*
46
+ ```
47
+
48
+ The license text is in [LICENSE](LICENSE).
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["flit_core>=3.12,<4"]
3
+ build-backend = "flit_core.buildapi"
4
+
5
+ [project]
6
+ name = "telegather"
7
+ dynamic = ["version"]
8
+ description = "Export text messages from Telegram channels to CSV."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{name = "Endale Shimelis", email = "endale406@gmail.com"}]
13
+ requires-python = ">=3.7"
14
+ dependencies = ["Telethon>=1.28,<2"]
15
+ classifiers = [
16
+ "Environment :: Console",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ ]
20
+
21
+ [project.scripts]
22
+ telegather = "telegather.cli:main"
23
+
24
+ [project.urls]
25
+ Source = "https://github.com/endale-dev/telegather"
26
+ Issues = "https://github.com/endale-dev/telegather/issues"
27
+
28
+ [tool.flit.sdist]
29
+ include = ["tests/*.py"]
@@ -0,0 +1,6 @@
1
+ """Export Telegram channel messages to CSV."""
2
+
3
+ from .scraper import TelegramScraperError, scrape_channel, scrape_channel_async
4
+
5
+ __version__ = "0.2.0"
6
+ __all__ = ["TelegramScraperError", "scrape_channel", "scrape_channel_async"]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,78 @@
1
+ """Command-line interface for Telegather."""
2
+
3
+ import argparse
4
+ import os
5
+ import sys
6
+ from getpass import getpass
7
+
8
+ from . import __version__
9
+ from .scraper import TelegramScraperError, scrape_channel
10
+
11
+
12
+ def _number(raw, minimum):
13
+ value = int(raw)
14
+ if value < minimum:
15
+ raise ValueError(f"Enter an integer of at least {minimum}.")
16
+ return value
17
+
18
+
19
+ def _prompt_number(label, minimum, default=None):
20
+ while True:
21
+ raw = input(label).strip()
22
+ if not raw and default is not None:
23
+ return default
24
+ try:
25
+ return _number(raw, minimum)
26
+ except ValueError:
27
+ print(f"Enter a whole number of at least {minimum}.", file=sys.stderr)
28
+
29
+
30
+ def main(argv=None):
31
+ parser = argparse.ArgumentParser(
32
+ prog="telegather", description="Export text messages from a Telegram channel to CSV."
33
+ )
34
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
35
+ parser.add_argument("--api-id", type=int, default=os.getenv("TELEGRAM_API_ID"),
36
+ help="Telegram API ID (or set TELEGRAM_API_ID).")
37
+ parser.add_argument("--api-hash", default=os.getenv("TELEGRAM_API_HASH"),
38
+ help="Telegram API hash (or set TELEGRAM_API_HASH).")
39
+ parser.add_argument("--channel", help="Telegram channel username.")
40
+ parser.add_argument("--limit", type=int, help="Messages to inspect (0 or omitted for all).")
41
+ parser.add_argument("--output", help="Destination CSV file (default: msgs.csv).")
42
+ parser.add_argument("--session", default="telegram_scraper_session",
43
+ help="Telethon session name or path (default: telegram_scraper_session).")
44
+ argv = sys.argv[1:] if argv is None else argv
45
+ args = parser.parse_args(argv)
46
+ interactive = sys.stdin.isatty()
47
+
48
+ try:
49
+ if interactive:
50
+ if args.api_id is None:
51
+ args.api_id = _prompt_number("Telegram API ID: ", 1)
52
+ if not args.api_hash:
53
+ args.api_hash = getpass("Telegram API hash: ").strip()
54
+ if not args.channel:
55
+ args.channel = input("Channel username: ").strip()
56
+ if not argv:
57
+ args.limit = _prompt_number("Messages to inspect [all]: ", 0, default=0)
58
+ args.output = input("Output CSV [msgs.csv]: ").strip()
59
+
60
+ if args.api_id is None or not args.api_hash or not args.channel:
61
+ parser.error("supply --api-id, --api-hash and --channel, or run in a terminal for prompts")
62
+ if args.limit is not None and args.limit < 0:
63
+ parser.error("--limit must be zero or a positive integer")
64
+ output = args.output or "msgs.csv"
65
+ count = scrape_channel(args.api_id, args.api_hash, args.channel, args.limit or None,
66
+ output, session=args.session)
67
+ except KeyboardInterrupt:
68
+ print("Export interrupted.", file=sys.stderr)
69
+ return 130
70
+ except (EOFError, TelegramScraperError) as exc:
71
+ print(f"Export failed: {exc}", file=sys.stderr)
72
+ return 1
73
+ print(f"Saved {count} messages to {output}.")
74
+ return 0
75
+
76
+
77
+ if __name__ == "__main__":
78
+ sys.exit(main())
@@ -0,0 +1,110 @@
1
+ """Stream Telegram messages to an Excel-compatible CSV file."""
2
+
3
+ import asyncio
4
+ import csv
5
+ import os
6
+ from pathlib import Path
7
+ from tempfile import NamedTemporaryFile
8
+ from typing import Optional, Union
9
+
10
+ from telethon import TelegramClient
11
+ from telethon.errors import (
12
+ ChannelInvalidError,
13
+ ChannelPrivateError,
14
+ FloodWaitError,
15
+ RPCError,
16
+ SessionPasswordNeededError,
17
+ )
18
+
19
+
20
+ class TelegramScraperError(Exception):
21
+ """A channel export could not be completed."""
22
+
23
+
24
+ async def scrape_channel_async(
25
+ api_id: int,
26
+ api_hash: str,
27
+ channel: str,
28
+ limit: Optional[int] = None,
29
+ output_csv: Union[str, Path] = "msgs.csv",
30
+ *,
31
+ session: Union[str, Path] = "telegram_scraper_session",
32
+ ) -> int:
33
+ """Export newest messages first and return the number of rows written.
34
+
35
+ The limit counts Telegram messages inspected, including those without text.
36
+ An empty export or a failed request leaves the destination intact.
37
+ """
38
+ if type(api_id) is not int or api_id <= 0:
39
+ raise TelegramScraperError("API ID must be a positive integer.")
40
+ if not isinstance(api_hash, str) or not api_hash.strip():
41
+ raise TelegramScraperError("API hash is required.")
42
+ if not isinstance(channel, str) or not channel.strip():
43
+ raise TelegramScraperError("Channel is required.")
44
+ if limit is not None and (type(limit) is not int or limit <= 0):
45
+ raise TelegramScraperError("Limit must be a positive integer or None.")
46
+
47
+ temporary = None
48
+ count = 0
49
+ try:
50
+ destination = Path(output_csv)
51
+ with NamedTemporaryFile(
52
+ mode="w", encoding="utf-8-sig", newline="", dir=destination.parent,
53
+ prefix=".telegather-", suffix=".tmp", delete=False,
54
+ ) as stream:
55
+ temporary = stream.name
56
+ writer = csv.writer(stream)
57
+ writer.writerow(("id", "date", "text"))
58
+ client = TelegramClient(str(session), api_id, api_hash.strip())
59
+ try:
60
+ await client.start()
61
+ async for message in client.iter_messages(channel.strip(), limit=limit):
62
+ if message.message:
63
+ text = message.message.replace("\r\n", " ").replace("\r", " ").replace("\n", " ")
64
+ writer.writerow((message.id, message.date.isoformat(), text))
65
+ count += 1
66
+ finally:
67
+ await client.disconnect()
68
+
69
+ if not count:
70
+ raise TelegramScraperError(f"No text messages found in '{channel}' within the requested limit.")
71
+ os.replace(temporary, destination)
72
+ temporary = None
73
+ return count
74
+ except TelegramScraperError:
75
+ raise
76
+ except SessionPasswordNeededError as exc:
77
+ raise TelegramScraperError("Sign in interactively with your two-step verification password.") from exc
78
+ except ChannelPrivateError as exc:
79
+ raise TelegramScraperError(f"Your account cannot access '{channel}'.") from exc
80
+ except ChannelInvalidError as exc:
81
+ raise TelegramScraperError(f"Invalid channel '{channel}'.") from exc
82
+ except FloodWaitError as exc:
83
+ raise TelegramScraperError(f"Telegram rate limit reached. Try again in {exc.seconds} seconds.") from exc
84
+ except RPCError as exc:
85
+ raise TelegramScraperError(f"Telegram request failed: {exc}") from exc
86
+ except Exception as exc:
87
+ raise TelegramScraperError(f"Could not export '{channel}' to '{output_csv}': {exc}") from exc
88
+ finally:
89
+ if temporary is not None and os.path.exists(temporary):
90
+ os.unlink(temporary)
91
+
92
+
93
+ def scrape_channel(
94
+ api_id: int,
95
+ api_hash: str,
96
+ channel: str,
97
+ limit: Optional[int] = None,
98
+ output_csv: Union[str, Path] = "msgs.csv",
99
+ *,
100
+ session: Union[str, Path] = "telegram_scraper_session",
101
+ ) -> int:
102
+ """Run an export synchronously. In an event loop, await scrape_channel_async."""
103
+ try:
104
+ asyncio.get_running_loop()
105
+ except RuntimeError:
106
+ pass
107
+ else:
108
+ raise TelegramScraperError("An event loop is running. Use await scrape_channel_async(...).")
109
+
110
+ return asyncio.run(scrape_channel_async(api_id, api_hash, channel, limit, output_csv, session=session))
@@ -0,0 +1,25 @@
1
+ import unittest
2
+ from io import StringIO
3
+ from unittest.mock import patch
4
+
5
+ from telegather.cli import main
6
+
7
+
8
+ class CliTests(unittest.TestCase):
9
+ def test_flags_run_without_prompts_or_exposing_hash(self):
10
+ output = StringIO()
11
+ with patch("telegather.cli.scrape_channel", return_value=2) as scrape:
12
+ with patch("sys.stdin.isatty", return_value=True):
13
+ with patch("builtins.input", side_effect=AssertionError("unexpected prompt")):
14
+ with patch("sys.stdout", output):
15
+ result = main([
16
+ "--api-id", "123", "--api-hash", "secret",
17
+ "--channel", "example", "--limit", "0",
18
+ ])
19
+ self.assertEqual(result, 0)
20
+ self.assertEqual(scrape.call_args.args, (123, "secret", "example", None, "msgs.csv"))
21
+ self.assertNotIn("secret", output.getvalue())
22
+
23
+
24
+ if __name__ == "__main__":
25
+ unittest.main()
@@ -0,0 +1,84 @@
1
+ import asyncio
2
+ import csv
3
+ import tempfile
4
+ import unittest
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from types import SimpleNamespace
8
+ from unittest.mock import patch
9
+
10
+ from telegather.scraper import TelegramScraperError, scrape_channel, scrape_channel_async
11
+
12
+
13
+ class FakeClient:
14
+ messages = []
15
+ failure = None
16
+ disconnected = False
17
+ last_instance = None
18
+
19
+ def __init__(self, session, api_id, api_hash):
20
+ self.session = session
21
+ FakeClient.last_instance = self
22
+
23
+ async def start(self):
24
+ pass
25
+
26
+ async def disconnect(self):
27
+ self.disconnected = True
28
+
29
+ async def iter_messages(self, channel, limit):
30
+ for message in self.messages[:limit]:
31
+ if self.failure:
32
+ raise self.failure
33
+ yield message
34
+
35
+
36
+ class ScraperTests(unittest.TestCase):
37
+ def setUp(self):
38
+ FakeClient.messages = [
39
+ SimpleNamespace(id=3, date=datetime(2025, 1, 1, tzinfo=timezone.utc), message="hello\nworld"),
40
+ SimpleNamespace(id=2, date=datetime(2025, 1, 1, tzinfo=timezone.utc), message=None),
41
+ SimpleNamespace(id=1, date=datetime(2025, 1, 1, tzinfo=timezone.utc), message="last"),
42
+ ]
43
+ FakeClient.failure = None
44
+ FakeClient.disconnected = False
45
+ self.directory = tempfile.TemporaryDirectory()
46
+ self.addCleanup(self.directory.cleanup)
47
+ self.output = Path(self.directory.name) / "messages.csv"
48
+ self.client_patch = patch("telegather.scraper.TelegramClient", FakeClient)
49
+ self.client_patch.start()
50
+ self.addCleanup(self.client_patch.stop)
51
+
52
+ def test_streams_messages_and_counts_only_text_rows(self):
53
+ count = scrape_channel(123, "hash", "channel", 2, self.output)
54
+ self.assertEqual(count, 1)
55
+ with self.output.open(encoding="utf-8-sig", newline="") as stream:
56
+ self.assertEqual(list(csv.reader(stream)), [
57
+ ["id", "date", "text"],
58
+ ["3", "2025-01-01T00:00:00+00:00", "hello world"],
59
+ ])
60
+ self.assertTrue(FakeClient.last_instance.disconnected)
61
+
62
+ def test_failure_keeps_existing_output(self):
63
+ self.output.write_text("existing", encoding="utf-8")
64
+ FakeClient.failure = RuntimeError("connection lost")
65
+ with self.assertRaises(TelegramScraperError):
66
+ scrape_channel(123, "hash", "channel", None, self.output)
67
+ self.assertEqual(self.output.read_text(encoding="utf-8"), "existing")
68
+ self.assertEqual(list(self.output.parent.glob(".telegather-*.tmp")), [])
69
+ self.assertTrue(FakeClient.last_instance.disconnected)
70
+
71
+ def test_async_entry_point(self):
72
+ count = asyncio.run(scrape_channel_async(123, "hash", "channel", None, self.output))
73
+ self.assertEqual(count, 2)
74
+
75
+ def test_running_loop_guides_to_async_entry_point(self):
76
+ async def call_sync():
77
+ with self.assertRaisesRegex(TelegramScraperError, "scrape_channel_async"):
78
+ scrape_channel(123, "hash", "channel", None, self.output)
79
+
80
+ asyncio.run(call_sync())
81
+
82
+
83
+ if __name__ == "__main__":
84
+ unittest.main()