post-on-telegram 0.1.0__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.
@@ -0,0 +1,23 @@
1
+ # src/post_on_telegram/__init__.py
2
+ """
3
+ Post on Telegram - Send messages and documents to Telegram chats through a bot.
4
+
5
+ This is an unofficial library, not affiliated with Telegram.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from ._version import __version__
11
+ from .errors import ConfigError, PostOnTelegramError
12
+ from .formatting import escape_html, escape_markdown_v2, format_pre
13
+ from .poster import Poster
14
+
15
+ __all__ = [
16
+ "Poster",
17
+ "PostOnTelegramError",
18
+ "ConfigError",
19
+ "escape_html",
20
+ "escape_markdown_v2",
21
+ "format_pre",
22
+ "__version__",
23
+ ]
@@ -0,0 +1,9 @@
1
+ # src/post_on_telegram/__main__.py
2
+ """Allow running the package as a module: python -m post_on_telegram."""
3
+
4
+ import sys
5
+
6
+ from .cli import main
7
+
8
+ if __name__ == "__main__":
9
+ sys.exit(main())
@@ -0,0 +1,2 @@
1
+ # src/post_on_telegram/_version.py
2
+ __version__ = "0.1.0"
@@ -0,0 +1,159 @@
1
+ # src/post_on_telegram/chunking.py
2
+ """Message chunking logic for Telegram's character limits."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import unicodedata
7
+
8
+
9
+ def _is_safe_split_point(text: str, index: int) -> bool:
10
+ """Return True if splitting at *index* won't break a surrogate pair or
11
+ separate a base character from its combining marks.
12
+
13
+ *index* is the position where the left chunk ends (i.e. text[index-1]
14
+ is the last character of the left chunk and text[index] is the first
15
+ character of the right chunk).
16
+ """
17
+ if index <= 0 or index >= len(text):
18
+ return True
19
+ left = text[index - 1]
20
+ right = text[index]
21
+ # Never split inside a surrogate pair (high surrogate followed by low).
22
+ if 0xD800 <= ord(left) <= 0xDBFF and 0xDC00 <= ord(right) <= 0xDFFF:
23
+ return False
24
+ # Never split a base character from its combining marks.
25
+ if unicodedata.category(right).startswith("M"):
26
+ return False
27
+ return True
28
+
29
+
30
+ def _find_split_point(text: str, limit: int) -> int:
31
+ """Find the best split point within *limit* characters.
32
+
33
+ Prefers a blank line, then a newline, then a space, finally a hard cut.
34
+ Never returns 0 unless limit <= 0 or text is empty.
35
+ """
36
+ if len(text) <= limit:
37
+ return len(text)
38
+ if limit <= 0:
39
+ return 0
40
+
41
+ search_end = min(limit, len(text))
42
+ # 1. Search backwards for a blank line (two consecutive newlines).
43
+ blank_line = text.rfind("\n\n", 0, search_end)
44
+ if blank_line != -1:
45
+ candidate = blank_line + 2
46
+ if candidate <= limit and _is_safe_split_point(text, candidate):
47
+ return candidate
48
+
49
+ # 2. Search backwards for a single newline.
50
+ newline = text.rfind("\n", 0, search_end)
51
+ if newline != -1:
52
+ candidate = newline + 1
53
+ if candidate <= limit and _is_safe_split_point(text, candidate):
54
+ return candidate
55
+
56
+ # 3. Search backwards for a space.
57
+ space = text.rfind(" ", 0, search_end)
58
+ if space != -1:
59
+ candidate = space + 1
60
+ if candidate <= limit and _is_safe_split_point(text, candidate):
61
+ return candidate
62
+
63
+ # 4. Hard cut: move backwards until we find a safe split point.
64
+ candidate = limit
65
+ while candidate > 0 and not _is_safe_split_point(text, candidate):
66
+ candidate -= 1
67
+ if candidate == 0:
68
+ # Last resort: split at limit
69
+ candidate = limit
70
+ return candidate
71
+
72
+
73
+ def _split_into_raw_slices(text: str, max_slice_len: int) -> list[str]:
74
+ """Split *text* into raw slices each at most *max_slice_len* characters.
75
+
76
+ Splits at natural boundaries (blank line, newline, space, or hard cut)
77
+ without dropping any non-whitespace content.
78
+ """
79
+ if max_slice_len <= 0:
80
+ raise ValueError("max_slice_len must be > 0")
81
+
82
+ slices: list[str] = []
83
+ remaining = text
84
+ while remaining:
85
+ if len(remaining) <= max_slice_len:
86
+ if remaining.strip():
87
+ slices.append(remaining)
88
+ break
89
+ split_at = _find_split_point(remaining, max_slice_len)
90
+ if split_at <= 0:
91
+ split_at = max_slice_len
92
+ piece = remaining[:split_at]
93
+ # Drop whitespace-only intermediate slices
94
+ if piece.strip():
95
+ slices.append(piece)
96
+ remaining = remaining[split_at:]
97
+ return slices
98
+
99
+
100
+ def _calculate_prefix_len(n: int) -> int:
101
+ """Calculate the length of the prefix "[i/n] " for a given chunk count n."""
102
+ return len(f"[{n}/{n}] ")
103
+
104
+
105
+ def chunk_text(text: str, max_length: int) -> list[str]:
106
+ """Split *text* into chunks of at most *max_length* characters.
107
+
108
+ When more than one chunk is needed, each chunk is prefixed with "[i/n] "
109
+ where the prefix is counted inside the *max_length* limit.
110
+
111
+ Splitting prefers blank lines, then newlines, then spaces, and finally
112
+ hard cuts. No empty chunks are produced and no text is lost.
113
+
114
+ Args:
115
+ text: The text to split.
116
+ max_length: Maximum characters per chunk (must be > 0).
117
+
118
+ Returns:
119
+ A list of non-empty chunks.
120
+ """
121
+ if max_length <= 0:
122
+ raise ValueError("max_length must be > 0")
123
+
124
+ if not text:
125
+ return []
126
+
127
+ # If the text fits in one chunk without prefix, return it directly.
128
+ if len(text) <= max_length:
129
+ return [text]
130
+
131
+ # Iteratively determine total chunk count n such that:
132
+ # len(f"[{i}/{n}] " + slice_i) <= max_length for all i in 1..n
133
+ n_guess = 2
134
+ while True:
135
+ # Calculate maximum prefix length across all 1..n_guess
136
+ # e.g. for n_guess=10, prefixes range from "[1/10] " (len 7) to "[10/10] " (len 8)
137
+ max_prefix_len = _calculate_prefix_len(n_guess)
138
+ payload_limit = max_length - max_prefix_len
139
+ if payload_limit <= 0:
140
+ # max_length is too small for prefix + payload
141
+ payload_limit = 1
142
+
143
+ raw_slices = _split_into_raw_slices(text, payload_limit)
144
+ actual_n = len(raw_slices)
145
+
146
+ if actual_n <= n_guess:
147
+ # We found a stable n!
148
+ n = actual_n
149
+ if n == 1:
150
+ return [text]
151
+ chunks: list[str] = []
152
+ for i, piece in enumerate(raw_slices, start=1):
153
+ # Use escaped prefix for MarkdownV2: \[i/n\]
154
+ # The prefix length is counted inside the max_length limit
155
+ prefix = f"[{i}/{n}] "
156
+ chunks.append(prefix + piece)
157
+ return chunks
158
+ # Otherwise, need more chunks than guessed
159
+ n_guess = max(actual_n, n_guess + 1)
@@ -0,0 +1,162 @@
1
+ # src/post_on_telegram/cli.py
2
+ """Command-line interface for post-on-telegram."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import sys
8
+ from collections.abc import Sequence
9
+
10
+ from ._version import __version__
11
+ from .poster import Poster, redact
12
+
13
+
14
+ def _build_parser() -> argparse.ArgumentParser:
15
+ parser = argparse.ArgumentParser(
16
+ prog="post-on-telegram",
17
+ description="Send messages and documents to Telegram chats via a bot.",
18
+ )
19
+ parser.add_argument(
20
+ "message",
21
+ nargs="?",
22
+ default=None,
23
+ help="Message text to send, or '-' for stdin",
24
+ )
25
+ parser.add_argument("--credentials", metavar="FILE", help="Path to credentials JSON file")
26
+ parser.add_argument(
27
+ "--parse-mode",
28
+ choices=["plain", "html", "markdownv2"],
29
+ default="plain",
30
+ help="Message parse mode (plain, html, or markdownv2)",
31
+ )
32
+ parser.add_argument("--no-preview", action="store_true", help="Disable web page preview")
33
+ parser.add_argument(
34
+ "--silent",
35
+ action="store_true",
36
+ help="Send silently (disable notification)",
37
+ )
38
+ parser.add_argument("--chat-id", metavar="ID", help="Override chat ID")
39
+ parser.add_argument("--file", metavar="PATH", help="Path of document to send")
40
+ parser.add_argument("--caption", metavar="TEXT", help="Caption for document")
41
+ parser.add_argument("--check", action="store_true", help="Verify credentials and bot identity")
42
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
43
+ return parser
44
+
45
+
46
+ def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
47
+ return _build_parser().parse_args(argv)
48
+
49
+
50
+ def main(argv: Sequence[str] | None = None) -> int:
51
+ """CLI main function.
52
+
53
+ Exit codes:
54
+ 0 - Success
55
+ 1 - Send or Telegram failure
56
+ 2 - Usage or configuration error
57
+ """
58
+ raw_args = list(sys.argv[1:] if argv is None else argv)
59
+
60
+ # Reject --token explicitly (security rule: tokens must not appear in process lists/argv)
61
+ for arg in raw_args:
62
+ if arg == "--token" or arg.startswith("--token="):
63
+ sys.stderr.write(
64
+ "Error: --token is not supported for security reasons. "
65
+ "Use a credentials file or POST_ON_TELEGRAM_TOKEN env var.\n"
66
+ )
67
+ return 2
68
+
69
+ try:
70
+ args = _parse_args(raw_args)
71
+ except SystemExit as exc:
72
+ return exc.code if isinstance(exc.code, int) else 2
73
+
74
+ # Map CLI parse-mode string to library parse_mode
75
+ mode_map = {
76
+ "plain": None,
77
+ "html": "HTML",
78
+ "markdownv2": "MarkdownV2",
79
+ }
80
+ lib_parse_mode = mode_map.get(args.parse_mode.lower()) if args.parse_mode else None
81
+
82
+ poster = Poster(credentials_file=args.credentials, chat_id=args.chat_id)
83
+
84
+ # Handle --check
85
+ if args.check:
86
+ if not poster.enabled:
87
+ err = poster.last_error or "Missing credentials (token or chat_id)"
88
+ sys.stderr.write(f"Check failed: {redact(err)}\n")
89
+ return 2
90
+
91
+ # Check bot validity via getMe
92
+ if not poster.check():
93
+ err = poster.last_error or "Check failed"
94
+ sys.stderr.write(f"Check failed: {redact(err)}\n")
95
+ return 1
96
+
97
+ # Fetch username if possible
98
+ username = "valid bot"
99
+ try:
100
+ url = f"https://api.telegram.org/bot{poster._token}/getMe"
101
+ resp = poster._session.get(url, timeout=(5, 10))
102
+ data = resp.json()
103
+ if isinstance(data, dict) and data.get("ok"):
104
+ res = data.get("result", {})
105
+ if isinstance(res, dict) and "username" in res:
106
+ username = f"@{res['username']}"
107
+ except Exception:
108
+ pass
109
+
110
+ sys.stdout.write(f"Bot verified successfully: {username}\n")
111
+ return 0
112
+
113
+ # Ensure poster is configured
114
+ if not poster.enabled:
115
+ err = poster.last_error or "No bot token or chat ID configured"
116
+ sys.stderr.write(f"Configuration error: {redact(err)}\n")
117
+ return 2
118
+
119
+ # Handle --file document upload
120
+ if args.file:
121
+ ok = poster.send_document(
122
+ args.file,
123
+ caption=args.caption,
124
+ parse_mode=lib_parse_mode,
125
+ chat_id=args.chat_id,
126
+ )
127
+ if not ok:
128
+ err = poster.last_error or "Failed to send document"
129
+ sys.stderr.write(f"Error: {redact(err)}\n")
130
+ return 1
131
+ return 0
132
+
133
+ # Read message
134
+ message_text = args.message
135
+ if message_text == "-":
136
+ try:
137
+ message_text = sys.stdin.read()
138
+ except Exception as exc:
139
+ sys.stderr.write(f"Error reading stdin: {exc}\n")
140
+ return 2
141
+
142
+ if message_text is None:
143
+ sys.stderr.write("Error: MESSAGE or --file or --check required\n")
144
+ return 2
145
+
146
+ ok = poster.send(
147
+ message_text,
148
+ parse_mode=lib_parse_mode,
149
+ disable_web_page_preview=args.no_preview,
150
+ disable_notification=args.silent,
151
+ chat_id=args.chat_id,
152
+ )
153
+ if not ok:
154
+ err = poster.last_error or "Failed to send message"
155
+ sys.stderr.write(f"Error: {redact(err)}\n")
156
+ return 1
157
+
158
+ return 0
159
+
160
+
161
+ if __name__ == "__main__":
162
+ sys.exit(main())
@@ -0,0 +1,221 @@
1
+ # src/post_on_telegram/credentials.py
2
+ """Credential resolution for the Poster class.
3
+
4
+ Handles reading bot tokens and chat IDs from:
5
+ 1. Explicit arguments to Poster
6
+ 2. A JSON credentials file
7
+ 3. Environment variables POST_ON_TELEGRAM_TOKEN / POST_ON_TELEGRAM_CHAT_ID
8
+
9
+ Never logs or returns the unmasked token.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import logging
16
+ import os
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from .errors import ConfigError
21
+
22
+ logger = logging.getLogger("post_on_telegram")
23
+
24
+
25
+ def _expand_user(path: str | os.PathLike[str]) -> Path:
26
+ """Expand ~ in *path* (environment variables are intentionally NOT expanded)."""
27
+ return Path(os.path.expanduser(str(path)))
28
+
29
+
30
+ def _check_file_permissions(path: str | Path) -> None:
31
+ """On POSIX, warn if credentials file is group/other readable (mode & 0o077).
32
+
33
+ Never raises; only logs a warning on non-Windows.
34
+ """
35
+ if os.name == "posix":
36
+ try:
37
+ mode = os.stat(str(path)).st_mode
38
+ if mode & 0o077:
39
+ logger.warning(
40
+ "Credentials file %s is group/other readable (mode %o); consider chmod 600",
41
+ path,
42
+ mode & 0o777,
43
+ )
44
+ except OSError:
45
+ pass
46
+
47
+
48
+ def _extract_token_from_dict(data: dict[str, Any]) -> str:
49
+ """Extract bot_token from dict, supporting legacy alias 'telegram_token'."""
50
+ val = data.get("bot_token")
51
+ if val is None:
52
+ val = data.get("telegram_token")
53
+ if val is None:
54
+ return ""
55
+ token_str = str(val).strip()
56
+ return token_str
57
+
58
+
59
+ def _extract_chat_id_from_dict(data: dict[str, Any]) -> str:
60
+ """Extract chat_id from dict, supporting legacy alias 'telegram_id'."""
61
+ val = data.get("chat_id")
62
+ if val is None:
63
+ val = data.get("telegram_id")
64
+ if val is None:
65
+ return ""
66
+ chat_str = str(val).strip()
67
+ return chat_str
68
+
69
+
70
+ def _decode_credentials_bytes(raw_bytes: bytes) -> str:
71
+ """Decode credentials file bytes, handling UTF-8 (with/without BOM) and UTF-16.
72
+
73
+ Detects UTF-16 BOMs (FF FE for little-endian, FE FF for big-endian) and
74
+ decodes accordingly. Falls back to UTF-8 with BOM handling (utf-8-sig).
75
+ """
76
+ if raw_bytes.startswith(b"\xff\xfe") or raw_bytes.startswith(b"\xfe\xff"):
77
+ return raw_bytes.decode("utf-16")
78
+ return raw_bytes.decode("utf-8-sig")
79
+
80
+
81
+ def resolve_credentials(
82
+ token: str | None = None,
83
+ chat_id: str | int | None = None,
84
+ *,
85
+ credentials_file: str | os.PathLike[str] | None = None,
86
+ strict: bool = False,
87
+ ) -> dict[str, str]:
88
+ """Resolve bot token and chat ID following the priority order.
89
+
90
+ Priority: explicit args > credentials file > env vars.
91
+
92
+ Args:
93
+ token: Explicit bot token.
94
+ chat_id: Explicit chat ID (str or int).
95
+ credentials_file: Path to JSON credentials file.
96
+ strict: If True, raise ConfigError on configuration errors.
97
+
98
+ Returns:
99
+ dict with "bot_token" and "chat_id" keys.
100
+
101
+ Raises:
102
+ ConfigError: If strict=True and resolution fails or format is invalid.
103
+ """
104
+ resolved_token: str | None = None
105
+ resolved_chat_id: str | None = None
106
+
107
+ # 1. Explicit arguments
108
+ if token is not None:
109
+ token_str = str(token).strip()
110
+ if token_str:
111
+ resolved_token = token_str
112
+
113
+ if chat_id is not None:
114
+ chat_str = str(chat_id).strip()
115
+ if chat_str:
116
+ resolved_chat_id = chat_str
117
+
118
+ # 2. Credentials file
119
+ if credentials_file is not None:
120
+ target_path = _expand_user(credentials_file)
121
+ try:
122
+ path_exists = target_path.exists()
123
+ except OSError as exc:
124
+ path_exists = False
125
+ msg = f"Could not access credentials file {target_path}: {exc}"
126
+ if strict:
127
+ raise ConfigError(msg) from exc
128
+ logger.warning(msg)
129
+
130
+ if not path_exists:
131
+ msg = f"Credentials file not found: {target_path}"
132
+ if strict:
133
+ raise ConfigError(msg)
134
+ logger.warning(msg)
135
+ else:
136
+ try:
137
+ is_file = target_path.is_file()
138
+ except OSError as exc:
139
+ is_file = False
140
+ msg = f"Could not stat credentials file {target_path}: {exc}"
141
+ if strict:
142
+ raise ConfigError(msg) from exc
143
+ logger.warning(msg)
144
+
145
+ if not is_file:
146
+ msg = f"Credentials path is not a file: {target_path}"
147
+ if strict:
148
+ raise ConfigError(msg)
149
+ logger.warning(msg)
150
+ else:
151
+ _check_file_permissions(target_path)
152
+ data: Any = {}
153
+ try:
154
+ raw_bytes = target_path.read_bytes()
155
+ raw_text = _decode_credentials_bytes(raw_bytes)
156
+ if not raw_text.strip():
157
+ msg = f"Credentials file is empty: {target_path}"
158
+ if strict:
159
+ raise ConfigError(msg)
160
+ logger.warning(msg)
161
+ data = {}
162
+ else:
163
+ data = json.loads(raw_text)
164
+ except ValueError as exc:
165
+ # Covers UnicodeDecodeError and json.JSONDecodeError
166
+ msg = f"Invalid JSON in credentials file {target_path}: {exc}"
167
+ if strict:
168
+ raise ConfigError(msg) from exc
169
+ logger.warning(msg)
170
+ data = {}
171
+ except OSError as exc:
172
+ msg = f"Could not read credentials file {target_path}: {exc}"
173
+ if strict:
174
+ raise ConfigError(msg) from exc
175
+ logger.warning(msg)
176
+ data = {}
177
+
178
+ if not isinstance(data, dict):
179
+ msg = (
180
+ f"Credentials file {target_path} must contain a JSON object, "
181
+ f"got {type(data).__name__}"
182
+ )
183
+ if strict:
184
+ raise ConfigError(msg)
185
+ logger.warning(msg)
186
+ else:
187
+ file_token = _extract_token_from_dict(data)
188
+ file_chat = _extract_chat_id_from_dict(data)
189
+
190
+ if resolved_token is None and file_token:
191
+ resolved_token = file_token
192
+ if resolved_chat_id is None and file_chat:
193
+ resolved_chat_id = file_chat
194
+
195
+ # 3. Environment variables fallback
196
+ if resolved_token is None:
197
+ env_token = os.environ.get("POST_ON_TELEGRAM_TOKEN", "").strip()
198
+ if env_token:
199
+ resolved_token = env_token
200
+
201
+ if resolved_chat_id is None:
202
+ env_chat = os.environ.get("POST_ON_TELEGRAM_CHAT_ID", "").strip()
203
+ if env_chat:
204
+ resolved_chat_id = env_chat
205
+
206
+ # Validate results
207
+ if strict:
208
+ if not resolved_token:
209
+ raise ConfigError("No bot_token provided or found in environment/file")
210
+ if not resolved_chat_id:
211
+ raise ConfigError("No chat_id provided or found in environment/file")
212
+ if ":" not in resolved_token:
213
+ raise ConfigError("Invalid token format: token does not contain ':'")
214
+
215
+ if resolved_token and ":" not in resolved_token:
216
+ logger.warning("Token does not contain ':' (not a valid Telegram bot token)")
217
+
218
+ return {
219
+ "bot_token": resolved_token or "",
220
+ "chat_id": resolved_chat_id or "",
221
+ }
@@ -0,0 +1,6 @@
1
+ class PostOnTelegramError(Exception):
2
+ """Base exception for post-on-telegram."""
3
+
4
+
5
+ class ConfigError(PostOnTelegramError):
6
+ """Raised when configuration is invalid (strict mode)."""
@@ -0,0 +1,50 @@
1
+ # src/post_on_telegram/formatting.py
2
+ """Text formatting helpers for Telegram messages."""
3
+
4
+ from __future__ import annotations
5
+
6
+
7
+ def escape_html(text: str) -> str:
8
+ """Escape HTML special characters: &, <, >.
9
+
10
+ Args:
11
+ text: The text to escape.
12
+
13
+ Returns:
14
+ The text with &, <, > escaped as HTML entities.
15
+ """
16
+ text = text.replace("&", "&amp;")
17
+ text = text.replace("<", "&lt;")
18
+ text = text.replace(">", "&gt;")
19
+ return text
20
+
21
+
22
+ def escape_markdown_v2(text: str) -> str:
23
+ """Escape all MarkdownV2 special characters.
24
+
25
+ Characters escaped: _ * [ ] ( ) ~ ` > # + - = | { } . ! and backslash.
26
+
27
+ Args:
28
+ text: The text to escape.
29
+
30
+ Returns:
31
+ The text with MarkdownV2 special characters escaped.
32
+ """
33
+ chars_to_escape = r"_*[]()~`>#+-=|{}.!\\"
34
+ escape_table = str.maketrans({c: f"\\{c}" for c in chars_to_escape})
35
+ return text.translate(escape_table)
36
+
37
+
38
+ def format_pre(text: str) -> str:
39
+ """Format text as a monospace code block (HTML <pre> tag).
40
+
41
+ Intended for use with parse_mode="HTML".
42
+
43
+ Args:
44
+ text: The text to format.
45
+
46
+ Returns:
47
+ The text wrapped in <pre> tags with HTML-escaped content.
48
+ """
49
+ escaped = escape_html(text)
50
+ return f"<pre>{escaped}</pre>"