Repository navigation
Expand file tree
/
Copy pathtelegram_post_all.py
More file actions
executable file
·359 lines (305 loc) · 12 KB
/
Copy pathtelegram_post_all.py
File metadata and controls
executable file
·359 lines (305 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env python3
"""
Post localized markdown content with optional media to multiple Telegram groups.
Usage:
python3 tools/telegram_post_all.py <path_to_content_folder> [--dry-run] [--yes]
python3 tools/telegram_post_all.py <folder> --only @OrganicMapsRu,de,zh-Hans
python3 tools/telegram_post_all.py <folder> --skip ru
The folder should contain markdown files like index.ru.md, index.fr.md, etc.
and optionally media files (images/videos/audio) to attach to every post.
Posting stops at the first failure. Use --only with the channels listed in the
"Resume with" hint to continue without double-posting to channels that already
succeeded.
Environment:
TELEGRAM_BOT_TOKEN - your bot token from @BotFather
"""
import argparse
import re
import shlex
import sys
from pathlib import Path
from markdown_frontmatter import strip_frontmatter
from telegram_post import (
failed_text_may_have_reached_channel,
get_token,
resolve_chat_id,
send_text_messages,
send_media,
validate_media_set,
load_references,
resolve_references,
find_unresolved_references,
load_base_url,
resolve_zola_references,
strip_tera_blocks,
ZOLA_FILENAME_RE,
)
# Telegram group → markdown filename
GROUPS: dict[str, str] = {
"@OrganicMapsApp": "index.md",
"@OrganicMapsAR": "index.ar.md",
"@OrganicMapsDeutsch": "index.de.md",
"@OrganicMapsES": "index.es.md",
"@OrganicMapsFR": "index.fr.md",
"@OrganicMapsIT": "index.it.md",
"@OrganicMapsPersian": "index.fa-IR.md",
"@OrganicMapsPT": "index.pt.md",
"@OrganicMapsRu": "index.ru.md",
"@OrganicMapsTR": "index.tr.md",
"@OrganicMapsUA": "index.uk.md",
"@OrganicMapsZH": "index.zh-Hans.md",
}
MEDIA_EXTENSIONS = {
".jpeg",
".jpg",
".m4a",
".mov",
".mp3",
".mp4",
".png",
".webp",
}
def group_lang(filename: str) -> str:
"""Language suffix of a content filename. 'index.zh-Hans.md' → 'zh-Hans'."""
m = ZOLA_FILENAME_RE.match(filename)
return (m.group("lang") if m else None) or "en"
def select_groups(only: str | None, skip: str | None) -> dict[str, str]:
"""Filter GROUPS by --only/--skip selectors.
A selector is either a channel name (with or without '@', case-insensitive)
or a language suffix such as 'ru' or 'zh-Hans'. Unknown selectors are a
hard error: a typo in --skip would otherwise post to a channel you meant
to leave out.
"""
def parse(raw: str | None) -> list[str]:
if not raw:
return []
return [s.strip() for s in raw.split(",") if s.strip()]
aliases: dict[str, str] = {}
for group, filename in GROUPS.items():
aliases[group.lower()] = group
aliases[group.lstrip("@").lower()] = group
aliases[group_lang(filename).lower()] = group
def resolve(selectors: list[str], flag: str) -> set[str]:
resolved: set[str] = set()
for sel in selectors:
group = aliases.get(sel.lower())
if group is None:
known = ", ".join(sorted(group_lang(f) for f in GROUPS.values()))
print(
f"Error: unknown {flag} selector '{sel}'.\n"
f"Use a channel name or one of: {known}",
file=sys.stderr,
)
sys.exit(1)
resolved.add(group)
return resolved
keep = resolve(parse(only), "--only") if only else set(GROUPS)
drop = resolve(parse(skip), "--skip")
return {g: f for g, f in GROUPS.items() if g in keep and g not in drop}
def find_media(folder: Path) -> list[Path]:
"""Find media, preferring lowercase .webp siblings over JPEG and PNG originals."""
media = sorted(
p
for p in folder.iterdir()
if p.is_file() and p.suffix.lower() in MEDIA_EXTENSIONS
)
webp_names = {p.name for p in media if p.suffix == ".webp"}
return [
p for p in media
if not (p.suffix.lower() in {".jpg", ".jpeg", ".png"} and p.with_suffix(".webp").name in webp_names)
]
def prepare_text(md_path: Path, site_root: Path) -> str:
"""Read markdown file, strip frontmatter, resolve references, clean up."""
raw = md_path.read_text(encoding="utf-8")
text, meta = strip_frontmatter(raw)
title = meta.get("title", "")
if title:
text = f"**{title}**\n\n{text.lstrip()}"
text = strip_tera_blocks(text)
# Strip angle brackets from bare URLs
text = re.sub(r"<(https?://[^>]+)>", r"\1", text)
# Clean up blank lines
text = re.sub(r"\n{3,}", "\n\n", text)
# Resolve markdown reference-style links
refs = load_references(site_root)
text = resolve_references(text, refs)
# Resolve Zola @/-style internal references → absolute site URLs.
base_url = load_base_url(site_root)
text, zola_unresolved = resolve_zola_references(text, site_root, base_url)
if zola_unresolved:
print(
f"Warning: {md_path.name} has "
f"{len(zola_unresolved)} unresolved Zola @/-reference(s):",
file=sys.stderr,
)
for target in zola_unresolved:
print(f" @/{target}", file=sys.stderr)
return text
def main() -> None:
parser = argparse.ArgumentParser(
description="Post localized content to multiple Telegram groups."
)
parser.add_argument(
"folder",
type=Path,
help="Path to folder with index.*.md files and optional media",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be posted without actually sending",
)
parser.add_argument(
"--yes", "-y", action="store_true", help="Skip confirmation prompts"
)
parser.add_argument(
"--only",
help="Comma-separated channels or language codes to post to "
"(e.g. '@OrganicMapsRu,de,zh-Hans'). Use this to resume after a failure.",
)
parser.add_argument(
"--skip",
help="Comma-separated channels or language codes to leave out",
)
parser.add_argument(
"--allow-plain-fallback",
action="store_true",
help="If Telegram rejects the MarkdownV2 markup, post the message "
"unformatted instead of aborting (default: abort)",
)
args = parser.parse_args()
if not args.folder.is_dir():
print(f"Error: not a directory: {args.folder}", file=sys.stderr)
sys.exit(1)
groups = select_groups(args.only, args.skip)
if not groups:
print("Error: no channels left after --only/--skip.", file=sys.stderr)
sys.exit(1)
# tools/ lives one level below the site root
site_root = Path(__file__).resolve().parent.parent
# Discover media files
media = find_media(args.folder)
media_problem = validate_media_set(media)
if media_problem:
print(f"Error: {media_problem}", file=sys.stderr)
sys.exit(1)
# A dry run never talks to the API, so it must not require a token.
token = "" if args.dry_run else get_token()
# Discover which groups have matching markdown files, and render each post
# once — prepare_text() is not free and its warnings should print once.
tasks: list[tuple[str, Path, str]] = []
for group, filename in groups.items():
md_path = args.folder / filename
if md_path.is_file():
tasks.append((group, md_path, prepare_text(md_path, site_root)))
if not tasks:
print("No matching markdown files found in the folder.", file=sys.stderr)
print(f"Expected filenames: {', '.join(groups.values())}")
sys.exit(1)
# Summary
print(f"Folder: {args.folder}")
print(f"Media: {len(media)} file(s)")
for m in media:
print(f" {m.name}")
print(f"Posts: {len(tasks)} group(s)")
for group, md_path, _ in tasks:
print(f" {group} ← {md_path.name}")
skipped = {fn for fn in groups.values()} - {t[1].name for t in tasks}
if skipped:
print(f"Skipped (file not found): {', '.join(sorted(skipped))}")
excluded = set(GROUPS) - set(groups)
if excluded:
print(f"Excluded by --only/--skip: {', '.join(sorted(excluded))}")
print()
# Check for unresolved references in all files before posting
has_warnings = False
for group, md_path, text in tasks:
unresolved = find_unresolved_references(text)
if unresolved:
has_warnings = True
print(
f"Warning: {md_path.name} has {len(unresolved)} "
f"unresolved reference(s):",
file=sys.stderr,
)
for match_text, ref_id, lineno in unresolved:
print(
f" line {lineno}: {match_text} " f"(undefined id: {ref_id})",
file=sys.stderr,
)
if has_warnings and not args.yes:
answer = input("\nContinue posting with unresolved references? [y/N] ").strip()
if answer.lower() not in ("y", "yes"):
print("Aborted.")
sys.exit(0)
if not args.yes and not args.dry_run:
answer = input(f"Post to {len(tasks)} group(s)? [y/N] ").strip()
if answer.lower() not in ("y", "yes"):
print("Aborted.")
sys.exit(0)
# Resolve every chat up front. resolve_chat_id() exits on an unknown
# channel or a failed lookup, before any messages have been sent.
chat_ids: dict[str, str] = {}
if not args.dry_run:
print("Resolving channels before posting...")
for group, _, _ in tasks:
chat_ids[group] = resolve_chat_id(token, group)
def abort(message: str, resume_at: int) -> None:
"""Report a failure and show how to resume without double-posting."""
print(f"\nFATAL: {message}", file=sys.stderr)
remaining = [group for group, _, _ in tasks[resume_at:]]
if remaining:
command = [
sys.executable, sys.argv[0], str(args.folder), "--only", ",".join(remaining),
]
if args.allow_plain_fallback:
command.append("--allow-plain-fallback")
print(f"\nResume with:\n {shlex.join(command)}", file=sys.stderr)
sys.exit(1)
# Post to each group
for index, (group, md_path, text) in enumerate(tasks):
print(f"\n{'='*60}")
print(f"[{index + 1}/{len(tasks)}] {group} ← {md_path.name}")
print(f"{'='*60}")
if args.dry_run:
print(
f" [DRY RUN] Would send text ({len(text)} chars)"
f" + {len(media)} media file(s)"
)
continue
chat_id = chat_ids[group]
results = send_text_messages(
token, chat_id, text, strict=not args.allow_plain_fallback
)
if results and not results[-1]["ok"]:
desc = results[-1].get("description", "unknown error")
message = f"{group}, text message {len(results)}: {desc}"
resume_at = index
if failed_text_may_have_reached_channel(results):
message += "\nCheck the channel and send only missing parts."
resume_at += 1
abort(message, resume_at)
if any(result.get("_markdown_fallback") for result in results):
print(
f" Warning: {group} was posted WITHOUT formatting.",
file=sys.stderr,
)
if media:
media_result = send_media(token, chat_id, media)
if not media_result["ok"]:
desc = media_result.get("description", "unknown error")
# The text is already published, so resuming this channel would
# duplicate it — only the media needs re-sending by hand.
abort(
f"Media for {group}: {desc}\n"
"The text was posted. Check the channel and send only missing media.",
index + 1,
)
print(f" Done: {group}")
print(f"\n{'='*60}")
if args.dry_run:
print(f"Dry run complete. {len(tasks)} group(s) would be posted to.")
else:
print(f"All {len(tasks)} group(s) posted successfully.")
if __name__ == "__main__":
main()