github-actions[bot] commited on
Commit
ee0695d
Β·
1 Parent(s): ac3902b

Automated sync from GitHub

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
.env.example ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- Telegram -------------------------------------------------------------
2
+ API_ID=
3
+ API_HASH=
4
+ BOT_TOKEN=
5
+ # Numeric Telegram ids (ask @userinfobot). Owners can manage admins in the bot.
6
+ OWNER_IDS=
7
+
8
+ # --- Database -------------------------------------------------------------
9
+ # PostgreSQL, e.g. a free Neon database. Leave empty to use a local SQLite file (data/bot.db).
10
+ DATABASE_URL=postgresql://user:password@host/dbname?sslmode=require
11
+ # "null" = short-lived connections (lets serverless Postgres sleep); "queue" = normal pool for an always-on DB
12
+ DB_POOL=null
13
+
14
+ # --- Optional -------------------------------------------------------------
15
+ # Where the login session is kept. On hosts that wipe files on restart, run `python make_session.py`
16
+ # once and put the printed text in SESSION_STRING instead.
17
+ SESSION_PATH=data/bot
18
+ SESSION_STRING=
19
+ # Seconds between edits during /replace (Telegram rate limits: don't go much lower)
20
+ EDIT_DELAY=1.2
21
+ # Also swap links that are typed as plain text in a post (not only hyperlinks and buttons)
22
+ REPLACE_TYPED_LINKS=true
23
+ # Some free hosts need an open port: set it and the bot answers "ok" on /
24
+ PORT=
25
+ LOG_LEVEL=INFO
.gitattributes CHANGED
@@ -1,34 +1,8 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tflite filter=lfs diff=lfs merge=lfs -text
29
- *.tgz filter=lfs diff=lfs merge=lfs -text
30
- *.wasm filter=lfs diff=lfs merge=lfs -text
31
- *.xz filter=lfs diff=lfs merge=lfs -text
32
- *.zip filter=lfs diff=lfs merge=lfs -text
33
- *.zst filter=lfs diff=lfs merge=lfs -text
34
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.webp filter=lfs diff=lfs merge=lfs -text
2
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
3
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
4
+ *.jpg filter=lfs diff=lfs merge=lfs -text
5
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
6
+ *.png filter=lfs diff=lfs merge=lfs -text
7
+ *.ttf filter=lfs diff=lfs merge=lfs -text
8
+ *.otf filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ .env
2
+ data/*
3
+ !data/.gitkeep
4
+ *.session
5
+ *.session-journal
6
+ __pycache__/
7
+ .pytest_cache/
Dockerfile CHANGED
@@ -1,16 +1,7 @@
1
- FROM python:3.11
2
-
3
- WORKDIR /code
4
-
5
- COPY ./requirements.txt /code/requirements.txt
6
- RUN python3 -m pip install --no-cache-dir --upgrade pip
7
- RUN python3 -m pip install --no-cache-dir --upgrade -r /code/requirements.txt
8
-
9
  COPY . .
10
-
11
- CMD ["panel", "serve", "/code/app.py", "--address", "0.0.0.0", "--port", "7860", "--allow-websocket-origin", "*"]
12
-
13
- RUN mkdir /.cache
14
- RUN chmod 777 /.cache
15
- RUN mkdir .chroma
16
- RUN chmod 777 .chroma
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ ENV PYTHONUNBUFFERED=1
4
+ COPY requirements.txt .
5
+ RUN pip install --no-cache-dir -r requirements.txt
 
 
 
6
  COPY . .
7
+ CMD python -m http.server 7860 & python bot.py
 
 
 
 
 
 
app.py DELETED
@@ -1,147 +0,0 @@
1
- import io
2
- import random
3
- from typing import List, Tuple
4
-
5
- import aiohttp
6
- import panel as pn
7
- from PIL import Image
8
- from transformers import CLIPModel, CLIPProcessor
9
-
10
- pn.extension(design="bootstrap", sizing_mode="stretch_width")
11
-
12
- ICON_URLS = {
13
- "brand-github": "https://github.com/holoviz/panel",
14
- "brand-twitter": "https://twitter.com/Panel_Org",
15
- "brand-linkedin": "https://www.linkedin.com/company/panel-org",
16
- "message-circle": "https://discourse.holoviz.org/",
17
- "brand-discord": "https://discord.gg/AXRHnJU6sP",
18
- }
19
-
20
-
21
- async def random_url(_):
22
- pet = random.choice(["cat", "dog"])
23
- api_url = f"https://api.the{pet}api.com/v1/images/search"
24
- async with aiohttp.ClientSession() as session:
25
- async with session.get(api_url) as resp:
26
- return (await resp.json())[0]["url"]
27
-
28
-
29
- @pn.cache
30
- def load_processor_model(
31
- processor_name: str, model_name: str
32
- ) -> Tuple[CLIPProcessor, CLIPModel]:
33
- processor = CLIPProcessor.from_pretrained(processor_name)
34
- model = CLIPModel.from_pretrained(model_name)
35
- return processor, model
36
-
37
-
38
- async def open_image_url(image_url: str) -> Image:
39
- async with aiohttp.ClientSession() as session:
40
- async with session.get(image_url) as resp:
41
- return Image.open(io.BytesIO(await resp.read()))
42
-
43
-
44
- def get_similarity_scores(class_items: List[str], image: Image) -> List[float]:
45
- processor, model = load_processor_model(
46
- "openai/clip-vit-base-patch32", "openai/clip-vit-base-patch32"
47
- )
48
- inputs = processor(
49
- text=class_items,
50
- images=[image],
51
- return_tensors="pt", # pytorch tensors
52
- )
53
- outputs = model(**inputs)
54
- logits_per_image = outputs.logits_per_image
55
- class_likelihoods = logits_per_image.softmax(dim=1).detach().numpy()
56
- return class_likelihoods[0]
57
-
58
-
59
- async def process_inputs(class_names: List[str], image_url: str):
60
- """
61
- High level function that takes in the user inputs and returns the
62
- classification results as panel objects.
63
- """
64
- try:
65
- main.disabled = True
66
- if not image_url:
67
- yield "##### ⚠️ Provide an image URL"
68
- return
69
-
70
- yield "##### βš™ Fetching image and running model..."
71
- try:
72
- pil_img = await open_image_url(image_url)
73
- img = pn.pane.Image(pil_img, height=400, align="center")
74
- except Exception as e:
75
- yield f"##### πŸ˜” Something went wrong, please try a different URL!"
76
- return
77
-
78
- class_items = class_names.split(",")
79
- class_likelihoods = get_similarity_scores(class_items, pil_img)
80
-
81
- # build the results column
82
- results = pn.Column("##### πŸŽ‰ Here are the results!", img)
83
-
84
- for class_item, class_likelihood in zip(class_items, class_likelihoods):
85
- row_label = pn.widgets.StaticText(
86
- name=class_item.strip(), value=f"{class_likelihood:.2%}", align="center"
87
- )
88
- row_bar = pn.indicators.Progress(
89
- value=int(class_likelihood * 100),
90
- sizing_mode="stretch_width",
91
- bar_color="secondary",
92
- margin=(0, 10),
93
- design=pn.theme.Material,
94
- )
95
- results.append(pn.Column(row_label, row_bar))
96
- yield results
97
- finally:
98
- main.disabled = False
99
-
100
-
101
- # create widgets
102
- randomize_url = pn.widgets.Button(name="Randomize URL", align="end")
103
-
104
- image_url = pn.widgets.TextInput(
105
- name="Image URL to classify",
106
- value=pn.bind(random_url, randomize_url),
107
- )
108
- class_names = pn.widgets.TextInput(
109
- name="Comma separated class names",
110
- placeholder="Enter possible class names, e.g. cat, dog",
111
- value="cat, dog, parrot",
112
- )
113
-
114
- input_widgets = pn.Column(
115
- "##### 😊 Click randomize or paste a URL to start classifying!",
116
- pn.Row(image_url, randomize_url),
117
- class_names,
118
- )
119
-
120
- # add interactivity
121
- interactive_result = pn.panel(
122
- pn.bind(process_inputs, image_url=image_url, class_names=class_names),
123
- height=600,
124
- )
125
-
126
- # add footer
127
- footer_row = pn.Row(pn.Spacer(), align="center")
128
- for icon, url in ICON_URLS.items():
129
- href_button = pn.widgets.Button(icon=icon, width=35, height=35)
130
- href_button.js_on_click(code=f"window.open('{url}')")
131
- footer_row.append(href_button)
132
- footer_row.append(pn.Spacer())
133
-
134
- # create dashboard
135
- main = pn.WidgetBox(
136
- input_widgets,
137
- interactive_result,
138
- footer_row,
139
- )
140
-
141
- title = "Panel Demo - Image Classification"
142
- pn.template.BootstrapTemplate(
143
- title=title,
144
- main=main,
145
- main_max_width="min(50%, 698px)",
146
- header_background="#F08080",
147
- ).servable(title=title)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/__init__.py ADDED
File without changes
app/autopost.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/autopost: the posts of a whole series - "Episodes 01 to 20", "Episodes 21 to 40", ... - each with a download button.
2
+
3
+ The ranges are planned here (pure functions, easy to test); the handler in handlers/autopost.py sends them.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ PLACEHOLDER_LINK = "https://t.me/English" # every button starts with this link; the real ones are asked for afterwards
8
+ MAX_POSTS = 200 # the most one /autopost run may post
9
+ MAX_EPISODES = 100_000
10
+
11
+ USAGE = (
12
+ "Usage: <code>/autopost &lt;total episodes&gt; &lt;interval&gt;</code>\n"
13
+ "Example: <code>/autopost 114 20</code> posts Episodes 01 to 20, 21 to 40 ... up to 114, each with a download "
14
+ "button, and then asks you for the real link of every button."
15
+ )
16
+
17
+
18
+ def parse_autopost_args(raw: str) -> tuple:
19
+ """'114 20' -> (114, 20). ValueError (with a message to show) when it can't be used."""
20
+ parts = (raw or "").replace(",", " ").split()
21
+ if len(parts) != 2 or not all(p.isdigit() for p in parts):
22
+ raise ValueError("I need two numbers: the total number of episodes and the interval.")
23
+ total, interval = int(parts[0]), int(parts[1])
24
+ if total < 1 or interval < 1:
25
+ raise ValueError("Both numbers must be at least 1.")
26
+ if total > MAX_EPISODES:
27
+ raise ValueError(f"The total can be at most {MAX_EPISODES}.")
28
+ return total, interval
29
+
30
+
31
+ def plan_ranges(total: int, interval: int) -> list:
32
+ """[(first, last), ...] covering 1..total in steps of `interval`.
33
+
34
+ The last, shorter range gets its own post when it is longer than half an interval (114 with 20 -> 101 to 114);
35
+ when it is half an interval or less it is added to the post before it (102 with 20 -> 81 to 102)."""
36
+ if total < 1 or interval < 1:
37
+ raise ValueError("total and interval must be at least 1")
38
+ ranges, start = [], 1
39
+ while start <= total:
40
+ end = min(start + interval - 1, total)
41
+ ranges.append((start, end))
42
+ start = end + 1
43
+ if len(ranges) >= 2:
44
+ a, b = ranges[-1]
45
+ size = b - a + 1
46
+ if size < interval and size * 2 <= interval:
47
+ ranges.pop()
48
+ ranges[-1] = (ranges[-1][0], b)
49
+ return ranges
50
+
51
+
52
+ def pad(n: int) -> str:
53
+ return f"{n:02d}"
54
+
55
+
56
+ def span(a: int, b: int) -> str:
57
+ return f"{pad(a)} to {pad(b)}"
58
+
59
+
60
+ def title_of(a: int, b: int) -> str:
61
+ return f"Episodes {span(a, b)}" if a != b else f"Episode {pad(a)}"
62
+
63
+
64
+ def post_text(a: int, b: int) -> str:
65
+ return f"{title_of(a, b)}\n\nClick the button below to download πŸ‘‡"
66
+
67
+
68
+ def button_label(a: int, b: int) -> str:
69
+ return f"Download {title_of(a, b)}"
70
+
71
+
72
+ def post_buttons(a: int, b: int, link: str = PLACEHOLDER_LINK) -> list:
73
+ return [[{"t": button_label(a, b), "u": link}]]
74
+
75
+
76
+ def ranges_summary(ranges: list, show: int = 8) -> str:
77
+ """'01–20 Β· 21–40 Β· 41–60 Β· … Β· 101–114' (the middle is left out of long lists)."""
78
+ parts = [f"{pad(a)}–{pad(b)}" if a != b else pad(a) for a, b in ranges]
79
+ if len(parts) > show:
80
+ parts = parts[: show - 2] + ["…"] + parts[-2:]
81
+ return " Β· ".join(parts)
app/backup.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Putting a backup made by /export back into the bot (/import).
2
+
3
+ The backup is a JSON file: {"exported_at", "channels": [...], "posts": [...], "ignored": [...]}. Importing only ADDS:
4
+
5
+ * a channel the bot already has is left as it is (its title, username and access come from Telegram, which is newer
6
+ than the file); a channel it does not have is added;
7
+ * a post at a message id the bot already has is left as it is; every other published post is added, and so is every
8
+ draft that is not already here;
9
+ * a post the owner has made the bot forget (/posts -> Only forget it in the bot) is not brought back;
10
+ * nothing is ever deleted or overwritten.
11
+
12
+ The file is read as data only: every value is checked before it goes near the database.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ from dataclasses import dataclass, field
19
+ from datetime import datetime, timezone
20
+ from typing import Optional
21
+
22
+ from sqlalchemy import select
23
+ from sqlalchemy.exc import IntegrityError
24
+
25
+ from .db import Channel, Database, IgnoredPost, Post, as_utc, utcnow
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ MAX_BYTES = 40 * 1024 * 1024 # a backup of tens of thousands of posts is a few megabytes
30
+ CHUNK = 500 # rows saved in one go
31
+ POST_KINDS = ("draft", "sent")
32
+ SOURCES = ("bot", "adopted")
33
+
34
+
35
+ class BackupError(ValueError):
36
+ """The file can't be used; the message says why (and is safe to show)."""
37
+
38
+
39
+ # ------------------------------------------------------------------------------------------------ reading
40
+ def _int(value, what: str) -> int:
41
+ if isinstance(value, bool) or not isinstance(value, int):
42
+ raise ValueError(f"{what} is not a whole number")
43
+ return value
44
+
45
+
46
+ def _text(value, what: str, limit: Optional[int] = None) -> str:
47
+ if value is None:
48
+ return ""
49
+ if not isinstance(value, str):
50
+ raise ValueError(f"{what} is not text")
51
+ return value[:limit] if limit else value
52
+
53
+
54
+ def _when(value, what: str, default: Optional[datetime] = None) -> Optional[datetime]:
55
+ if value in (None, ""):
56
+ return default
57
+ if not isinstance(value, str):
58
+ raise ValueError(f"{what} is not a date")
59
+ try:
60
+ d = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
61
+ except ValueError:
62
+ raise ValueError(f"{what} is not a date")
63
+ return as_utc(d)
64
+
65
+
66
+ def _rows_of(value, what: str) -> list:
67
+ if value is None:
68
+ return []
69
+ if not isinstance(value, list):
70
+ raise BackupError(f"β€œ{what}” should be a list.")
71
+ return value
72
+
73
+
74
+ def channel_row(row) -> dict:
75
+ """One channel of the file as the values for a Channel row (ValueError if it is not usable)."""
76
+ if not isinstance(row, dict):
77
+ raise ValueError("not an object")
78
+ cid = _int(row.get("id"), "id")
79
+ if cid == 0:
80
+ raise ValueError("id is 0")
81
+ username = _text(row.get("username"), "username", 64).strip().lstrip("@") or None
82
+ created = _when(row.get("created_at"), "created_at", utcnow())
83
+ return dict(
84
+ id=cid,
85
+ access_hash=_int(row.get("access_hash", 0) or 0, "access_hash"),
86
+ title=_text(row.get("title"), "title", 256),
87
+ username=username,
88
+ active=bool(row.get("active", True)),
89
+ added_by=_int(row.get("added_by", 0) or 0, "added_by"),
90
+ created_at=created,
91
+ )
92
+
93
+
94
+ def _buttons(value) -> list:
95
+ if value is None:
96
+ return []
97
+ if not isinstance(value, list):
98
+ raise ValueError("buttons are not a list")
99
+ for line in value:
100
+ if not isinstance(line, list) or not all(isinstance(b, dict) for b in line):
101
+ raise ValueError("buttons are not rows of buttons")
102
+ return value
103
+
104
+
105
+ def _entities(value) -> list:
106
+ if value is None:
107
+ return []
108
+ if not isinstance(value, list) or not all(isinstance(e, dict) for e in value):
109
+ raise ValueError("formatting is not a list")
110
+ return value
111
+
112
+
113
+ def post_row(row) -> dict:
114
+ """One post of the file as the values for a Post row (ValueError if it is not usable)."""
115
+ if not isinstance(row, dict):
116
+ raise ValueError("not an object")
117
+ cid = _int(row.get("channel_id"), "channel_id")
118
+ mid = row.get("message_id")
119
+ mid = None if mid is None else _int(mid, "message_id")
120
+ status = row.get("status") or ("sent" if mid else "draft")
121
+ if status not in POST_KINDS:
122
+ raise ValueError(f"status β€œ{str(status)[:20]}” is unknown")
123
+ if status == "sent" and (mid is None or mid < 1):
124
+ raise ValueError("a published post without a message id")
125
+ if status == "draft":
126
+ mid = None
127
+ source = row.get("source") if row.get("source") in SOURCES else "bot"
128
+ kind = row.get("media_kind")
129
+ if kind is not None and (not isinstance(kind, str) or len(kind) > 16):
130
+ raise ValueError("media_kind is not usable")
131
+ ref = row.get("media_file_id")
132
+ if ref is not None and not isinstance(ref, str):
133
+ raise ValueError("media_file_id is not text")
134
+ created = _when(row.get("created_at"), "created_at", utcnow())
135
+ return dict(
136
+ channel_id=cid,
137
+ message_id=mid,
138
+ status=status,
139
+ source=source,
140
+ text=_text(row.get("text"), "text"),
141
+ entities=_entities(row.get("entities")),
142
+ media_kind=kind or None,
143
+ media_file_id=ref or None,
144
+ buttons=_buttons(row.get("buttons")),
145
+ link_preview=bool(row.get("link_preview")),
146
+ created_by=_int(row.get("created_by", 0) or 0, "created_by"),
147
+ created_at=created,
148
+ updated_at=_when(row.get("updated_at"), "updated_at", created),
149
+ sent_at=_when(row.get("sent_at"), "sent_at"),
150
+ )
151
+
152
+
153
+ @dataclass
154
+ class Backup:
155
+ exported_at: Optional[str] = None
156
+ channels: list = field(default_factory=list) # dicts for Channel(**d)
157
+ posts: list = field(default_factory=list) # dicts for Post(**d)
158
+ ignored: list = field(default_factory=list) # (channel id, message id)
159
+ bad_rows: int = 0 # entries of the file that were not usable and are left out
160
+
161
+
162
+ def parse_backup(raw: bytes) -> Backup:
163
+ """The file's bytes -> a Backup. BackupError (with a message for the person) when it is not an /export file."""
164
+ if len(raw) > MAX_BYTES:
165
+ raise BackupError(f"it is larger than {MAX_BYTES // (1024 * 1024)} MB.")
166
+ try:
167
+ data = json.loads(raw.decode("utf-8-sig"))
168
+ except (UnicodeDecodeError, ValueError):
169
+ raise BackupError("it is not a JSON file. Send the file that /export made, unchanged.")
170
+ if not isinstance(data, dict) or ("channels" not in data and "posts" not in data):
171
+ raise BackupError("it does not look like a backup from /export (no channels and posts in it).")
172
+ bk = Backup(exported_at=data.get("exported_at") if isinstance(data.get("exported_at"), str) else None)
173
+ for row in _rows_of(data.get("channels"), "channels"):
174
+ try:
175
+ bk.channels.append(channel_row(row))
176
+ except (ValueError, TypeError):
177
+ bk.bad_rows += 1
178
+ for row in _rows_of(data.get("posts"), "posts"):
179
+ try:
180
+ bk.posts.append(post_row(row))
181
+ except (ValueError, TypeError):
182
+ bk.bad_rows += 1
183
+ for row in _rows_of(data.get("ignored"), "ignored"):
184
+ try:
185
+ if not isinstance(row, dict):
186
+ raise ValueError("not an object")
187
+ bk.ignored.append((_int(row.get("channel_id"), "channel_id"), _int(row.get("message_id"), "message_id")))
188
+ except (ValueError, TypeError):
189
+ bk.bad_rows += 1
190
+ if not (bk.channels or bk.posts):
191
+ raise BackupError("there is nothing in it that can be imported." + (" (All entries were unreadable.)" if bk.bad_rows else ""))
192
+ return bk
193
+
194
+
195
+ # ------------------------------------------------------------------------------------------------ the plan
196
+ @dataclass
197
+ class ImportPlan:
198
+ backup: Backup
199
+ new_channels: list = field(default_factory=list) # channel dicts that are not in the bot yet
200
+ channels_present: int = 0 # channels of the file the bot has already (left as they are)
201
+ new_posts: list = field(default_factory=list) # published posts and drafts to add
202
+ posts_present: int = 0 # published posts at a message id the bot already has
203
+ drafts_present: int = 0 # drafts that are here already
204
+ posts_forgotten: int = 0 # posts the owner made the bot forget: not brought back
205
+ posts_orphaned: int = 0 # posts of a channel that is neither in the bot nor in the file
206
+ new_ignored: list = field(default_factory=list) # "forgotten" marks to add
207
+
208
+ @property
209
+ def sent_to_add(self) -> int:
210
+ return sum(1 for p in self.new_posts if p["status"] == "sent")
211
+
212
+ @property
213
+ def drafts_to_add(self) -> int:
214
+ return sum(1 for p in self.new_posts if p["status"] == "draft")
215
+
216
+ @property
217
+ def nothing_new(self) -> bool:
218
+ return not (self.new_channels or self.new_posts or self.new_ignored)
219
+
220
+
221
+ async def plan_import(db: Database, backup: Backup) -> ImportPlan:
222
+ """What importing would do - nothing is written."""
223
+ plan = ImportPlan(backup=backup)
224
+ async with db.Session() as s:
225
+ have_channels = {int(c) for c in (await s.execute(select(Channel.id))).scalars()}
226
+ known_marks = {(int(c), int(m)) for c, m in (await s.execute(select(IgnoredPost.channel_id, IgnoredPost.message_id))).all()}
227
+ wanted = {p["channel_id"] for p in backup.posts}
228
+ have_posts: set = set()
229
+ have_drafts: set = set()
230
+ if wanted:
231
+ q = select(Post.channel_id, Post.message_id).where(Post.message_id.is_not(None))
232
+ have_posts = {(int(c), int(m)) for c, m in (await s.execute(q)).all() if int(c) in wanted}
233
+ q = select(Post.channel_id, Post.text, Post.created_at).where(Post.status == "draft")
234
+ have_drafts = {(int(c), t, as_utc(at)) for c, t, at in (await s.execute(q)).all() if int(c) in wanted}
235
+ in_file: dict = {}
236
+ for ch in backup.channels:
237
+ if ch["id"] in have_channels:
238
+ plan.channels_present += 1
239
+ elif ch["id"] not in in_file:
240
+ in_file[ch["id"]] = ch
241
+ plan.new_channels.append(ch)
242
+ marks = set(known_marks)
243
+ for mark in backup.ignored:
244
+ if mark[0] in have_channels or mark[0] in in_file:
245
+ if mark not in marks:
246
+ marks.add(mark)
247
+ plan.new_ignored.append(mark)
248
+ seen_posts: set = set()
249
+ seen_drafts: set = set()
250
+ for p in backup.posts:
251
+ cid = p["channel_id"]
252
+ if cid not in have_channels and cid not in in_file:
253
+ plan.posts_orphaned += 1
254
+ elif p["status"] == "sent":
255
+ key = (cid, p["message_id"])
256
+ if key in marks:
257
+ plan.posts_forgotten += 1
258
+ elif key in have_posts or key in seen_posts:
259
+ plan.posts_present += 1
260
+ else:
261
+ seen_posts.add(key)
262
+ plan.new_posts.append(p)
263
+ else:
264
+ key = (cid, p["text"], p["created_at"])
265
+ if key in have_drafts or key in seen_drafts:
266
+ plan.drafts_present += 1
267
+ else:
268
+ seen_drafts.add(key)
269
+ plan.new_posts.append(p)
270
+ return plan
271
+
272
+
273
+ # ----------------------------------------------------------------------------------------------- doing it
274
+ @dataclass
275
+ class ImportResult:
276
+ channels_added: int = 0
277
+ posts_added: int = 0
278
+ drafts_added: int = 0
279
+ marks_added: int = 0
280
+ skipped_meanwhile: int = 0 # posts that turned up in the bot while the import was running
281
+
282
+
283
+ async def _save_posts(db: Database, rows: list) -> list:
284
+ """Save these posts; returns the ones that were saved (one that is there already is skipped, never an error)."""
285
+ async with db.Session() as s:
286
+ s.add_all([Post(**r) for r in rows])
287
+ try:
288
+ await s.commit()
289
+ return list(rows)
290
+ except IntegrityError:
291
+ await s.rollback()
292
+ saved = []
293
+ for r in rows: # one is there already: one by one
294
+ async with db.Session() as s:
295
+ s.add(Post(**r))
296
+ try:
297
+ await s.commit()
298
+ saved.append(r)
299
+ except IntegrityError:
300
+ await s.rollback()
301
+ return saved
302
+
303
+
304
+ async def apply_import(db: Database, plan: ImportPlan, progress=None) -> ImportResult:
305
+ """Write the plan: channels first (posts point at them), then the posts in pieces, then the "forgotten" marks."""
306
+ res = ImportResult()
307
+ if plan.new_channels:
308
+ async with db.Session() as s:
309
+ for d in plan.new_channels:
310
+ if await s.get(Channel, d["id"]) is None:
311
+ s.add(Channel(**d))
312
+ res.channels_added += 1
313
+ await s.commit()
314
+ rows = plan.new_posts
315
+ for i in range(0, len(rows), CHUNK):
316
+ part = rows[i : i + CHUNK]
317
+ saved = await _save_posts(db, part)
318
+ res.posts_added += sum(1 for r in saved if r["status"] == "sent")
319
+ res.drafts_added += sum(1 for r in saved if r["status"] == "draft")
320
+ res.skipped_meanwhile += len(part) - len(saved)
321
+ if progress is not None:
322
+ await progress(min(i + CHUNK, len(rows)), len(rows))
323
+ for cid, mid in plan.new_ignored:
324
+ await db.ignore_post(cid, mid)
325
+ res.marks_added += 1
326
+ return res
327
+
328
+
329
+ def stamp(iso: Optional[str]) -> str:
330
+ """'2026-10-07T10:00:00+00:00' -> '07 Oct 2026, 10:00 UTC' (the text as it is when it can't be read)."""
331
+ if not iso:
332
+ return ""
333
+ try:
334
+ d = as_utc(datetime.fromisoformat(iso.replace("Z", "+00:00")))
335
+ except ValueError:
336
+ return iso[:40]
337
+ return d.astimezone(timezone.utc).strftime("%d %b %Y, %H:%M UTC")
app/buttons.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Button model: rows of {'t': text, 'u': url} (URL buttons) or {'t', 'raw'} (other bots' buttons, kept as-is)."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Optional
6
+
7
+ MAX_ROW = 8
8
+ MAX_TOTAL = 100
9
+ _URL_RX = re.compile(r"(?:https?://|tg://|t\.me/|telegram\.me/)\S+", re.I)
10
+
11
+
12
+ def norm_url(u: str) -> Optional[str]:
13
+ u = (u or "").strip()
14
+ if re.match(r"(?i)^(t\.me|telegram\.me)/", u):
15
+ u = "https://" + u
16
+ if not re.match(r"(?i)^(https?://|tg://)\S+$", u) or len(u) > 2000:
17
+ return None
18
+ return u
19
+
20
+
21
+ def parse_buttons_text(text: str) -> list:
22
+ """One row per line, 'Text - link'. Several buttons in a row: separate them with ' | '."""
23
+ rows: list = []
24
+ total = 0
25
+ for line in (text or "").strip().splitlines():
26
+ line = line.strip()
27
+ if not line:
28
+ continue
29
+ row = []
30
+ for part in re.split(r"\s+\|\s+|\s*&&\s*", line):
31
+ part = part.strip()
32
+ if not part:
33
+ continue
34
+ found = list(_URL_RX.finditer(part))
35
+ if not found:
36
+ raise ValueError(f"No link found in: {part}")
37
+ m = found[-1]
38
+ label = part[: m.start()].strip().rstrip("-–—:|=").strip()
39
+ if not label:
40
+ raise ValueError(f"No button text before the link in: {part}")
41
+ url = norm_url(m.group(0))
42
+ if not url:
43
+ raise ValueError(f"That link doesn't look valid: {m.group(0)}")
44
+ row.append({"t": label, "u": url})
45
+ if len(row) > MAX_ROW:
46
+ raise ValueError(f"At most {MAX_ROW} buttons fit in one row.")
47
+ if row:
48
+ rows.append(row)
49
+ total += len(row)
50
+ if total > MAX_TOTAL:
51
+ raise ValueError(f"At most {MAX_TOTAL} buttons per post.")
52
+ return rows
53
+
54
+
55
+ def copy_rows(rows: list) -> list:
56
+ return [[dict(b) for b in row] for row in (rows or [])]
57
+
58
+
59
+ def count(rows: list) -> int:
60
+ return sum(len(r) for r in rows or [])
61
+
62
+
63
+ def missing_links(rows: list) -> int:
64
+ return sum(1 for r in rows or [] for b in r if not b.get("u") and not b.get("raw"))
65
+
66
+
67
+ def link_positions(rows: list) -> list:
68
+ """(row, column) of every button that has a link of its own. Other bots' buttons (reactions...) are left out:
69
+ they can't be edited."""
70
+ return [(r, c) for r, row in enumerate(rows or []) for c, b in enumerate(row) if b.get("u") and not b.get("raw")]
71
+
72
+
73
+ def valid(rows: list, r: int, c: int) -> bool:
74
+ return 0 <= r < len(rows) and 0 <= c < len(rows[r])
75
+
76
+
77
+ def add_button(rows: list, btn: dict, new_row: bool = True) -> list:
78
+ rows = copy_rows(rows)
79
+ if new_row or not rows or len(rows[-1]) >= MAX_ROW:
80
+ rows.append([btn])
81
+ else:
82
+ rows[-1].append(btn)
83
+ return rows
84
+
85
+
86
+ def set_field(rows: list, r: int, c: int, **fields) -> list:
87
+ rows = copy_rows(rows)
88
+ if valid(rows, r, c):
89
+ rows[r][c].update(fields)
90
+ return rows
91
+
92
+
93
+ def delete_button(rows: list, r: int, c: int) -> list:
94
+ rows = copy_rows(rows)
95
+ if valid(rows, r, c):
96
+ rows[r].pop(c)
97
+ rows = [row for row in rows if row]
98
+ return rows
99
+
100
+
101
+ def move_button(rows: list, r: int, c: int, direction: str) -> tuple:
102
+ """direction: l | r | u | d. Returns (rows, new_r, new_c)."""
103
+ rows = copy_rows(rows)
104
+ if not valid(rows, r, c):
105
+ return rows, r, c
106
+ b = rows[r][c]
107
+ if direction == "l":
108
+ if c > 0:
109
+ rows[r][c - 1], rows[r][c] = rows[r][c], rows[r][c - 1]
110
+ c -= 1
111
+ elif direction == "r":
112
+ if c < len(rows[r]) - 1:
113
+ rows[r][c + 1], rows[r][c] = rows[r][c], rows[r][c + 1]
114
+ c += 1
115
+ elif direction == "u":
116
+ if r > 0 and len(rows[r - 1]) < MAX_ROW:
117
+ rows[r].pop(c)
118
+ pos = min(c, len(rows[r - 1]))
119
+ rows[r - 1].insert(pos, b)
120
+ nr, nc = r - 1, pos
121
+ if not rows[r]:
122
+ rows.pop(r)
123
+ r, c = nr, nc
124
+ elif direction == "d":
125
+ if r < len(rows) - 1:
126
+ if len(rows[r + 1]) < MAX_ROW:
127
+ rows[r].pop(c)
128
+ pos = min(c, len(rows[r + 1]))
129
+ rows[r + 1].insert(pos, b)
130
+ nr, nc = r + 1, pos
131
+ if not rows[r]:
132
+ rows.pop(r)
133
+ nr -= 1
134
+ r, c = nr, nc
135
+ elif len(rows[r]) > 1: # last row with company: split off into a new row below
136
+ rows[r].pop(c)
137
+ rows.append([b])
138
+ r, c = len(rows) - 1, 0
139
+ return rows, r, c
140
+
141
+
142
+ def grid_label(b: dict) -> str:
143
+ t = (b.get("t") or "").strip() or "…"
144
+ if len(t) > 26:
145
+ t = t[:25] + "…"
146
+ if b.get("raw"):
147
+ return "πŸ”’ " + t
148
+ if not b.get("u"):
149
+ return "⚠️ " + t
150
+ return t
app/buttons_sync.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Make sure the buttons shown in a channel are the ones we saved - and fix them when they are not.
2
+
3
+ Used by /repost (every new post is read back right after it is created) and by "Check buttons" in My posts,
4
+ which repairs posts whose buttons are saved in the bot but are missing in the channel.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import logging
10
+ from dataclasses import dataclass, field
11
+ from typing import Awaitable, Callable, Optional
12
+
13
+ from telethon import errors, types
14
+
15
+ from .replace_engine import CHUNK, fetch_messages, is_skippable
16
+ from .tgutil import build_markup, button_url, edit_raw, flood_retry, peer_of
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+ ABORT_AFTER = 5 # stop repairing after this many failures in a row
21
+ # A throw-away keyboard. If Telegram answers "message not modified" to the real keyboard (it believes the post
22
+ # already has it), we first show this one, then the real one: two real changes.
23
+ NUDGE_ROWS = [[{"t": "…", "u": "https://t.me/telegram"}]]
24
+
25
+
26
+ class ButtonsNotShown(RuntimeError):
27
+ """Telegram accepted the edit, but the post still does not show the buttons it should."""
28
+
29
+
30
+ def link_buttons(markup) -> list:
31
+ """[(text, url)] of the link buttons of a keyboard, in reading order."""
32
+ out: list = []
33
+ if isinstance(markup, types.ReplyInlineMarkup):
34
+ for row in markup.rows:
35
+ for b in row.buttons:
36
+ u = button_url(b)
37
+ if u is not None:
38
+ out.append((getattr(b, "text", ""), u))
39
+ return out
40
+
41
+
42
+ def link_urls(markup) -> list:
43
+ return [u for _, u in link_buttons(markup)]
44
+
45
+
46
+ async def live_urls(client, peer, message_id: int) -> Optional[list]:
47
+ """The link-button URLs the channel shows on a post right now; None if the post is gone."""
48
+ msgs = await fetch_messages(client, peer, [message_id])
49
+ m = msgs[0] if msgs else None
50
+ if is_skippable(m):
51
+ return None
52
+ return link_urls(m.reply_markup)
53
+
54
+
55
+ async def ensure_markup(client, peer, message_id: int, markup, *, pause: float = 0.7) -> str:
56
+ """Make post `message_id` show the link buttons of `markup`, and check it by reading the post back.
57
+
58
+ Returns "fine" (it already did), "set" (one edit was enough) or "nudged" (needed the two-step edit).
59
+ Raises ButtonsNotShown if the buttons still are not there, LookupError if the post no longer exists.
60
+ """
61
+ want = link_urls(markup)
62
+ if not want:
63
+ return "fine"
64
+ live = await live_urls(client, peer, message_id)
65
+ if live is None:
66
+ raise LookupError(f"post {message_id} no longer exists")
67
+ if live == want:
68
+ return "fine"
69
+
70
+ try:
71
+ await flood_retry(lambda: edit_raw(client, peer, message_id, markup=markup))
72
+ except errors.MessageNotModifiedError:
73
+ pass # Telegram thinks the keyboard is already there - checked below
74
+ if pause:
75
+ await asyncio.sleep(pause)
76
+ if await live_urls(client, peer, message_id) == want:
77
+ return "set"
78
+
79
+ log.info("post %s: the edit did not make the buttons show - trying the two-step edit", message_id)
80
+ for step in (build_markup(NUDGE_ROWS), markup):
81
+ try:
82
+ await flood_retry(lambda step=step: edit_raw(client, peer, message_id, markup=step))
83
+ except errors.MessageNotModifiedError:
84
+ pass
85
+ if pause:
86
+ await asyncio.sleep(pause)
87
+ if await live_urls(client, peer, message_id) == want:
88
+ return "nudged"
89
+ raise ButtonsNotShown(f"post {message_id} still does not show its buttons")
90
+
91
+
92
+ # ------------------------------------------------------------------------------------ checking
93
+ @dataclass
94
+ class ButtonScan:
95
+ channel: object
96
+ total: int = 0 # saved posts that have link buttons
97
+ fine: int = 0
98
+ bad: list = field(default_factory=list) # [(post, live urls, wanted urls)]
99
+ gone: list = field(default_factory=list) # posts that no longer exist in the channel
100
+
101
+
102
+ async def scan_buttons(
103
+ client, ch, posts: list, *, progress: Optional[Callable[[ButtonScan], Awaitable[None]]] = None
104
+ ) -> ButtonScan:
105
+ """Compare the saved link buttons of `posts` with what the channel shows."""
106
+ scan = ButtonScan(channel=ch)
107
+ peer = peer_of(ch)
108
+ wanted = []
109
+ for p in posts:
110
+ if not p.message_id:
111
+ continue
112
+ urls = link_urls(build_markup(p.buttons))
113
+ if urls:
114
+ wanted.append((p, urls))
115
+ scan.total = len(wanted)
116
+ for i in range(0, len(wanted), CHUNK):
117
+ part = wanted[i : i + CHUNK]
118
+ msgs = await fetch_messages(client, peer, [p.message_id for p, _ in part])
119
+ for (p, urls), m in zip(part, msgs):
120
+ if is_skippable(m):
121
+ scan.gone.append(p)
122
+ elif link_urls(m.reply_markup) == urls:
123
+ scan.fine += 1
124
+ else:
125
+ scan.bad.append((p, link_urls(m.reply_markup), urls))
126
+ if progress:
127
+ await progress(scan)
128
+ return scan
129
+
130
+
131
+ @dataclass
132
+ class FixResult:
133
+ fixed: int = 0
134
+ nudged: int = 0 # of those, how many needed the two-step edit
135
+ already: int = 0 # turned out to be fine when looked at again
136
+ gone: int = 0
137
+ failed: list = field(default_factory=list) # [(message id, error name)]
138
+ aborted: Optional[str] = None
139
+ stopped: bool = False
140
+
141
+
142
+ async def fix_buttons(
143
+ client,
144
+ ch,
145
+ bad: list,
146
+ *,
147
+ delay: float = 1.2,
148
+ pause: float = 0.7,
149
+ progress: Optional[Callable[[FixResult], Awaitable[None]]] = None,
150
+ should_stop: Optional[Callable[[], bool]] = None,
151
+ ) -> FixResult:
152
+ """Put the saved buttons back on the posts in `bad` (the first item of each entry is the saved post)."""
153
+ res = FixResult()
154
+ peer = peer_of(ch)
155
+ streak = 0
156
+ for entry in bad:
157
+ post = entry[0]
158
+ if should_stop and should_stop():
159
+ res.stopped = True
160
+ break
161
+ try:
162
+ how = await ensure_markup(client, peer, post.message_id, build_markup(post.buttons), pause=pause)
163
+ except LookupError:
164
+ res.gone += 1
165
+ continue
166
+ except Exception as e: # one bad post must not stop the others
167
+ name = type(e).__name__
168
+ log.warning("could not fix the buttons of %s: %s %s", post.message_id, name, e)
169
+ res.failed.append((post.message_id, name))
170
+ streak += 1
171
+ if streak >= ABORT_AFTER:
172
+ res.aborted = name
173
+ break
174
+ await asyncio.sleep(delay)
175
+ continue
176
+ streak = 0
177
+ if how == "fine":
178
+ res.already += 1
179
+ else:
180
+ res.fixed += 1
181
+ if how == "nudged":
182
+ res.nudged += 1
183
+ if progress:
184
+ await progress(res)
185
+ await asyncio.sleep(delay)
186
+ return res
app/channelref.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Find a channel from what a person types: @username, t.me link, numeric id (-100...), or an invite link.
2
+
3
+ Used by /shift. The bot can only talk to a channel it can see: registered channels (the database has their access
4
+ details), channels it has met in updates, public channels by @username, and channels it is a member of (invite link).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from dataclasses import dataclass
10
+ from typing import Optional
11
+
12
+ from telethon import functions, types
13
+
14
+ from .common import Ctx, UserError
15
+
16
+ _REF_RX = re.compile(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me)/(?:c/(\d+)|([A-Za-z0-9_]{3,32}))(?:/\d+)?/?$")
17
+ _INVITE_RX = re.compile(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me|telegram\.dog)/(?:\+|joinchat/)([A-Za-z0-9_-]{6,})/?$")
18
+ _TG_INVITE_RX = re.compile(r"(?i)^tg://join\?invite=([A-Za-z0-9_-]{6,})$")
19
+
20
+
21
+ def parse_channel_ref(text: str):
22
+ """@name / t.me link / numeric id -> username (str) or channel id (int); None if unrecognised."""
23
+ t = (text or "").strip()
24
+ m = _REF_RX.match(t)
25
+ if m:
26
+ return int(m.group(1)) if m.group(1) else m.group(2)
27
+ t = t.lstrip("@")
28
+ if re.fullmatch(r"-?\d+", t):
29
+ s = str(abs(int(t)))
30
+ return int(s[3:]) if s.startswith("100") and len(s) > 10 else int(s)
31
+ if re.fullmatch(r"[A-Za-z0-9_]{3,32}", t):
32
+ return t
33
+ return None
34
+
35
+
36
+ def classify_ref(text: str) -> tuple:
37
+ """-> ("invite", hash) | ("username", name) | ("id", int) | (None, None)"""
38
+ t = (text or "").strip()
39
+ m = _INVITE_RX.match(t) or _TG_INVITE_RX.match(t)
40
+ if m:
41
+ return "invite", m.group(1)
42
+ ref = parse_channel_ref(t)
43
+ if isinstance(ref, int):
44
+ return "id", ref
45
+ if isinstance(ref, str):
46
+ return "username", ref
47
+ return None, None
48
+
49
+
50
+ @dataclass
51
+ class ChannelRef:
52
+ """A channel as the bot can reach it."""
53
+
54
+ id: int
55
+ access_hash: int
56
+ title: str
57
+ username: Optional[str]
58
+ registered: bool # the bot's database knows it (it can be used with /new, /posts ...)
59
+
60
+
61
+ def _from_entity(ent, registered: bool) -> ChannelRef:
62
+ if not isinstance(ent, types.Channel):
63
+ raise UserError("That is not a channel (it looks like a user, bot or group). Only channels can be used here.")
64
+ if not ent.broadcast:
65
+ raise UserError("That is a group, not a channel. Only channels can be used here.")
66
+ if not ent.access_hash or getattr(ent, "min", False):
67
+ raise UserError(
68
+ "I can see that channel, but Telegram has not given me its access details. Use its @username, or add the "
69
+ "bot to the channel as an admin and post something there first."
70
+ )
71
+ return ChannelRef(ent.id, ent.access_hash, ent.title or "", ent.username, registered)
72
+
73
+
74
+ async def _entity(client, what):
75
+ try:
76
+ return await client.get_entity(what)
77
+ except Exception:
78
+ return None
79
+
80
+
81
+ async def resolve_channel(ctx: Ctx, text: str) -> ChannelRef:
82
+ """The channel `text` points at, or a UserError that says what to do."""
83
+ kind, value = classify_ref(text)
84
+ if kind is None:
85
+ raise UserError(
86
+ f"β€œ{text}” is not a channel I understand. Use an @username, a t.me link, the channel id (-100…) or an invite link."
87
+ )
88
+ db, client = ctx.db, ctx.client
89
+ if kind == "username":
90
+ for ch in await db.list_channels(active_only=False):
91
+ if ch.username and ch.username.lower() == value.lower():
92
+ return ChannelRef(ch.id, ch.access_hash, ch.title, ch.username, ch.active)
93
+ ent = await _entity(client, value)
94
+ if ent is None:
95
+ raise UserError(f"I couldn't find a channel called @{value}. Check the name, or add the bot to it as an admin.")
96
+ elif kind == "id":
97
+ ch = await db.get_channel(value)
98
+ if ch is not None:
99
+ return ChannelRef(ch.id, ch.access_hash, ch.title, ch.username, ch.active)
100
+ ent = ctx.seen_channels.get(value) or await _entity(client, types.PeerChannel(value))
101
+ if ent is None:
102
+ raise UserError(
103
+ f"I don't know a channel with the id {value}. A bot can only use an id for channels it is part of; "
104
+ "use the @username instead, or add the bot to the channel as an admin."
105
+ )
106
+ else: # invite link: only tells which channel it is; the bot cannot join by itself
107
+ try:
108
+ info = await client(functions.messages.CheckChatInviteRequest(hash=value))
109
+ except Exception as e:
110
+ raise UserError(f"That invite link doesn't work ({type(e).__name__}).")
111
+ chat = getattr(info, "chat", None)
112
+ if chat is None:
113
+ raise UserError(
114
+ "The bot is not a member of that channel, so it cannot use that invite link. Add the bot to the channel "
115
+ "as an admin first (a bot cannot join by itself)."
116
+ )
117
+ ent = chat
118
+ known = await db.get_channel(getattr(ent, "id", 0))
119
+ return _from_entity(ent, known is not None and known.active)
app/common.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared context, permission guard, message helpers and post send/edit operations."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import functools
6
+ import logging
7
+ import shutil
8
+ import tempfile
9
+ import time
10
+ from dataclasses import dataclass, field
11
+ from types import SimpleNamespace
12
+ from typing import Any, Callable, Optional
13
+
14
+ from telethon import TelegramClient, errors, events
15
+
16
+ from .buttons_sync import ensure_markup, link_urls
17
+ from .config import Config
18
+ from .db import Database
19
+ from .replace_engine import fetch_messages, is_skippable
20
+ from .richmsg import rich_of, send_rich, with_rich
21
+ from .tgutil import build_markup, de_entities, edit_raw, esc, explain_rpc, fetch_media, media_info, peer_of, with_media
22
+ from .userbot import UserbotError, UserbotRefused, edit_problem_text
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+
27
+ class UserError(Exception):
28
+ """An error whose message is safe and useful to show to the user."""
29
+
30
+
31
+ @dataclass
32
+ class Ctx:
33
+ cfg: Config
34
+ db: Database
35
+ client: TelegramClient
36
+ admins: set = field(default_factory=set)
37
+ state: dict = field(default_factory=dict) # user id -> {"mode": ..., ...}
38
+ pending: dict = field(default_factory=dict) # tokens for confirm dialogs (replace, repost)
39
+ seen_channels: dict = field(default_factory=dict) # channel id -> Channel entity seen in updates
40
+ text_handlers: dict = field(default_factory=dict) # mode -> async fn(event, state)
41
+ callbacks: dict = field(default_factory=dict) # prefix -> async fn(event, parts)
42
+ pickers: dict = field(default_factory=dict) # channel chooser kind -> async fn(event, arg, page) that draws it again
43
+ lock: asyncio.Lock = field(default_factory=asyncio.Lock) # one long job (replace / repost) at a time
44
+ userbot: Any = None # app.userbot.Userbot or None
45
+ reporter: Any = None # app.errorlog.ErrorReporter or None
46
+ expirer: Any = None # app.expiry.Expirer (timed deletions of broadcasts) or None
47
+ syncer: Any = None # app.syncer.Syncer (keeps My posts in step with the channels) or None
48
+ sync_ignore: set = field(default_factory=set) # (channel id, message id) of posts the owner made the bot forget
49
+
50
+
51
+ def is_cb(event) -> bool:
52
+ return isinstance(event, events.CallbackQuery.Event) or getattr(event, "_is_callback", False)
53
+
54
+
55
+ def guard(ctx: Ctx, owner: bool = False) -> Callable:
56
+ """Only allowed users may use a handler; errors are turned into friendly messages."""
57
+
58
+ def deco(fn):
59
+ @functools.wraps(fn)
60
+ async def wrapper(event):
61
+ uid = event.sender_id
62
+ ok = ctx.cfg.is_owner(uid) if owner else (ctx.cfg.is_owner(uid) or uid in ctx.admins or uid in ctx.cfg.admins)
63
+ if not ok:
64
+ try:
65
+ if is_cb(event):
66
+ await event.answer("Not allowed.", alert=True)
67
+ elif getattr(event, "is_private", False):
68
+ await event.respond("β›” This bot is private.")
69
+ except Exception:
70
+ pass
71
+ return
72
+ try:
73
+ await fn(event)
74
+ except events.StopPropagation:
75
+ raise
76
+ except errors.MessageNotModifiedError:
77
+ if is_cb(event):
78
+ try:
79
+ await event.answer()
80
+ except Exception:
81
+ pass
82
+ except UserError as e:
83
+ await notify_error(event, str(e))
84
+ except errors.RPCError as e:
85
+ log.error("Telegram refused a request in handler %s (user %s)", fn.__name__, uid, exc_info=True)
86
+ await notify_error(event, "❌ " + explain_rpc(e))
87
+ except Exception as e:
88
+ log.exception("Unhandled exception in handler %s (user %s)", fn.__name__, uid)
89
+ await notify_error(event, f"⚠️ Something went wrong: {type(e).__name__}: {str(e)[:200]}")
90
+
91
+ return wrapper
92
+
93
+ return deco
94
+
95
+
96
+ async def notify_error(event, text: str) -> None:
97
+ try:
98
+ if is_cb(event):
99
+ try:
100
+ await event.answer("That didn't work - see the message below.", alert=False)
101
+ except Exception:
102
+ pass
103
+ await event.respond(esc(text), link_preview=False)
104
+ except Exception: # pragma: no cover
105
+ log.exception("could not report an error")
106
+
107
+
108
+ async def say(event, text: str, buttons=None):
109
+ return await event.respond(text, buttons=buttons, link_preview=False)
110
+
111
+
112
+ async def edit_callback_message(event, text: str, buttons=None):
113
+ """Edit the message a button was pressed on.
114
+
115
+ Telethon's CallbackQuery.edit() quietly starts a second `answer` task; the dispatcher has already
116
+ answered the query, so we call edit_message directly instead.
117
+ """
118
+ query = getattr(event, "query", None)
119
+ if query is not None and hasattr(event, "client"):
120
+ return await event.client.edit_message(
121
+ await event.get_input_chat(), query.msg_id, text, buttons=buttons, link_preview=False
122
+ )
123
+ return await event.edit(text, buttons=buttons, link_preview=False) # test doubles
124
+
125
+
126
+ async def show(event, text: str, buttons=None):
127
+ """Edit the message a button was pressed on; for normal messages send a new one."""
128
+ if is_cb(event):
129
+ try:
130
+ return await edit_callback_message(event, text, buttons)
131
+ except errors.MessageNotModifiedError:
132
+ return None
133
+ return await say(event, text, buttons)
134
+
135
+
136
+ def require_owner(ctx: Ctx, event) -> None:
137
+ if not ctx.cfg.is_owner(event.sender_id):
138
+ raise UserError("β›” Only the bot owner can do that.")
139
+
140
+
141
+ # ------------------------------------------------------------------ sending and editing
142
+ async def send_post(client, peer, post):
143
+ ents = de_entities(post.entities)
144
+ markup = build_markup(post.buttons)
145
+ rich = rich_of(post)
146
+ if rich is not None and not post.media_file_id: # a rich message: Telegram builds its blocks from what was kept
147
+ return await send_rich(client, peer, rich, markup=markup)
148
+ if post.media_file_id:
149
+ return await with_media(
150
+ post.media_file_id,
151
+ lambda media: client.send_file(
152
+ peer, media, caption=post.text or "", formatting_entities=ents, buttons=markup
153
+ ),
154
+ )
155
+ return await client.send_message(
156
+ peer, post.text, formatting_entities=ents, buttons=markup, link_preview=bool(post.link_preview)
157
+ )
158
+
159
+
160
+ async def push_edit(client, ch, p, *, replace_media: bool = False) -> None:
161
+ """Make the live channel message look like `p` (any object with the Post fields)."""
162
+ peer = peer_of(ch)
163
+ ents = de_entities(p.entities)
164
+ markup = build_markup(p.buttons)
165
+ rich = rich_of(p)
166
+ if rich is not None and not p.media_kind:
167
+ await with_rich(rich, lambda inp: edit_raw(client, peer, p.message_id, rich_message=inp, markup=markup))
168
+ return
169
+ if replace_media and p.media_file_id:
170
+ await with_media(
171
+ p.media_file_id,
172
+ lambda media: client.edit_message(
173
+ peer, p.message_id, text=p.text or "", formatting_entities=ents, buttons=markup, file=media
174
+ ),
175
+ )
176
+ else:
177
+ await edit_raw(
178
+ client,
179
+ peer,
180
+ p.message_id,
181
+ text=p.text or "",
182
+ entities=ents,
183
+ markup=markup,
184
+ preview=None if p.media_kind else bool(p.link_preview),
185
+ )
186
+
187
+
188
+ # What the userbot can change in a post. It is a user account: it can't set buttons, and it fails the way the bot did
189
+ # when Telegram dislikes the text itself.
190
+ USERBOT_EDITS = {"text", "entities", "link_preview"}
191
+ NOT_THE_USERBOTS_JOB = {
192
+ "EntityBoundsInvalidError", "EntitiesTooLongError", "MessageTooLongError", "MediaCaptionTooLongError",
193
+ "MessageEmptyError", "ButtonUrlInvalidError", "ReplyMarkupInvalidError",
194
+ }
195
+
196
+
197
+ @dataclass
198
+ class EditReport:
199
+ """How the edit of a published post went (for the message the owner gets)."""
200
+
201
+ by_userbot: bool = False # Telegram refused the bot, so the userbot made the edit
202
+ bot_error: Optional[str] = None # the name of the error Telegram gave the bot
203
+ buttons: Optional[str] = None # after the userbot's edit: "kept" | "restored" | "lost" (None: no link buttons saved)
204
+ notes: list = field(default_factory=list) # what the userbot had to do in the channel (joined, got a right ...)
205
+ media: Optional[tuple] = None # (kind, reference) of the photo / file the post shows now, as the bot sees it
206
+
207
+
208
+ def edit_report_text(report: Optional[EditReport]) -> str:
209
+ """The lines to add to the owner's message when the userbot had to make the edit (empty for an ordinary edit)."""
210
+ if report is None or not report.by_userbot:
211
+ return ""
212
+ lines = [f"πŸ€– Telegram refused the bot ({esc(report.bot_error or 'error')}), so the userbot made the edit."]
213
+ if report.buttons == "kept":
214
+ lines.append("The buttons are still on the post.")
215
+ elif report.buttons == "restored":
216
+ lines.append("Telegram dropped the buttons with that edit, so the bot put them back.")
217
+ elif report.buttons == "lost":
218
+ lines.append(
219
+ "Telegram dropped the buttons with that edit and the bot may not put them back. They stay saved in "
220
+ "My posts; πŸ”§ Check buttons tries again."
221
+ )
222
+ if report.notes:
223
+ text = "; ".join(report.notes)
224
+ lines.append("ℹ️ " + esc(text[:1].upper() + text[1:]) + ".")
225
+ return "\n".join(lines)
226
+
227
+
228
+ async def put_buttons_back(client, ch, p) -> Optional[str]:
229
+ """After the userbot's edit: make the post show its saved link buttons again where Telegram dropped them.
230
+
231
+ "kept" (they were there), "restored", "lost" (Telegram won't let the bot set them), None (none are saved)."""
232
+ markup = build_markup(p.buttons)
233
+ if not link_urls(markup):
234
+ return None
235
+ try:
236
+ how = await ensure_markup(client, peer_of(ch), p.message_id, markup)
237
+ except Exception as e: # noqa: BLE001 - the edit itself worked; only the buttons are missing
238
+ log.info("could not put the buttons back on %s: %s", p.message_id, type(e).__name__)
239
+ return "lost"
240
+ return "kept" if how == "fine" else "restored"
241
+
242
+
243
+ async def live_media(client, ch, message_id: int) -> Optional[tuple]:
244
+ """(kind, reference) of the photo / file the channel post shows now, as the bot sees it; None if it can't be read."""
245
+ try:
246
+ msgs = await fetch_messages(client, peer_of(ch), [message_id])
247
+ except Exception: # noqa: BLE001
248
+ return None
249
+ m = msgs[0] if msgs else None
250
+ if is_skippable(m):
251
+ return None
252
+ kind, ref = media_info(m)
253
+ return (kind, ref) if kind else None
254
+
255
+
256
+ async def edit_by_userbot(ctx: Ctx, ch, p, *, replace_media: bool, bot_error: str, notify=None) -> Optional[EditReport]:
257
+ """The userbot makes the live post look like `p`. None when there is no userbot to ask; UserbotError when it fails.
258
+
259
+ A new photo / file goes through the userbot's own chat with the bot: the bot sends it there and the userbot edits the
260
+ post with that copy, so nothing is downloaded or uploaded - a big file is as quick as a small one and keeps its
261
+ thumbnail. Only when that does not work does the bot download the file (with its thumbnail) and the userbot upload
262
+ it again, which is slow for a big file. `notify(text)` tells the owner what is going on."""
263
+ ub = ctx.userbot
264
+ editor = await ub.editor_for(ch) if ub is not None else None
265
+ if editor is None:
266
+ return None
267
+ report = EditReport(by_userbot=True, bot_error=bot_error)
268
+ folder = None
269
+
270
+ async def tell(text: str) -> None:
271
+ if notify is not None:
272
+ await notify(text)
273
+
274
+ fields = dict(
275
+ text=p.text or "",
276
+ entities=de_entities(p.entities),
277
+ preview=None if p.media_kind or rich_of(p) else bool(p.link_preview),
278
+ rich=None if p.media_kind else rich_of(p),
279
+ )
280
+ try:
281
+ await tell("⏳ Telegram refused the bot, so the userbot is making the edit.")
282
+ if not (replace_media and p.media_file_id):
283
+ await editor.edit(p.message_id, **fields)
284
+ else:
285
+ done = False
286
+ media = await editor.media_by_reference(p.media_file_id)
287
+ if media is not None:
288
+ try:
289
+ await editor.edit(p.message_id, media=media, **fields)
290
+ done = True
291
+ editor.notes.append("the new file went through the userbot's chat with the bot, so nothing was uploaded")
292
+ except UserbotRefused as e:
293
+ if not e.about_media:
294
+ raise
295
+ editor.dm_problem = f"Telegram would not take the userbot's copy of the file ({e.name})"
296
+ if not done:
297
+ why = editor.dm_problem or "that did not work"
298
+ editor.notes.append(f"the file was downloaded and uploaded again, because {why}")
299
+ await tell(
300
+ "⏳ The file can't go through the userbot's chat with the bot, so it is downloaded and uploaded "
301
+ f"again - a big file takes a while. (Reason: {esc(why)}.)"
302
+ )
303
+ folder = tempfile.mkdtemp(prefix="cpb-media-")
304
+ try:
305
+ media = await fetch_media(ctx.client, p.media_file_id, p.media_kind, folder)
306
+ except (errors.RPCError, OSError, ValueError) as e:
307
+ raise UserbotError(f"I could not download the new media for the userbot ({type(e).__name__}).")
308
+ await editor.edit(p.message_id, media=media, **fields)
309
+ finally:
310
+ await editor.close()
311
+ report.notes = list(editor.notes)
312
+ if folder:
313
+ shutil.rmtree(folder, ignore_errors=True)
314
+ if replace_media:
315
+ report.media = await live_media(ctx.client, ch, p.message_id)
316
+ report.buttons = await put_buttons_back(ctx.client, ch, p)
317
+ return report
318
+
319
+
320
+ async def apply_edit_reported(ctx: Ctx, post, ch, *, replace_media: bool = False, notify=None, **changes):
321
+ """Edit the channel message first (if the post is published), and only then save the change.
322
+
323
+ The bot edits. If Telegram refuses it (a post that belongs to another bot) and the change is to the text, caption
324
+ or media, the userbot makes the edit instead. Returns (the saved post, an EditReport)."""
325
+ report = EditReport()
326
+ if post.status == "sent" and post.message_id:
327
+ new = SimpleNamespace(**{**post.as_dict(), **changes})
328
+ try:
329
+ await push_edit(ctx.client, ch, new, replace_media=replace_media)
330
+ except errors.MessageNotModifiedError:
331
+ pass
332
+ except errors.RPCError as e:
333
+ refused = "❌ " + explain_rpc(e)
334
+ if type(e).__name__ in NOT_THE_USERBOTS_JOB or not (replace_media or USERBOT_EDITS & set(changes)):
335
+ raise UserError(refused + "\nNothing was changed.")
336
+ try:
337
+ done = await edit_by_userbot(
338
+ ctx, ch, new, replace_media=replace_media, bot_error=type(e).__name__, notify=notify
339
+ )
340
+ except UserbotError as ue:
341
+ log.info("the userbot could not make the edit either: %s", ue)
342
+ raise UserError(f"{refused} {edit_problem_text(ctx.userbot, fallback_error=str(ue))}\nNothing was changed.")
343
+ if done is None:
344
+ raise UserError(f"{refused} {edit_problem_text(ctx.userbot)}\nNothing was changed.")
345
+ report = done
346
+ if report.media: # the post now shows the userbot's upload: keep My posts in step with it
347
+ changes = {**changes, "media_kind": report.media[0], "media_file_id": report.media[1]}
348
+ return await ctx.db.update_post(post.id, **changes), report
349
+
350
+
351
+ async def apply_edit(ctx: Ctx, post, ch, *, replace_media: bool = False, **changes):
352
+ """apply_edit_reported for the callers that only want the saved post."""
353
+ saved, _ = await apply_edit_reported(ctx, post, ch, replace_media=replace_media, **changes)
354
+ return saved
355
+
356
+
357
+ def purge_pending(ctx: Ctx, ttl: float = 3600.0) -> None:
358
+ """Forget confirm dialogs (replace plans, repost choices...) nobody answered for a while."""
359
+ now = time.monotonic()
360
+ stale = [
361
+ k
362
+ for k, v in ctx.pending.items()
363
+ if not getattr(v, "running", False) and now - getattr(v, "created", now) > ttl
364
+ ]
365
+ for k in stale:
366
+ ctx.pending.pop(k, None)
367
+
368
+
369
+ def on_cb(ctx: Ctx, prefix: str):
370
+ def deco(fn):
371
+ ctx.callbacks[prefix] = fn
372
+ return fn
373
+
374
+ return deco
375
+
376
+
377
+ def on_text(ctx: Ctx, mode: str):
378
+ def deco(fn):
379
+ ctx.text_handlers[mode] = fn
380
+ return fn
381
+
382
+ return deco
383
+
384
+
385
+ def set_state(ctx: Ctx, uid: int, mode: str, **data: Any) -> dict:
386
+ ctx.state[uid] = {"mode": mode, **data}
387
+ return ctx.state[uid]
388
+
389
+
390
+ def clear_state(ctx: Ctx, uid: int) -> Optional[dict]:
391
+ return ctx.state.pop(uid, None)
392
+
393
+
394
+ def cmd(name: str, args: bool = False):
395
+ """Event builder for a private-chat command such as /new or /replace <args>."""
396
+ pat = rf"(?is)^/{name}(?:@\w+)?" + (r"(?:\s+(.*))?$" if args else r"\s*$")
397
+ return events.NewMessage(incoming=True, pattern=pat, func=lambda e: e.is_private)
398
+
399
+
400
+ async def discard_temp(ctx: Ctx, uid: int) -> None:
401
+ """Drop a half-made draft when the user abandons the flow that was creating it."""
402
+ st = ctx.state.get(uid)
403
+ if st and st.get("temp") and st.get("pid"):
404
+ p = await ctx.db.get_post(st["pid"])
405
+ if p is not None and p.status == "draft":
406
+ await ctx.db.delete_post(p.id)
app/config.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Settings, read from environment variables (or a .env file)."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import os
6
+ import tempfile
7
+ from dataclasses import dataclass
8
+ from typing import Optional
9
+
10
+ try: # python-dotenv is optional; real env vars always win
11
+ from dotenv import load_dotenv
12
+
13
+ load_dotenv()
14
+ except Exception: # pragma: no cover
15
+ pass
16
+
17
+
18
+ def _ints(name: str) -> frozenset:
19
+ raw = os.getenv(name, "") or ""
20
+ out = set()
21
+ for part in raw.replace(";", ",").replace(" ", ",").split(","):
22
+ part = part.strip()
23
+ if part.lstrip("-").isdigit():
24
+ out.add(int(part))
25
+ return frozenset(out)
26
+
27
+
28
+ def _bool(name: str, default: bool) -> bool:
29
+ raw = os.getenv(name)
30
+ if raw is None or raw.strip() == "":
31
+ return default
32
+ return raw.strip().lower() in {"1", "true", "yes", "on"}
33
+
34
+
35
+ DEFAULT_ERROR_LOG_CHAT_ID = -1002525172451
36
+ _OFF = {"0", "off", "none", "false", "no", "disabled", "disable"}
37
+
38
+
39
+ def _chat_id(name: str, default: Optional[int]) -> Optional[int]:
40
+ """A chat id from the environment: unset or empty -> default, "0" / "off" -> None (switched off)."""
41
+ raw = (os.getenv(name) or "").strip()
42
+ if raw == "":
43
+ return default
44
+ if raw.lower() in _OFF:
45
+ return None
46
+ try:
47
+ return int(raw)
48
+ except ValueError:
49
+ raise SystemExit(f"{name} must be a chat id such as -1001234567890 (or 0 / off to switch it off), not {raw!r}")
50
+
51
+
52
+ def _float(name: str, default: float) -> float:
53
+ try:
54
+ return float(os.getenv(name, "") or default)
55
+ except ValueError:
56
+ return default
57
+
58
+
59
+ def _whole(name: str, default: int) -> int:
60
+ """A whole number from the environment; anything that is not a finite number gives the default."""
61
+ value = _float(name, float(default))
62
+ return int(value) if math.isfinite(value) else default
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Config:
67
+ api_id: int
68
+ api_hash: str
69
+ bot_token: str
70
+ owners: frozenset
71
+ admins: frozenset
72
+ database_url: str
73
+ db_pool: str
74
+ session_path: str
75
+ session_string: str
76
+ edit_delay: float
77
+ replace_typed_links: bool
78
+ port: int
79
+ log_level: str
80
+ error_log_chat_id: Optional[int] = None # errors are sent to this chat; None = off
81
+ userbot_session: str = "" # session text of the helper account that deletes old posts
82
+ userbot_keep_admin: bool = False # keep the userbot an admin after a clean-up (default: take the right away)
83
+ delete_service_messages: bool = True # remove "channel name changed", "pinned a message", video chat ... notices
84
+ sync_interval_minutes: int = 60 # how often every channel is compared with My posts (0 = never on its own)
85
+ import_old_posts: bool = True # read the posts that were in a channel before the bot was added into My posts
86
+ markup_input: bool = True # text typed as HTML or Markdown (and sent without Telegram formatting) becomes real formatting
87
+
88
+ def is_owner(self, uid) -> bool:
89
+ return uid in self.owners
90
+
91
+ def is_allowed(self, uid) -> bool:
92
+ return uid in self.owners or uid in self.admins
93
+
94
+
95
+ def default_session_path() -> str:
96
+ """Outside the app folder on purpose: a host that publishes that folder (python -m http.server) must not
97
+ publish the login session. A bot can always log in again with its token, so losing it is harmless."""
98
+ return os.path.join(tempfile.gettempdir(), "channel-post-bot", "bot")
99
+
100
+
101
+ def load_config() -> Config:
102
+ missing = [k for k in ("API_ID", "API_HASH", "BOT_TOKEN") if not os.getenv(k)]
103
+ owners = _ints("OWNER_IDS")
104
+ if not owners:
105
+ missing.append("OWNER_IDS")
106
+ if missing:
107
+ raise SystemExit("Missing required settings: " + ", ".join(missing) + " (see .env.example)")
108
+ try:
109
+ api_id = int(os.environ["API_ID"])
110
+ except ValueError:
111
+ raise SystemExit("API_ID must be a number")
112
+ return Config(
113
+ api_id=api_id,
114
+ api_hash=os.environ["API_HASH"].strip(),
115
+ bot_token=os.environ["BOT_TOKEN"].strip(),
116
+ owners=owners,
117
+ admins=frozenset(),
118
+ database_url=(os.getenv("DATABASE_URL") or "sqlite+aiosqlite:///data/bot.db").strip(),
119
+ db_pool=(os.getenv("DB_POOL") or "null").strip().lower(),
120
+ session_path=(os.getenv("SESSION_PATH") or default_session_path()).strip(),
121
+ session_string=(os.getenv("SESSION_STRING") or "").strip(),
122
+ edit_delay=max(0.3, _float("EDIT_DELAY", 1.2)),
123
+ replace_typed_links=_bool("REPLACE_TYPED_LINKS", True),
124
+ port=int(os.getenv("PORT") or 0),
125
+ log_level=(os.getenv("LOG_LEVEL") or "INFO").upper(),
126
+ error_log_chat_id=_chat_id("ERROR_LOG_CHAT_ID", DEFAULT_ERROR_LOG_CHAT_ID),
127
+ userbot_session=(os.getenv("USERBOT_SESSION") or "").strip(),
128
+ userbot_keep_admin=_bool("USERBOT_KEEP_ADMIN", False),
129
+ delete_service_messages=_bool("DELETE_SERVICE_MESSAGES", True),
130
+ sync_interval_minutes=max(0, _whole("SYNC_INTERVAL_MINUTES", 60)),
131
+ import_old_posts=_bool("IMPORT_OLD_POSTS", True),
132
+ markup_input=_bool("MARKUP_INPUT", True),
133
+ )
app/crosslinks.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Links to posts that moved: pointed at their new place in EVERY connected channel.
2
+
3
+ /repost gives every post of a channel a new message id, and /shift -c puts the posts into another channel. A link to
4
+ the old post - https://t.me/name/52, https://t.me/c/123/52, a hyperlink behind some text, a button - that sits in ANY
5
+ connected channel would lead nowhere once the old post is gone. relink_channels reads the connected channels, finds
6
+ those links and points them at the equivalent new post. Only the digits of the id change (for /shift also the channel
7
+ part of the link); the text around a link, the formatting and all other buttons stay exactly as they are.
8
+
9
+ Rules
10
+ * only a link whose old post HAS a copy is changed: a link to a post that was not copied stays as it is;
11
+ * running it again changes nothing more - a link that already points at a copy is not an old link any more;
12
+ * a post is read again right before it is edited, so something an admin changed meanwhile is never overwritten;
13
+ * a post of somebody else is edited only if the bot has the "Edit messages of others" right; otherwise it is only
14
+ counted, so the report can say so;
15
+ * what Telegram holds back (a copyright notice instead of the post) and a channel Telegram restricts are not edited;
16
+ * nothing is deleted anywhere.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import logging
22
+ from dataclasses import dataclass, field
23
+ from typing import Any, Awaitable, Callable, Optional
24
+
25
+ from telethon import errors, types
26
+
27
+ from .buttons_sync import ensure_markup, link_urls
28
+ from .postlinks import PostLinks, relink_message
29
+ from .replace_engine import CHUNK, fetch_messages, is_skippable, preview_flag
30
+ from .restrictions import message_restriction, probe_channel
31
+ from .tgutil import FATAL, edit_raw, esc, flood_retry, get_rights, peer_of, ser_entities, ser_markup
32
+
33
+ log = logging.getLogger(__name__)
34
+
35
+ PAUSE = 0.25 # between two reads while a channel is scanned
36
+ ABORT_AFTER = 5 # the same refusal this many times in a row: leave the channel (the others are still done)
37
+
38
+
39
+ @dataclass
40
+ class ChannelLinks:
41
+ """What was found and done in one channel."""
42
+
43
+ channel: Any
44
+ scanned: int = 0 # message ids read so far
45
+ top: int = 0 # the last id that is read
46
+ checked: int = 0 # posts looked at
47
+ found: int = 0 # posts with a link to change
48
+ relinked: int = 0 # posts whose links were changed
49
+ links: int = 0 # links changed in total
50
+ not_allowed: int = 0 # posts with a link to change that the bot may not edit (somebody else's, no right)
51
+ held_back: int = 0 # posts Telegram holds back (copyright ...): left as they are
52
+ gone: int = 0 # posts that were deleted while we worked
53
+ failed: list = field(default_factory=list) # [(message id, error name)]
54
+ skipped: Optional[str] = None # why the channel was not looked at
55
+ aborted: Optional[str] = None # the refusal that made us give up on this channel
56
+
57
+
58
+ @dataclass
59
+ class CrossResult:
60
+ """What a run did in all the channels (also handed to `progress` while it works)."""
61
+
62
+ channels: list = field(default_factory=list) # [ChannelLinks], in the order they were done
63
+ total: int = 0 # channels to look at
64
+ index: int = 0 # the number of the channel being worked on (1 = the first)
65
+ current: Optional[ChannelLinks] = None
66
+ phase: str = "" # scan | edit
67
+ stopped: bool = False
68
+
69
+ @property
70
+ def relinked(self) -> int:
71
+ return sum(c.relinked for c in self.channels)
72
+
73
+ @property
74
+ def links(self) -> int:
75
+ return sum(c.links for c in self.channels)
76
+
77
+ @property
78
+ def failed(self) -> list:
79
+ return [(c.channel, mid, name) for c in self.channels for mid, name in c.failed]
80
+
81
+ @property
82
+ def not_allowed(self) -> int:
83
+ return sum(c.not_allowed for c in self.channels)
84
+
85
+ @property
86
+ def changed_channels(self) -> list:
87
+ return [c for c in self.channels if c.relinked]
88
+
89
+ @property
90
+ def skipped(self) -> list:
91
+ return [c for c in self.channels if c.skipped]
92
+
93
+ @property
94
+ def clean(self) -> bool:
95
+ """Everything that had to be done was done."""
96
+ return not self.stopped and not self.failed and not self.not_allowed and not any(c.aborted for c in self.channels)
97
+
98
+
99
+ async def _edit(client, peer, m, rl) -> None:
100
+ if rl.text_changed:
101
+ await edit_raw(client, peer, m.id, text=rl.text, entities=rl.entities, markup=rl.markup, preview=preview_flag(m))
102
+ else: # only buttons changed: the text is not sent again
103
+ await edit_raw(client, peer, m.id, markup=rl.markup)
104
+
105
+
106
+ async def _scan(
107
+ client, peer, top: int, links: PostLinks, leave: set, mine: set, can_edit_others: bool, res: ChannelLinks, *,
108
+ pause: float, tick: Callable[[], Awaitable[None]], should_stop: Optional[Callable[[], bool]],
109
+ ) -> list:
110
+ """Read ids 1..top; the ids of the posts that have links to change (and may be changed) come back, oldest first."""
111
+ todo: list = []
112
+ a = 1
113
+ while a <= top:
114
+ if should_stop and should_stop():
115
+ break
116
+ hi = min(a + CHUNK - 1, top)
117
+ for m in await fetch_messages(client, peer, list(range(a, hi + 1))):
118
+ if m is None or isinstance(m, (types.MessageEmpty, types.MessageService)):
119
+ continue
120
+ res.checked += 1
121
+ if m.id in leave:
122
+ continue
123
+ if message_restriction(m):
124
+ res.held_back += 1
125
+ continue
126
+ if relink_message(m, links) is None:
127
+ continue
128
+ res.found += 1
129
+ if not (getattr(m, "out", False) or m.id in mine) and not can_edit_others:
130
+ res.not_allowed += 1
131
+ continue
132
+ todo.append(m.id)
133
+ res.scanned = hi
134
+ a = hi + 1
135
+ await tick()
136
+ if pause and a <= top:
137
+ await asyncio.sleep(pause)
138
+ return todo
139
+
140
+
141
+ async def _apply(
142
+ client, db, ch, peer, ids: list, links: PostLinks, res: ChannelLinks, *,
143
+ delay: float, settle_pause: float, tick: Callable[[], Awaitable[None]], should_stop: Optional[Callable[[], bool]],
144
+ ) -> bool:
145
+ """Edit the posts in `ids`, each one read again first. False when the run was stopped."""
146
+ streak, last_name = 0, None
147
+ for mid in ids:
148
+ if should_stop and should_stop():
149
+ return False
150
+ (m,) = await fetch_messages(client, peer, [mid])
151
+ if is_skippable(m):
152
+ res.gone += 1
153
+ continue
154
+ if message_restriction(m):
155
+ res.held_back += 1
156
+ continue
157
+ rl = relink_message(m, links)
158
+ if rl is None: # somebody fixed it meanwhile
159
+ continue
160
+ try:
161
+ await flood_retry(lambda: _edit(client, peer, m, rl))
162
+ if link_urls(rl.markup):
163
+ await ensure_markup(client, peer, m.id, rl.markup, pause=settle_pause)
164
+ except errors.MessageNotModifiedError:
165
+ continue
166
+ except Exception as e: # one bad post must not stop the others
167
+ name = type(e).__name__
168
+ log.warning("could not update the links of %s/%s: %s %s", ch.id, m.id, name, e)
169
+ res.failed.append((m.id, name))
170
+ streak = streak + 1 if name == last_name else 1
171
+ last_name = name
172
+ if name in FATAL or streak >= ABORT_AFTER:
173
+ res.aborted = name
174
+ return True
175
+ continue
176
+ streak, last_name = 0, None
177
+ res.relinked += 1
178
+ res.links += rl.links
179
+ fields: dict = {}
180
+ if rl.text_changed:
181
+ fields.update(text=rl.text, entities=ser_entities(rl.entities))
182
+ if rl.markup_changed:
183
+ fields["buttons"] = ser_markup(rl.markup)
184
+ try:
185
+ await db.update_post_by_message(ch.id, m.id, **fields)
186
+ except Exception: # the channel is right; the next sync corrects the saved copy
187
+ log.warning("could not save the new links of %s/%s", ch.id, m.id, exc_info=True)
188
+ await tick()
189
+ await asyncio.sleep(delay)
190
+ return True
191
+
192
+
193
+ async def relink_channels(
194
+ client,
195
+ db,
196
+ links: PostLinks,
197
+ channels: list,
198
+ *,
199
+ leave: Optional[dict] = None,
200
+ delay: float = 1.2,
201
+ settle_pause: float = 0.7,
202
+ pause: float = PAUSE,
203
+ progress: Optional[Callable[[CrossResult], Awaitable[None]]] = None,
204
+ should_stop: Optional[Callable[[], bool]] = None,
205
+ result: Optional[CrossResult] = None,
206
+ ) -> CrossResult:
207
+ """Point every link that `links` knows (old post -> its new place) at the new place, in each of `channels`.
208
+
209
+ `leave` ({channel id: message ids}) are posts that must not be touched, such as the originals of a repost.
210
+ `result` may be given to watch a run from outside: it is filled in while the run goes on."""
211
+ res = result if result is not None else CrossResult()
212
+ res.total = len(channels)
213
+ leave = leave or {}
214
+ if not links.ids:
215
+ return res
216
+
217
+ async def tick() -> None:
218
+ if progress:
219
+ await progress(res)
220
+
221
+ for n, ch in enumerate(channels, 1):
222
+ if should_stop and should_stop():
223
+ res.stopped = True
224
+ break
225
+ one = ChannelLinks(channel=ch)
226
+ res.channels.append(one)
227
+ res.index, res.current, res.phase = n, one, "scan"
228
+ await tick()
229
+ peer = peer_of(ch)
230
+ rights = await get_rights(client, ch)
231
+ if rights is not None and not rights.admin:
232
+ one.skipped = "the bot is not an admin there"
233
+ continue
234
+ if rights is not None and not (rights.post or rights.edit):
235
+ one.skipped = "the bot has no right to post or edit there"
236
+ continue
237
+ can_others = True if rights is None else bool(rights.edit)
238
+ top, why, err = await probe_channel(client, peer)
239
+ if err:
240
+ one.skipped = err
241
+ continue
242
+ if why:
243
+ one.skipped = f"Telegram restricts this channel ({why})"
244
+ continue
245
+ one.top = top or 0
246
+ try:
247
+ todo = await _scan(
248
+ client, peer, one.top, links, set(leave.get(ch.id, ())), await db.mine_message_ids(ch.id), can_others,
249
+ one, pause=pause, tick=tick, should_stop=should_stop,
250
+ )
251
+ if should_stop and should_stop():
252
+ res.stopped = True
253
+ break
254
+ res.phase = "edit"
255
+ await tick()
256
+ if not await _apply(
257
+ client, db, ch, peer, todo, links, one, delay=delay, settle_pause=settle_pause, tick=tick,
258
+ should_stop=should_stop,
259
+ ):
260
+ res.stopped = True
261
+ break
262
+ except errors.RPCError as e: # the channel can't be read (any more): the others still can
263
+ log.warning("could not read %s while pointing links at the new posts: %s", ch.id, type(e).__name__)
264
+ one.aborted = type(e).__name__
265
+ res.phase, res.current = "", None
266
+ return res
267
+
268
+
269
+ # ------------------------------------------------------------------------------ the three ways to use it
270
+ async def relink_after_repost(
271
+ client, db, ch, mig, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE,
272
+ progress=None, should_stop=None, result: Optional[CrossResult] = None,
273
+ ) -> CrossResult:
274
+ """After /repost: every link to an old post of `ch`, in any connected channel, points at the copy of that post.
275
+ The originals themselves are not touched (they are deleted later, or kept if the repost is undone)."""
276
+ res = result if result is not None else CrossResult()
277
+ ids = dict(await db.migration_pairs(mid=mig.id))
278
+ if not ids:
279
+ return res
280
+ await db.set_mark(mig.id, "links") # from now on an undo has to point the links back
281
+ return await relink_channels(
282
+ client, db, PostLinks.for_channel(ch, ids), await db.list_channels(), leave={ch.id: set(ids)}, delay=delay,
283
+ settle_pause=settle_pause, pause=pause, progress=progress, should_stop=should_stop, result=res,
284
+ )
285
+
286
+
287
+ async def restore_after_undo(
288
+ client, db, ch, mig, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE,
289
+ progress=None, should_stop=None, result: Optional[CrossResult] = None,
290
+ ) -> CrossResult:
291
+ """Before the copies of a repost are removed: links that were pointed at them go back to the original posts."""
292
+ res = result if result is not None else CrossResult()
293
+ if not await db.has_mark(mig.id, "links"):
294
+ return res # no link anywhere was changed for this repost
295
+ back = {new: old for old, new in await db.migration_pairs(mid=mig.id)}
296
+ return await relink_channels(
297
+ client, db, PostLinks.for_channel(ch, back), await db.list_channels(), leave={ch.id: set(back)}, delay=delay,
298
+ settle_pause=settle_pause, pause=pause, progress=progress, should_stop=should_stop, result=res,
299
+ )
300
+
301
+
302
+ def shift_links(src, dst, ids: dict) -> PostLinks:
303
+ """Links to the posts of the source channel -> the equivalent posts of the destination (`ids`: source id -> copy)."""
304
+ return PostLinks(
305
+ username=src.username, channel_id=src.id, ids=ids, target_username=dst.username, target_id=dst.id
306
+ )
307
+
308
+
309
+ async def relink_after_shift(
310
+ client, db, shift, src, dst, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE,
311
+ progress=None, should_stop=None, result: Optional[CrossResult] = None,
312
+ ) -> CrossResult:
313
+ """After /shift -c: a link to a post of the source channel, in any connected channel (the source itself is only
314
+ read, never changed), points at the copy of that post in the destination."""
315
+ res = result if result is not None else CrossResult()
316
+ ids = dict(await db.shift_pairs(shift.id))
317
+ if not ids:
318
+ return res
319
+ await db.set_mark(shift.id, "links")
320
+ chans = [c for c in await db.list_channels() if c.id != src.id]
321
+ return await relink_channels(
322
+ client, db, shift_links(src, dst, ids), chans, delay=delay, settle_pause=settle_pause, pause=pause,
323
+ progress=progress, should_stop=should_stop, result=res,
324
+ )
325
+
326
+
327
+ async def restore_after_shift_undo(
328
+ client, db, shift, src, dst, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE,
329
+ progress=None, should_stop=None, result: Optional[CrossResult] = None,
330
+ ) -> CrossResult:
331
+ """Before the copies of a shift are removed: links that were pointed at them go back to the source posts."""
332
+ res = result if result is not None else CrossResult()
333
+ if not await db.has_mark(shift.id, "links"):
334
+ return res
335
+ back = {new: old for old, new in await db.shift_pairs(shift.id)}
336
+ links = PostLinks(
337
+ username=dst.username, channel_id=dst.id, ids=back, target_username=src.username, target_id=src.id
338
+ )
339
+ chans = [c for c in await db.list_channels() if c.id != src.id]
340
+ return await relink_channels(
341
+ client, db, links, chans, leave={dst.id: set(back)}, delay=delay, settle_pause=settle_pause, pause=pause,
342
+ progress=progress, should_stop=should_stop, result=res,
343
+ )
344
+
345
+
346
+ # ------------------------------------------------------------------------------------------ the report
347
+ def _name(ch) -> str:
348
+ return esc(getattr(ch, "title", None) or str(getattr(ch, "id", "?")))
349
+
350
+
351
+ def report_lines(res: CrossResult, *, what: str = "the new copies", back: bool = False) -> list:
352
+ """Lines (HTML) for the end of a repost / shift. `what`: where the links point now. `back`: they were pointed back."""
353
+ out: list = []
354
+ done = [c for c in res.channels if not c.skipped]
355
+ if res.relinked:
356
+ n = len(res.changed_channels)
357
+ out.append(
358
+ f"πŸ”— {res.links} link(s) in {res.relinked} post(s) of {n} channel(s) "
359
+ f"{'point back at the original posts' if back else 'now point at ' + what}."
360
+ )
361
+ if n > 1 or (n == 1 and len(done) > 1):
362
+ for c in res.changed_channels[:12]:
363
+ out.append(f"β€’ {_name(c.channel)}: {c.links} link(s) in {c.relinked} post(s)")
364
+ elif done and not res.stopped and not any(c.aborted or c.failed for c in done):
365
+ out.append(f"πŸ”— Checked {len(done)} channel(s): no link there needed changing.")
366
+ if res.not_allowed:
367
+ names = ", ".join(_name(c.channel) for c in res.channels if c.not_allowed)
368
+ out.append(
369
+ f"{res.not_allowed} post(s) with such a link were made by somebody else and the bot may not edit them "
370
+ f"({names}). Give the bot the β€œEdit messages of others” right and press β€œπŸ”— Update links again”."
371
+ )
372
+ failed = res.failed
373
+ if failed:
374
+ sample = ", ".join(f"{_name(c)} #{mid} {esc(name)}" for c, mid, name in failed[:5])
375
+ out.append(f"{len(failed)} post(s) could not get their links updated ({sample}{'…' if len(failed) > 5 else ''}).")
376
+ if any(name in ("MessageIdInvalidError", "MessageAuthorRequiredError") for _, _, name in failed):
377
+ out.append(
378
+ "Telegram refuses edits to posts that other bots (or other people) made or put buttons on: those "
379
+ "links have to be changed by their owner."
380
+ )
381
+ for c in res.channels:
382
+ if c.aborted:
383
+ out.append(f"Gave up on {_name(c.channel)} ({esc(c.aborted)}).")
384
+ skipped = res.skipped
385
+ if skipped:
386
+ out.append("Not looked at: " + "; ".join(f"{_name(c.channel)} ({esc(c.skipped)})" for c in skipped[:8]))
387
+ held = sum(c.held_back for c in res.channels)
388
+ if held:
389
+ out.append(f"{held} post(s) are held back by Telegram (copyright notice) and were left alone.")
390
+ if res.stopped:
391
+ out.append("⏹ Stopped before every channel was done - press β€œπŸ”— Update links again” to finish.")
392
+ return out
393
+
394
+
395
+ def progress_text(res: CrossResult, *, title: str = "Pointing links at the new copies") -> str:
396
+ """The line shown while a run is going on."""
397
+ cur = res.current
398
+ where = f" - {_name(cur.channel)}" if cur is not None else ""
399
+ step = f" ({res.index} of {res.total})" if res.total else ""
400
+ if cur is not None and res.phase == "scan" and cur.top:
401
+ detail = f"\nReading posts {cur.scanned} of {cur.top}…"
402
+ elif cur is not None and res.phase == "edit":
403
+ detail = f"\nChanging links: {cur.relinked} of {cur.found - cur.not_allowed} post(s) done…"
404
+ else:
405
+ detail = ""
406
+ return f"πŸ”— {title}{step}{where}{detail}\n{res.links} link(s) changed so far."
app/db.py ADDED
@@ -0,0 +1,1067 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Database layer (SQLAlchemy 2.0 async). PostgreSQL in production, SQLite for local tests."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import logging
6
+ import os
7
+ from datetime import datetime, timezone
8
+ from typing import Any, Optional
9
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
10
+
11
+ from sqlalchemy import (
12
+ JSON,
13
+ BigInteger,
14
+ Boolean,
15
+ DateTime,
16
+ ForeignKey,
17
+ Integer,
18
+ String,
19
+ Text,
20
+ UniqueConstraint,
21
+ delete,
22
+ desc,
23
+ func,
24
+ select,
25
+ update,
26
+ )
27
+ from sqlalchemy.dialects.postgresql import JSONB
28
+ from sqlalchemy.exc import IntegrityError
29
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
30
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
31
+ from sqlalchemy.pool import NullPool
32
+
33
+ log = logging.getLogger(__name__)
34
+
35
+ JSONType = JSON().with_variant(JSONB(), "postgresql")
36
+
37
+
38
+ def utcnow() -> datetime:
39
+ return datetime.now(timezone.utc)
40
+
41
+
42
+ class Base(DeclarativeBase):
43
+ pass
44
+
45
+
46
+ class Channel(Base):
47
+ __tablename__ = "channels"
48
+
49
+ id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False)
50
+ access_hash: Mapped[int] = mapped_column(BigInteger, default=0)
51
+ title: Mapped[str] = mapped_column(String(256), default="")
52
+ username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
53
+ active: Mapped[bool] = mapped_column(Boolean, default=True)
54
+ added_by: Mapped[int] = mapped_column(BigInteger, default=0)
55
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
56
+
57
+
58
+ class Post(Base):
59
+ __tablename__ = "posts"
60
+ __table_args__ = (UniqueConstraint("channel_id", "message_id", name="uq_post_channel_msg"),)
61
+
62
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
63
+ channel_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("channels.id"), index=True)
64
+ message_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True)
65
+ status: Mapped[str] = mapped_column(String(16), default="draft", index=True) # draft | sent
66
+ source: Mapped[str] = mapped_column(String(16), default="bot") # bot | adopted
67
+ text: Mapped[str] = mapped_column(Text, default="")
68
+ entities: Mapped[list] = mapped_column(JSONType, default=list)
69
+ media_kind: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
70
+ media_file_id: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
71
+ buttons: Mapped[list] = mapped_column(JSONType, default=list)
72
+ link_preview: Mapped[bool] = mapped_column(Boolean, default=False)
73
+ created_by: Mapped[int] = mapped_column(BigInteger, default=0)
74
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
75
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
76
+ sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
77
+
78
+ def as_dict(self) -> dict:
79
+ return {c.name: getattr(self, c.name) for c in self.__table__.columns}
80
+
81
+
82
+ class Batch(Base):
83
+ """One /swap run (so it can be undone)."""
84
+
85
+ __tablename__ = "batches"
86
+
87
+ id: Mapped[str] = mapped_column(String(32), primary_key=True)
88
+ old_username: Mapped[str] = mapped_column(String(64))
89
+ new_username: Mapped[str] = mapped_column(String(64))
90
+ created_by: Mapped[int] = mapped_column(BigInteger, default=0)
91
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
92
+ undone: Mapped[bool] = mapped_column(Boolean, default=False)
93
+
94
+
95
+ class Change(Base):
96
+ __tablename__ = "changes"
97
+
98
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
99
+ batch_id: Mapped[str] = mapped_column(String(32), ForeignKey("batches.id"), index=True)
100
+ channel_id: Mapped[int] = mapped_column(BigInteger)
101
+ message_id: Mapped[int] = mapped_column(BigInteger)
102
+ old_state: Mapped[dict] = mapped_column(JSONType, default=dict)
103
+ new_state: Mapped[dict] = mapped_column(JSONType, default=dict)
104
+ reverted: Mapped[bool] = mapped_column(Boolean, default=False)
105
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
106
+
107
+
108
+ class Migration(Base):
109
+ """One /repost run: a channel copied post by post, so it can be continued, undone or finished."""
110
+
111
+ __tablename__ = "migrations"
112
+
113
+ id: Mapped[str] = mapped_column(String(32), primary_key=True)
114
+ channel_id: Mapped[int] = mapped_column(BigInteger, index=True)
115
+ old_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
116
+ new_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
117
+ include_typed: Mapped[bool] = mapped_column(Boolean, default=True)
118
+ include_posts: Mapped[bool] = mapped_column(Boolean, default=False)
119
+ first_id: Mapped[int] = mapped_column(BigInteger)
120
+ last_id: Mapped[int] = mapped_column(BigInteger)
121
+ partial: Mapped[bool] = mapped_column(Boolean, default=False)
122
+ # copying | stopped | incomplete | copied | old_deleted | copies_deleted
123
+ status: Mapped[str] = mapped_column(String(16), default="copying")
124
+ created_by: Mapped[int] = mapped_column(BigInteger, default=0)
125
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
126
+
127
+
128
+ class MigrationItem(Base):
129
+ __tablename__ = "migration_items"
130
+
131
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
132
+ migration_id: Mapped[str] = mapped_column(String(32), ForeignKey("migrations.id"), index=True)
133
+ old_id: Mapped[int] = mapped_column(BigInteger)
134
+ new_id: Mapped[int] = mapped_column(BigInteger)
135
+ old_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
136
+ new_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
137
+
138
+
139
+ class Shift(Base):
140
+ """One /shift run: posts of a source channel copied into another channel (so it can be continued or undone)."""
141
+
142
+ __tablename__ = "shifts"
143
+
144
+ id: Mapped[str] = mapped_column(String(32), primary_key=True)
145
+ src_channel_id: Mapped[int] = mapped_column(BigInteger, index=True)
146
+ src_access_hash: Mapped[int] = mapped_column(BigInteger, default=0)
147
+ src_title: Mapped[str] = mapped_column(String(256), default="")
148
+ src_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
149
+ dst_channel_id: Mapped[int] = mapped_column(BigInteger, index=True)
150
+ first_id: Mapped[int] = mapped_column(BigInteger)
151
+ last_id: Mapped[int] = mapped_column(BigInteger)
152
+ # copying | stopped | incomplete | copied | copies_deleted
153
+ status: Mapped[str] = mapped_column(String(16), default="copying")
154
+ created_by: Mapped[int] = mapped_column(BigInteger, default=0)
155
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
156
+
157
+
158
+ class ShiftItem(Base):
159
+ __tablename__ = "shift_items"
160
+
161
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
162
+ shift_id: Mapped[str] = mapped_column(String(32), ForeignKey("shifts.id"), index=True)
163
+ old_id: Mapped[int] = mapped_column(BigInteger) # message id in the source channel
164
+ new_id: Mapped[int] = mapped_column(BigInteger) # message id of the copy in the destination channel
165
+ new_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
166
+
167
+
168
+ class ScheduledDelete(Base):
169
+ """A channel message the bot has to delete at a given time (a broadcast with an expiry)."""
170
+
171
+ __tablename__ = "scheduled_deletes"
172
+
173
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
174
+ channel_id: Mapped[int] = mapped_column(BigInteger, index=True)
175
+ message_id: Mapped[int] = mapped_column(BigInteger)
176
+ delete_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
177
+ group_id: Mapped[str] = mapped_column(String(32), default="") # the broadcast it belongs to
178
+ status: Mapped[str] = mapped_column(String(12), default="pending") # pending | failed
179
+ attempts: Mapped[int] = mapped_column(Integer, default=0)
180
+ last_error: Mapped[Optional[str]] = mapped_column(String(160), nullable=True)
181
+ created_by: Mapped[int] = mapped_column(BigInteger, default=0)
182
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
183
+
184
+
185
+ class ChannelSync(Base):
186
+ """Where the last look at a channel stopped, so the next one only has to read what is new."""
187
+
188
+ __tablename__ = "channel_sync"
189
+
190
+ channel_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False)
191
+ last_top: Mapped[int] = mapped_column(BigInteger, default=0) # the newest message id that existed then
192
+ last_pts: Mapped[int] = mapped_column(BigInteger, default=0) # the channel's event counter then
193
+ deferred: Mapped[int] = mapped_column(Integer, default=0) # new messages left for the next look (too fresh then)
194
+ last_run: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
195
+ last_deep: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) # last look at every id
196
+
197
+
198
+ class ChannelHistory(Base):
199
+ """How far the older posts of a channel (the ones sent before the bot was there) have been read into My posts."""
200
+
201
+ __tablename__ = "channel_history"
202
+
203
+ channel_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False)
204
+ top: Mapped[int] = mapped_column(BigInteger, default=0) # the newest message id that counts as "older"
205
+ next_id: Mapped[int] = mapped_column(BigInteger, default=1) # where the reading goes on
206
+ imported: Mapped[int] = mapped_column(Integer, default=0) # older posts added to My posts so far
207
+ done: Mapped[bool] = mapped_column(Boolean, default=False)
208
+ started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
209
+ finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
210
+
211
+
212
+ class IgnoredPost(Base):
213
+ """A post the owner made the bot forget: it stays in the channel, but the sync never takes it over again."""
214
+
215
+ __tablename__ = "ignored_posts"
216
+ __table_args__ = (UniqueConstraint("channel_id", "message_id", name="uq_ignored_channel_msg"),)
217
+
218
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
219
+ channel_id: Mapped[int] = mapped_column(BigInteger, index=True)
220
+ message_id: Mapped[int] = mapped_column(BigInteger)
221
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
222
+
223
+
224
+ class JobMark(Base):
225
+ """A fact about a /repost or /shift run that has to outlive a restart, e.g. that links in other channels were
226
+ pointed at its copies (so that Undo points them back), or which extras a shift was asked for."""
227
+
228
+ __tablename__ = "job_marks"
229
+
230
+ job_id: Mapped[str] = mapped_column(String(32), primary_key=True)
231
+ mark: Mapped[str] = mapped_column(String(24), primary_key=True)
232
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
233
+
234
+
235
+ class Admin(Base):
236
+ __tablename__ = "admins"
237
+ user_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
238
+
239
+
240
+ def as_utc(dt: Optional[datetime]) -> Optional[datetime]:
241
+ """A datetime from the database as an aware UTC one (SQLite hands back naive values)."""
242
+ if dt is None:
243
+ return None
244
+ return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt.astimezone(timezone.utc)
245
+
246
+
247
+ def normalize_db_url(url: str) -> tuple:
248
+ """Turn a plain DATABASE_URL into a SQLAlchemy async URL + connect args."""
249
+ connect_args: dict = {}
250
+ if url.startswith("postgres://"):
251
+ url = "postgresql://" + url[len("postgres://"):]
252
+ if url.startswith("postgresql://"):
253
+ url = "postgresql+asyncpg://" + url[len("postgresql://"):]
254
+ if url.startswith("postgresql+asyncpg://"):
255
+ parts = urlsplit(url)
256
+ keep = []
257
+ for k, v in parse_qsl(parts.query, keep_blank_values=True):
258
+ if k == "sslmode":
259
+ if v in ("require", "verify-ca", "verify-full"):
260
+ connect_args["ssl"] = True
261
+ elif k in ("channel_binding", "options"):
262
+ continue
263
+ else:
264
+ keep.append((k, v))
265
+ host = parts.hostname or ""
266
+ if "-pooler" in host or "pgbouncer" in host:
267
+ # PgBouncer in transaction mode does not support prepared statements
268
+ connect_args["statement_cache_size"] = 0
269
+ keep.append(("prepared_statement_cache_size", "0"))
270
+ url = urlunsplit(parts._replace(query=urlencode(keep)))
271
+ elif url.startswith("sqlite:///"):
272
+ url = "sqlite+aiosqlite:///" + url[len("sqlite:///"):]
273
+ return url, connect_args
274
+
275
+
276
+ class Database:
277
+ def __init__(self, url: str, pool: str = "null"):
278
+ self.url, connect_args = normalize_db_url(url)
279
+ kwargs: dict = {"connect_args": connect_args}
280
+ if self.url.startswith("sqlite"):
281
+ path = self.url.split(":///", 1)[-1]
282
+ if path and path != ":memory:":
283
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
284
+ elif pool == "queue":
285
+ kwargs.update(pool_size=5, max_overflow=5, pool_pre_ping=True, pool_recycle=1800)
286
+ else:
287
+ # short-lived connections: lets serverless Postgres (e.g. Neon) go to sleep when idle
288
+ kwargs["poolclass"] = NullPool
289
+ self.engine = create_async_engine(self.url, **kwargs)
290
+ self.Session = async_sessionmaker(self.engine, expire_on_commit=False)
291
+
292
+ async def init(self, retries: int = 6) -> None:
293
+ last: Optional[BaseException] = None
294
+ for i in range(retries):
295
+ try:
296
+ async with self.engine.begin() as conn:
297
+ await conn.run_sync(Base.metadata.create_all)
298
+ return
299
+ except Exception as e: # cold start of serverless DBs can fail once
300
+ last = e
301
+ log.warning("database not ready (%s) - retry %s/%s", e, i + 1, retries)
302
+ await asyncio.sleep(min(2 ** i, 15))
303
+ assert last is not None
304
+ raise last
305
+
306
+ async def close(self) -> None:
307
+ await self.engine.dispose()
308
+
309
+ async def list_admins(self) -> set[int]:
310
+ async with self.Session() as s:
311
+ return set((await s.execute(select(Admin.user_id))).scalars())
312
+
313
+ async def add_admin(self, uid: int) -> bool:
314
+ async with self.Session() as s:
315
+ if await s.get(Admin, uid) is not None:
316
+ return False
317
+ s.add(Admin(user_id=uid))
318
+ await s.commit()
319
+ return True
320
+
321
+ async def remove_admin(self, uid: int) -> bool:
322
+ async with self.Session() as s:
323
+ row = await s.get(Admin, uid)
324
+ if row is None:
325
+ return False
326
+ await s.delete(row)
327
+ await s.commit()
328
+ return True
329
+
330
+ # ------------------------------------------------------------------ channels
331
+ async def list_channels(self, active_only: bool = True) -> list:
332
+ async with self.Session() as s:
333
+ q = select(Channel).order_by(Channel.title)
334
+ if active_only:
335
+ q = q.where(Channel.active.is_(True))
336
+ return list((await s.execute(q)).scalars())
337
+
338
+ async def get_channel(self, cid: int) -> Optional[Channel]:
339
+ async with self.Session() as s:
340
+ return await s.get(Channel, cid)
341
+
342
+ async def save_channel(self, cid: int, access_hash: int, title: str, username: Optional[str], added_by: int) -> Channel:
343
+ async with self.Session() as s:
344
+ ch = await s.get(Channel, cid)
345
+ if ch is None:
346
+ ch = Channel(id=cid, access_hash=access_hash, title=title, username=username, added_by=added_by, active=True)
347
+ s.add(ch)
348
+ else:
349
+ ch.access_hash = access_hash or ch.access_hash
350
+ ch.title = title or ch.title
351
+ ch.username = username
352
+ ch.active = True
353
+ await s.commit()
354
+ return ch
355
+
356
+ async def touch_channel_hash(self, cid: int, access_hash: int) -> None:
357
+ async with self.Session() as s:
358
+ ch = await s.get(Channel, cid)
359
+ if ch is not None and access_hash and ch.access_hash != access_hash:
360
+ ch.access_hash = access_hash
361
+ await s.commit()
362
+
363
+ async def set_channel_active(self, cid: int, active: bool) -> None:
364
+ async with self.Session() as s:
365
+ ch = await s.get(Channel, cid)
366
+ if ch is not None:
367
+ ch.active = active
368
+ await s.commit()
369
+
370
+ async def count_channel_posts(self, cid: int) -> int:
371
+ """Every post of the channel in My posts - published ones and drafts."""
372
+ async with self.Session() as s:
373
+ return int((await s.execute(select(func.count()).select_from(Post).where(Post.channel_id == cid))).scalar_one())
374
+
375
+ async def delete_channel_data(self, cid: int) -> int:
376
+ """Everything My posts holds about a channel: its saved posts (published and drafts) and what the sync keeps
377
+ about them - the posts forgotten on purpose, where the last look and the reading of the older posts stopped - so a
378
+ channel that is added again starts from scratch. Nothing is touched in Telegram. The channel itself stays
379
+ registered (switched off) because reposts and shifts that name it still need it, and so do timed deletions.
380
+ Returns how many posts went."""
381
+ async with self.Session() as s:
382
+ n = (await s.execute(select(func.count()).select_from(Post).where(Post.channel_id == cid))).scalar_one()
383
+ await s.execute(delete(Post).where(Post.channel_id == cid))
384
+ for model in (IgnoredPost, ChannelSync, ChannelHistory):
385
+ await s.execute(delete(model).where(model.channel_id == cid))
386
+ await s.commit()
387
+ return int(n)
388
+
389
+ # --------------------------------------------------------------------- posts
390
+ async def create_post(self, **fields: Any) -> Post:
391
+ async with self.Session() as s:
392
+ p = Post(**fields)
393
+ s.add(p)
394
+ await s.commit()
395
+ return p
396
+
397
+ async def get_post(self, pid: int) -> Optional[Post]:
398
+ async with self.Session() as s:
399
+ return await s.get(Post, pid)
400
+
401
+ async def update_post(self, pid: int, **fields: Any) -> Optional[Post]:
402
+ async with self.Session() as s:
403
+ p = await s.get(Post, pid)
404
+ if p is None:
405
+ return None
406
+ for k, v in fields.items():
407
+ setattr(p, k, v)
408
+ p.updated_at = utcnow()
409
+ await s.commit()
410
+ return p
411
+
412
+ async def delete_post(self, pid: int) -> None:
413
+ async with self.Session() as s:
414
+ p = await s.get(Post, pid)
415
+ if p is not None:
416
+ await s.delete(p)
417
+ await s.commit()
418
+
419
+ async def list_posts(self, channel_id: Optional[int], status: Optional[str], offset: int, limit: int) -> tuple:
420
+ cond = []
421
+ if channel_id is not None:
422
+ cond.append(Post.channel_id == channel_id)
423
+ if status:
424
+ cond.append(Post.status == status)
425
+ async with self.Session() as s:
426
+ total = (await s.execute(select(func.count()).select_from(Post).where(*cond))).scalar_one()
427
+ q = (
428
+ select(Post)
429
+ .where(*cond)
430
+ .order_by(Post.status.asc(), desc(Post.message_id), desc(Post.id))
431
+ .offset(offset)
432
+ .limit(limit)
433
+ )
434
+ rows = list((await s.execute(q)).scalars())
435
+ return rows, total
436
+
437
+ async def latest_sent(self, channel_id: int, limit: int = 30) -> list:
438
+ async with self.Session() as s:
439
+ q = (
440
+ select(Post)
441
+ .where(Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None))
442
+ .order_by(desc(Post.message_id))
443
+ .limit(limit)
444
+ )
445
+ return list((await s.execute(q)).scalars())
446
+
447
+ async def sent_posts(self, channel_id: int) -> list:
448
+ """Every published post of a channel, oldest first."""
449
+ async with self.Session() as s:
450
+ q = (
451
+ select(Post)
452
+ .where(Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None))
453
+ .order_by(Post.message_id)
454
+ )
455
+ return list((await s.execute(q)).scalars())
456
+
457
+ async def sent_posts_from(self, channel_id: int, first_message_id: int) -> list:
458
+ """Published posts of a channel from message id `first_message_id` on, oldest first."""
459
+ async with self.Session() as s:
460
+ q = (
461
+ select(Post)
462
+ .where(
463
+ Post.channel_id == channel_id,
464
+ Post.status == "sent",
465
+ Post.message_id.is_not(None),
466
+ Post.message_id >= first_message_id,
467
+ )
468
+ .order_by(Post.message_id, Post.id)
469
+ )
470
+ return list((await s.execute(q)).scalars())
471
+
472
+ async def mine_message_ids(self, channel_id: int) -> set:
473
+ async with self.Session() as s:
474
+ q = select(Post.message_id).where(
475
+ Post.channel_id == channel_id, Post.source == "bot", Post.message_id.is_not(None)
476
+ )
477
+ return {r for r in (await s.execute(q)).scalars()}
478
+
479
+ async def find_by_message(self, channel_id: int, message_id: int) -> Optional[Post]:
480
+ async with self.Session() as s:
481
+ q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id)
482
+ return (await s.execute(q)).scalar_one_or_none()
483
+
484
+ async def forget_posts(self, channel_id: int, message_ids: list) -> int:
485
+ """Remove the saved posts of these channel messages (they were deleted in the channel) and what hangs on them:
486
+ a timed deletion that is not needed any more, a "forgotten on purpose" mark. Returns how many posts went."""
487
+ if not message_ids:
488
+ return 0
489
+ ids = list(message_ids)
490
+ async with self.Session() as s:
491
+ rows = (await s.execute(select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(ids)))).scalars().all()
492
+ for p in rows:
493
+ await s.delete(p)
494
+ for model in (ScheduledDelete, IgnoredPost):
495
+ extra = await s.execute(select(model).where(model.channel_id == channel_id, model.message_id.in_(ids)))
496
+ for r in extra.scalars().all():
497
+ await s.delete(r)
498
+ await s.commit()
499
+ return len(rows)
500
+
501
+ async def posts_at(self, channel_id: int, message_ids: list) -> list:
502
+ """The published posts that sit at these message ids."""
503
+ if not message_ids:
504
+ return []
505
+ async with self.Session() as s:
506
+ q = select(Post).where(
507
+ Post.channel_id == channel_id, Post.status == "sent", Post.message_id.in_(list(message_ids))
508
+ )
509
+ return list((await s.execute(q)).scalars())
510
+
511
+ async def release_slot(self, channel_id: int, message_id: int, keep_pid: Optional[int] = None) -> int:
512
+ """Drop any other saved post at this message id (the sync may have picked the message up a moment earlier)."""
513
+ async with self.Session() as s:
514
+ q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id)
515
+ if keep_pid is not None:
516
+ q = q.where(Post.id != keep_pid)
517
+ rows = list((await s.execute(q)).scalars())
518
+ for p in rows:
519
+ await s.delete(p)
520
+ if rows:
521
+ await s.commit()
522
+ return len(rows)
523
+
524
+ async def _drop_slots(self, s, channel_id: int, message_ids: list) -> None:
525
+ """Inside a transaction: remove saved posts at these ids, so the posts about to be saved can take their place."""
526
+ q = select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(list(message_ids)))
527
+ rows = list((await s.execute(q)).scalars())
528
+ for p in rows:
529
+ await s.delete(p)
530
+ if rows:
531
+ await s.flush()
532
+
533
+ # ------------------------------------------------------- what happens outside the bot
534
+ async def get_sync(self, channel_id: int) -> Optional[ChannelSync]:
535
+ async with self.Session() as s:
536
+ return await s.get(ChannelSync, channel_id)
537
+
538
+ async def max_saved_id(self, channel_id: int) -> int:
539
+ """The newest message id among the channel's published posts (0 if there is none)."""
540
+ async with self.Session() as s:
541
+ q = select(func.max(Post.message_id)).where(
542
+ Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None)
543
+ )
544
+ return int((await s.execute(q)).scalar_one_or_none() or 0)
545
+
546
+ async def save_sync(
547
+ self, channel_id: int, *, last_top: int, last_pts: int, deferred: int = 0, deep: bool = False
548
+ ) -> None:
549
+ async with self.Session() as s:
550
+ row = await s.get(ChannelSync, channel_id)
551
+ if row is None:
552
+ row = ChannelSync(channel_id=channel_id)
553
+ s.add(row)
554
+ now = utcnow()
555
+ row.last_top, row.last_pts, row.deferred, row.last_run = last_top, last_pts, deferred, now
556
+ if deep:
557
+ row.last_deep = now
558
+ await s.commit()
559
+
560
+ async def adopt_message(self, channel_id: int, message_id: int, fields: dict, sent_at: Optional[datetime] = None) -> tuple:
561
+ """Save a post somebody else made in the channel. Returns (post, True), or (None, False) when the bot already
562
+ has a post at that message id (also when another task saved it a moment ago)."""
563
+ async with self.Session() as s:
564
+ q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id)
565
+ if (await s.execute(q)).scalar_one_or_none() is not None:
566
+ return None, False
567
+ p = Post(channel_id=channel_id, message_id=message_id, status="sent", source="adopted", created_by=0,
568
+ sent_at=sent_at or utcnow(), **fields)
569
+ s.add(p)
570
+ try:
571
+ await s.commit()
572
+ except IntegrityError:
573
+ await s.rollback()
574
+ return None, False
575
+ return p, True
576
+
577
+ async def adopt_many(self, channel_id: int, items: list) -> list:
578
+ """items: [(message id, post fields, sent_at)] - save the posts somebody else made, many at once. Returns the
579
+ message ids that were new (the bot already had a post at the others)."""
580
+ if not items:
581
+ return []
582
+ ids = [i[0] for i in items]
583
+ async with self.Session() as s:
584
+ have = set(
585
+ (await s.execute(select(Post.message_id).where(Post.channel_id == channel_id, Post.message_id.in_(ids)))).scalars()
586
+ )
587
+ fresh = [i for i in items if i[0] not in have]
588
+ if not fresh:
589
+ return []
590
+ s.add_all(
591
+ [
592
+ Post(channel_id=channel_id, message_id=mid, status="sent", source="adopted", created_by=0,
593
+ sent_at=at or utcnow(), **fields)
594
+ for mid, fields, at in fresh
595
+ ]
596
+ )
597
+ try:
598
+ await s.commit()
599
+ return [i[0] for i in fresh]
600
+ except IntegrityError: # somebody saved one of them a moment ago: one by one then
601
+ await s.rollback()
602
+ made = []
603
+ for mid, fields, at in fresh:
604
+ _, created = await self.adopt_message(channel_id, mid, fields, sent_at=at)
605
+ if created:
606
+ made.append(mid)
607
+ return made
608
+
609
+ # ------------------------------------------------------------- the channel's older posts
610
+ async def get_history(self, channel_id: int) -> Optional[ChannelHistory]:
611
+ async with self.Session() as s:
612
+ return await s.get(ChannelHistory, channel_id)
613
+
614
+ async def start_history(self, channel_id: int, top: int) -> ChannelHistory:
615
+ """Note that the older posts of a channel (message ids 1 to `top`) are to be read in. Does nothing when that
616
+ has begun already."""
617
+ async with self.Session() as s:
618
+ row = await s.get(ChannelHistory, channel_id)
619
+ if row is not None:
620
+ return row
621
+ row = ChannelHistory(channel_id=channel_id, top=max(0, top), next_id=1, imported=0)
622
+ if top < 1: # an empty channel: nothing to read
623
+ row.done, row.finished_at = True, utcnow()
624
+ s.add(row)
625
+ try:
626
+ await s.commit()
627
+ except IntegrityError:
628
+ await s.rollback()
629
+ row = await s.get(ChannelHistory, channel_id)
630
+ return row
631
+
632
+ async def save_history(self, channel_id: int, *, next_id: int, imported: int = 0, done: bool = False) -> None:
633
+ async with self.Session() as s:
634
+ row = await s.get(ChannelHistory, channel_id)
635
+ if row is None:
636
+ return
637
+ row.next_id = max(row.next_id, next_id)
638
+ row.imported += imported
639
+ if done and not row.done:
640
+ row.done, row.finished_at = True, utcnow()
641
+ await s.commit()
642
+
643
+ async def reset_history(self, channel_id: int) -> None:
644
+ """Read the channel's older posts again at the next look (the posts the bot already has are skipped)."""
645
+ async with self.Session() as s:
646
+ row = await s.get(ChannelHistory, channel_id)
647
+ if row is not None:
648
+ await s.delete(row)
649
+ await s.commit()
650
+
651
+ # ------------------------------------------------------------ posts forgotten on purpose
652
+ async def ignore_post(self, channel_id: int, message_id: int) -> None:
653
+ async with self.Session() as s:
654
+ q = select(IgnoredPost).where(IgnoredPost.channel_id == channel_id, IgnoredPost.message_id == message_id)
655
+ if (await s.execute(q)).scalar_one_or_none() is not None:
656
+ return
657
+ s.add(IgnoredPost(channel_id=channel_id, message_id=message_id))
658
+ try:
659
+ await s.commit()
660
+ except IntegrityError:
661
+ await s.rollback()
662
+
663
+ async def ignored_ids(self, channel_id: int) -> set:
664
+ async with self.Session() as s:
665
+ q = select(IgnoredPost.message_id).where(IgnoredPost.channel_id == channel_id)
666
+ return {int(r) for r in (await s.execute(q)).scalars()}
667
+
668
+ # ------------------------------------------------------------ facts about a repost / shift run
669
+ async def set_mark(self, job_id: str, mark: str) -> None:
670
+ async with self.Session() as s:
671
+ if await s.get(JobMark, (job_id, mark)) is not None:
672
+ return
673
+ s.add(JobMark(job_id=job_id, mark=mark))
674
+ try:
675
+ await s.commit()
676
+ except IntegrityError:
677
+ await s.rollback()
678
+
679
+ async def has_mark(self, job_id: str, mark: str) -> bool:
680
+ async with self.Session() as s:
681
+ return await s.get(JobMark, (job_id, mark)) is not None
682
+
683
+ async def marks_of(self, job_id: str) -> set:
684
+ async with self.Session() as s:
685
+ q = select(JobMark.mark).where(JobMark.job_id == job_id)
686
+ return set((await s.execute(q)).scalars())
687
+
688
+ async def sync_update_post(self, pid: int, expected: Optional[datetime], fields: dict) -> bool:
689
+ """Save what the channel shows - but only if the saved post is still exactly as it was when it was read
690
+ (`expected` is its updated_at then), so a change made through the bot meanwhile is never overwritten."""
691
+ async with self.Session() as s:
692
+ res = await s.execute(
693
+ update(Post).where(Post.id == pid, Post.updated_at == expected).values(**fields, updated_at=utcnow())
694
+ )
695
+ await s.commit()
696
+ return bool(res.rowcount)
697
+
698
+ # ------------------------------------------------------------ timed deletions
699
+ async def schedule_deletes(self, rows: list) -> None:
700
+ """rows: dicts with channel_id, message_id, delete_at, group_id, created_by."""
701
+ if not rows:
702
+ return
703
+ async with self.Session() as s:
704
+ s.add_all([ScheduledDelete(**r) for r in rows])
705
+ await s.commit()
706
+
707
+ async def due_deletes(self, now: datetime, limit: int = 500) -> list:
708
+ async with self.Session() as s:
709
+ q = (
710
+ select(ScheduledDelete)
711
+ .where(ScheduledDelete.status == "pending", ScheduledDelete.delete_at <= now)
712
+ .order_by(ScheduledDelete.delete_at, ScheduledDelete.id)
713
+ .limit(limit)
714
+ )
715
+ return list((await s.execute(q)).scalars())
716
+
717
+ async def next_delete_at(self) -> Optional[datetime]:
718
+ async with self.Session() as s:
719
+ q = select(func.min(ScheduledDelete.delete_at)).where(ScheduledDelete.status == "pending")
720
+ return as_utc((await s.execute(q)).scalar_one_or_none())
721
+
722
+ async def pending_deletes(self, group_id: Optional[str] = None, status: str = "pending") -> list:
723
+ async with self.Session() as s:
724
+ q = select(ScheduledDelete).where(ScheduledDelete.status == status).order_by(ScheduledDelete.id)
725
+ if group_id:
726
+ q = q.where(ScheduledDelete.group_id == group_id)
727
+ return list((await s.execute(q)).scalars())
728
+
729
+ async def finish_deletes(self, ids: list) -> None:
730
+ if not ids:
731
+ return
732
+ async with self.Session() as s:
733
+ for row in (await s.execute(select(ScheduledDelete).where(ScheduledDelete.id.in_(list(ids))))).scalars():
734
+ await s.delete(row)
735
+ await s.commit()
736
+
737
+ async def retry_delete(self, sid: int, *, at: datetime, error: str) -> None:
738
+ async with self.Session() as s:
739
+ row = await s.get(ScheduledDelete, sid)
740
+ if row is not None:
741
+ row.attempts += 1
742
+ row.delete_at = at
743
+ row.last_error = error[:160]
744
+ await s.commit()
745
+
746
+ async def fail_delete(self, sid: int, error: str) -> None:
747
+ async with self.Session() as s:
748
+ row = await s.get(ScheduledDelete, sid)
749
+ if row is not None:
750
+ row.attempts += 1
751
+ row.status = "failed"
752
+ row.last_error = error[:160]
753
+ await s.commit()
754
+
755
+ # ------------------------------------------------------------- replace history
756
+ async def create_batch(self, batch_id: str, old: str, new: str, user_id: int) -> None:
757
+ async with self.Session() as s:
758
+ s.add(Batch(id=batch_id, old_username=old, new_username=new, created_by=user_id))
759
+ await s.commit()
760
+
761
+ async def _adopt(self, s, channel_id: int, message_id: int, fields: dict, user_id: int) -> None:
762
+ q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id)
763
+ p = (await s.execute(q)).scalar_one_or_none()
764
+ if p is not None:
765
+ for k, v in fields.items():
766
+ setattr(p, k, v)
767
+ p.updated_at = utcnow()
768
+ else:
769
+ s.add(
770
+ Post(
771
+ channel_id=channel_id,
772
+ message_id=message_id,
773
+ status="sent",
774
+ source="adopted",
775
+ created_by=user_id,
776
+ sent_at=utcnow(),
777
+ **fields,
778
+ )
779
+ )
780
+
781
+ async def record_changes(self, batch_id: str, channel_id: int, records: list, user_id: int) -> None:
782
+ """records: [{message_id, old_state, new_state, adopt: {post fields}}]"""
783
+ if not records:
784
+ return
785
+ async with self.Session() as s:
786
+ for r in records:
787
+ s.add(
788
+ Change(
789
+ batch_id=batch_id,
790
+ channel_id=channel_id,
791
+ message_id=r["message_id"],
792
+ old_state=r["old_state"],
793
+ new_state=r["new_state"],
794
+ )
795
+ )
796
+ await self._adopt(s, channel_id, r["message_id"], r["adopt"], user_id)
797
+ await s.commit()
798
+
799
+ async def last_batch(self) -> Optional[Batch]:
800
+ async with self.Session() as s:
801
+ q = select(Batch).where(Batch.undone.is_(False)).order_by(desc(Batch.created_at)).limit(1)
802
+ return (await s.execute(q)).scalar_one_or_none()
803
+
804
+ async def get_batch(self, batch_id: str) -> Optional[Batch]:
805
+ async with self.Session() as s:
806
+ return await s.get(Batch, batch_id)
807
+
808
+ async def batch_changes(self, batch_id: str) -> list:
809
+ async with self.Session() as s:
810
+ q = select(Change).where(Change.batch_id == batch_id, Change.reverted.is_(False)).order_by(Change.id)
811
+ return list((await s.execute(q)).scalars())
812
+
813
+ async def count_batch_changes(self, batch_id: str) -> int:
814
+ async with self.Session() as s:
815
+ q = select(func.count()).select_from(Change).where(Change.batch_id == batch_id, Change.reverted.is_(False))
816
+ return (await s.execute(q)).scalar_one()
817
+
818
+ async def finish_undo(self, batch_id: str, change_ids: list, restored: list, all_done: bool) -> None:
819
+ """restored: [(channel_id, message_id, state)] -> refresh the saved post copies."""
820
+ async with self.Session() as s:
821
+ for cid in change_ids:
822
+ c = await s.get(Change, cid)
823
+ if c is not None:
824
+ c.reverted = True
825
+ for channel_id, message_id, state in restored:
826
+ q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id)
827
+ p = (await s.execute(q)).scalar_one_or_none()
828
+ if p is not None:
829
+ if not state.get("rich"): # a rich message's text was never changed: it stays as saved
830
+ p.text = state.get("text", "")
831
+ p.entities = state.get("entities", [])
832
+ p.buttons = state.get("buttons", [])
833
+ p.updated_at = utcnow()
834
+ if all_done:
835
+ b = await s.get(Batch, batch_id)
836
+ if b is not None:
837
+ b.undone = True
838
+ await s.commit()
839
+
840
+
841
+ # ------------------------------------------------------------------ /repost
842
+ OPEN_STATES = ("copying", "stopped", "incomplete", "copied")
843
+
844
+ async def create_migration(self, mid: str, channel_id: int, *, old, new, include_typed: bool, include_posts: bool,
845
+ first_id: int, last_id: int, partial: bool, user_id: int) -> None:
846
+ async with self.Session() as s:
847
+ s.add(Migration(id=mid, channel_id=channel_id, old_username=old, new_username=new,
848
+ include_typed=include_typed, include_posts=include_posts, first_id=first_id,
849
+ last_id=last_id, partial=partial, created_by=user_id))
850
+ await s.commit()
851
+
852
+ async def get_migration(self, mid: str) -> Optional[Migration]:
853
+ async with self.Session() as s:
854
+ return await s.get(Migration, mid)
855
+
856
+ async def open_migration(self, channel_id: Optional[int] = None) -> Optional[Migration]:
857
+ """The newest repost that is not finished yet (copies exist, old posts not deleted / copies not removed)."""
858
+ async with self.Session() as s:
859
+ q = select(Migration).where(Migration.status.in_(self.OPEN_STATES))
860
+ if channel_id is not None:
861
+ q = q.where(Migration.channel_id == channel_id)
862
+ q = q.order_by(desc(Migration.created_at)).limit(1)
863
+ return (await s.execute(q)).scalar_one_or_none()
864
+
865
+ async def set_migration_status(self, mid: str, status: str) -> None:
866
+ async with self.Session() as s:
867
+ m = await s.get(Migration, mid)
868
+ if m is not None:
869
+ m.status = status
870
+ await s.commit()
871
+
872
+ async def migration_done_old_ids(self, mid: str) -> set:
873
+ async with self.Session() as s:
874
+ q = select(MigrationItem.old_id).where(MigrationItem.migration_id == mid)
875
+ return set((await s.execute(q)).scalars())
876
+
877
+ async def record_repost(self, mid: str, channel_id: int, rows: list, user_id: int) -> None:
878
+ """rows: [{old_id, new_id, post: {Post fields}}] - saves the mapping and registers the new posts."""
879
+ if not rows:
880
+ return
881
+ async with self.Session() as s:
882
+ await self._drop_slots(s, channel_id, [r["new_id"] for r in rows])
883
+ for r in rows:
884
+ s.add(MigrationItem(migration_id=mid, old_id=r["old_id"], new_id=r["new_id"]))
885
+ s.add(Post(channel_id=channel_id, message_id=r["new_id"], status="sent", source="bot",
886
+ created_by=user_id, sent_at=utcnow(), **r["post"]))
887
+ await s.commit()
888
+
889
+ async def migration_pairs(
890
+ self, mid: Optional[str] = None, channel_id: Optional[int] = None, alive_only: bool = True
891
+ ) -> list:
892
+ """[(old id, new id)] of the copies of one repost (`mid`) or of every repost of a channel, oldest repost first.
893
+ alive_only: leave out copies that were removed again (undo)."""
894
+ async with self.Session() as s:
895
+ q = select(MigrationItem.old_id, MigrationItem.new_id).join(Migration, Migration.id == MigrationItem.migration_id)
896
+ if mid is not None:
897
+ q = q.where(MigrationItem.migration_id == mid)
898
+ if channel_id is not None:
899
+ q = q.where(Migration.channel_id == channel_id)
900
+ if alive_only:
901
+ q = q.where(MigrationItem.new_deleted.is_(False))
902
+ q = q.order_by(Migration.created_at, MigrationItem.id)
903
+ return [(a, b) for a, b in (await s.execute(q)).all()]
904
+
905
+ async def update_post_by_message(self, channel_id: int, message_id: int, **fields: Any) -> Optional[Post]:
906
+ """Change the saved copy of the post that sits at `message_id` (None if the bot does not know that post)."""
907
+ async with self.Session() as s:
908
+ q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id)
909
+ p = (await s.execute(q)).scalar_one_or_none()
910
+ if p is None:
911
+ return None
912
+ for k, v in fields.items():
913
+ setattr(p, k, v)
914
+ p.updated_at = utcnow()
915
+ await s.commit()
916
+ return p
917
+
918
+ async def migration_pending_ids(self, mid: str, which: str, limit: int = 100) -> list:
919
+ col, flag = (MigrationItem.old_id, MigrationItem.old_deleted) if which == "old" else (MigrationItem.new_id, MigrationItem.new_deleted)
920
+ async with self.Session() as s:
921
+ q = select(col).where(MigrationItem.migration_id == mid, flag.is_(False)).order_by(col).limit(limit)
922
+ return list((await s.execute(q)).scalars())
923
+
924
+ async def mark_migration_deleted(self, mid: str, channel_id: int, which: str, ids: list) -> None:
925
+ """The messages are gone from Telegram: flag them and drop their saved post copies."""
926
+ if not ids:
927
+ return
928
+ col, flag = ("old_id", "old_deleted") if which == "old" else ("new_id", "new_deleted")
929
+ async with self.Session() as s:
930
+ q = select(MigrationItem).where(MigrationItem.migration_id == mid, getattr(MigrationItem, col).in_(ids))
931
+ for it in (await s.execute(q)).scalars():
932
+ setattr(it, flag, True)
933
+ pq = select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(ids))
934
+ for p in (await s.execute(pq)).scalars():
935
+ await s.delete(p)
936
+ await s.commit()
937
+
938
+ async def migration_counts(self, mid: str) -> dict:
939
+ async with self.Session() as s:
940
+ total = (await s.execute(select(func.count()).select_from(MigrationItem).where(MigrationItem.migration_id == mid))).scalar_one()
941
+ old_left = (await s.execute(select(func.count()).select_from(MigrationItem).where(
942
+ MigrationItem.migration_id == mid, MigrationItem.old_deleted.is_(False)))).scalar_one()
943
+ new_left = (await s.execute(select(func.count()).select_from(MigrationItem).where(
944
+ MigrationItem.migration_id == mid, MigrationItem.new_deleted.is_(False)))).scalar_one()
945
+ lo = (await s.execute(select(func.min(MigrationItem.new_id)).where(MigrationItem.migration_id == mid))).scalar_one()
946
+ hi = (await s.execute(select(func.max(MigrationItem.new_id)).where(MigrationItem.migration_id == mid))).scalar_one()
947
+ return {"copied": total, "old_left": old_left, "new_left": new_left, "first_new": lo, "last_new": hi}
948
+
949
+ # ------------------------------------------------------------------- /shift
950
+ SHIFT_OPEN = ("copying", "stopped", "incomplete")
951
+
952
+ async def create_shift(self, sid: str, *, src, dst_channel_id: int, first_id: int, last_id: int, user_id: int) -> None:
953
+ """`src`: any object with id, access_hash, title and username (the source channel need not be registered)."""
954
+ async with self.Session() as s:
955
+ s.add(Shift(id=sid, src_channel_id=src.id, src_access_hash=src.access_hash or 0, src_title=src.title or "",
956
+ src_username=src.username, dst_channel_id=dst_channel_id, first_id=first_id, last_id=last_id,
957
+ created_by=user_id))
958
+ await s.commit()
959
+
960
+ async def get_shift(self, sid: str) -> Optional[Shift]:
961
+ async with self.Session() as s:
962
+ return await s.get(Shift, sid)
963
+
964
+ async def open_shift(self, src_id: Optional[int] = None, dst_id: Optional[int] = None) -> Optional[Shift]:
965
+ """The newest shift that is not finished (still copying, stopped, or incomplete)."""
966
+ async with self.Session() as s:
967
+ q = select(Shift).where(Shift.status.in_(self.SHIFT_OPEN))
968
+ if src_id is not None:
969
+ q = q.where(Shift.src_channel_id == src_id)
970
+ if dst_id is not None:
971
+ q = q.where(Shift.dst_channel_id == dst_id)
972
+ return (await s.execute(q.order_by(desc(Shift.created_at)).limit(1))).scalar_one_or_none()
973
+
974
+ async def last_finished_shift(self) -> Optional[Shift]:
975
+ """The newest finished shift that still has copies in its destination - so its Undo can be offered again."""
976
+ async with self.Session() as s:
977
+ alive = select(ShiftItem.id).where(ShiftItem.shift_id == Shift.id, ShiftItem.new_deleted.is_(False)).exists()
978
+ q = select(Shift).where(Shift.status == "copied", alive).order_by(desc(Shift.created_at)).limit(1)
979
+ return (await s.execute(q)).scalar_one_or_none()
980
+
981
+ async def set_shift_status(self, sid: str, status: str) -> None:
982
+ async with self.Session() as s:
983
+ sh = await s.get(Shift, sid)
984
+ if sh is not None:
985
+ sh.status = status
986
+ await s.commit()
987
+
988
+ async def shift_done_ids(self, sid: str) -> set:
989
+ async with self.Session() as s:
990
+ q = select(ShiftItem.old_id).where(ShiftItem.shift_id == sid)
991
+ return set((await s.execute(q)).scalars())
992
+
993
+ async def shift_pairs(self, sid: str, alive_only: bool = True) -> list:
994
+ """[(source id, id of the copy)] of one shift, in copy order."""
995
+ async with self.Session() as s:
996
+ q = select(ShiftItem.old_id, ShiftItem.new_id).where(ShiftItem.shift_id == sid)
997
+ if alive_only:
998
+ q = q.where(ShiftItem.new_deleted.is_(False))
999
+ return [(a, b) for a, b in (await s.execute(q.order_by(ShiftItem.id))).all()]
1000
+
1001
+ async def shifted_ids(self, src_id: int, dst_id: int, first: int, last: int) -> set:
1002
+ """Source ids in first..last that already have a live copy in `dst_id` from an earlier shift."""
1003
+ async with self.Session() as s:
1004
+ q = (
1005
+ select(ShiftItem.old_id)
1006
+ .join(Shift, Shift.id == ShiftItem.shift_id)
1007
+ .where(Shift.src_channel_id == src_id, Shift.dst_channel_id == dst_id, ShiftItem.new_deleted.is_(False),
1008
+ ShiftItem.old_id >= first, ShiftItem.old_id <= last)
1009
+ )
1010
+ return set((await s.execute(q)).scalars())
1011
+
1012
+ async def record_shift(self, sid: str, dst_channel_id: int, rows: list, user_id: int) -> None:
1013
+ """rows: [{old_id, new_id, post: {Post fields}}] - saves the mapping and registers the copies in My posts."""
1014
+ if not rows:
1015
+ return
1016
+ async with self.Session() as s:
1017
+ await self._drop_slots(s, dst_channel_id, [r["new_id"] for r in rows])
1018
+ for r in rows:
1019
+ s.add(ShiftItem(shift_id=sid, old_id=r["old_id"], new_id=r["new_id"]))
1020
+ s.add(Post(channel_id=dst_channel_id, message_id=r["new_id"], status="sent", source="bot",
1021
+ created_by=user_id, sent_at=utcnow(), **r["post"]))
1022
+ await s.commit()
1023
+
1024
+ async def shift_counts(self, sid: str) -> dict:
1025
+ async with self.Session() as s:
1026
+ base = ShiftItem.shift_id == sid
1027
+ total = (await s.execute(select(func.count()).select_from(ShiftItem).where(base))).scalar_one()
1028
+ left = (await s.execute(select(func.count()).select_from(ShiftItem).where(base, ShiftItem.new_deleted.is_(False)))).scalar_one()
1029
+ lo = (await s.execute(select(func.min(ShiftItem.new_id)).where(base))).scalar_one()
1030
+ hi = (await s.execute(select(func.max(ShiftItem.new_id)).where(base))).scalar_one()
1031
+ return {"copied": total, "new_left": left, "first_new": lo, "last_new": hi}
1032
+
1033
+ async def shift_pending_new(self, sid: str, limit: int = 100) -> list:
1034
+ async with self.Session() as s:
1035
+ q = select(ShiftItem.new_id).where(ShiftItem.shift_id == sid, ShiftItem.new_deleted.is_(False)).order_by(ShiftItem.new_id).limit(limit)
1036
+ return list((await s.execute(q)).scalars())
1037
+
1038
+ async def mark_shift_deleted(self, sid: str, dst_channel_id: int, ids: list) -> None:
1039
+ """The copies are gone from Telegram: flag them and drop their saved posts."""
1040
+ if not ids:
1041
+ return
1042
+ async with self.Session() as s:
1043
+ q = select(ShiftItem).where(ShiftItem.shift_id == sid, ShiftItem.new_id.in_(ids))
1044
+ for it in (await s.execute(q)).scalars():
1045
+ it.new_deleted = True
1046
+ pq = select(Post).where(Post.channel_id == dst_channel_id, Post.message_id.in_(ids))
1047
+ for p in (await s.execute(pq)).scalars():
1048
+ await s.delete(p)
1049
+ await s.commit()
1050
+
1051
+ # -------------------------------------------------------------------- export
1052
+ async def export_all(self) -> dict:
1053
+ def clean(d: dict) -> dict:
1054
+ return {k: (v.isoformat() if isinstance(v, datetime) else v) for k, v in d.items()}
1055
+
1056
+ async with self.Session() as s:
1057
+ chans = list((await s.execute(select(Channel))).scalars())
1058
+ posts = list((await s.execute(select(Post).order_by(Post.id))).scalars())
1059
+ marks = (await s.execute(select(IgnoredPost.channel_id, IgnoredPost.message_id).order_by(IgnoredPost.id))).all()
1060
+ return {
1061
+ "exported_at": utcnow().isoformat(),
1062
+ "channels": [
1063
+ clean({c.name: getattr(ch, c.name) for c in ch.__table__.columns}) for ch in chans
1064
+ ],
1065
+ "posts": [clean(p.as_dict()) for p in posts],
1066
+ "ignored": [{"channel_id": int(c), "message_id": int(m)} for c, m in marks], # posts forgotten on purpose
1067
+ }
app/errorlog.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Send errors to a Telegram chat (ERROR_LOG_CHAT_ID) as a `python` code block.
2
+
3
+ What is reported:
4
+ * every log record of level ERROR or higher that carries a message / traceback (handler failures included),
5
+ * exceptions nobody caught in background tasks ("Unhandled exception in background task <unnamed>:"),
6
+ * a crash of the whole bot (sent right before it exits).
7
+ Long tracebacks are cut into several messages, never shortened. Secrets (bot token, API hash, session texts,
8
+ database password) are replaced by *** before anything leaves the bot. The reporter never raises, never blocks the
9
+ bot, and protects the chat from floods (identical reports are merged, at most a few per minute).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import hashlib
15
+ import logging
16
+ import re
17
+ import time
18
+ import traceback
19
+ from collections import deque
20
+ from typing import Optional
21
+
22
+ from telethon import types
23
+
24
+ from .tgutil import utf16_len
25
+
26
+ log = logging.getLogger(__name__)
27
+
28
+ PART_LIMIT = 3800 # characters per message (Telegram allows 4096; the rest is head-room for the part label)
29
+ PIECE = 1500 # a single line longer than a message is cut into pieces of this size
30
+ MUTE_SECONDS = 600 # after "can't write to the log chat" stay quiet this long
31
+ MIN_SECRET = 6 # shorter secrets are not redacted (they would mangle ordinary text)
32
+
33
+
34
+ # ----------------------------------------------------------------------------- text helpers
35
+ def split_report(text: str, limit: int = PART_LIMIT) -> list:
36
+ """Cut a report into messages of at most `limit` characters at line breaks. Nothing is dropped."""
37
+ if len(text) <= limit:
38
+ return [text]
39
+ room = limit - 40 # space for the "(part 3/12)" label
40
+ pieces: list = []
41
+ for line in text.split("\n"):
42
+ while len(line) > room: # a single huge line: cut it
43
+ size = min(PIECE, room)
44
+ pieces.append(line[:size])
45
+ line = line[size:]
46
+ pieces.append(line)
47
+ parts: list = []
48
+ cur: list = [] # the lines of the part being built
49
+ used = 0
50
+ for piece in pieces:
51
+ add = len(piece) + (1 if cur else 0)
52
+ if cur and used + add > room:
53
+ parts.append("\n".join(cur))
54
+ cur, used = [piece], len(piece)
55
+ else:
56
+ cur.append(piece)
57
+ used += add
58
+ if cur:
59
+ parts.append("\n".join(cur))
60
+ n = len(parts)
61
+ return [f"(part {i}/{n})\n{p}" for i, p in enumerate(parts, 1)]
62
+
63
+
64
+ def redact(text: str, secrets) -> str:
65
+ for s in sorted({s for s in secrets if s and len(s) >= MIN_SECRET}, key=len, reverse=True):
66
+ text = text.replace(s, "***")
67
+ return text
68
+
69
+
70
+ def format_exception(exc: BaseException) -> str:
71
+ return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
72
+
73
+
74
+ def _task_label(task) -> str:
75
+ name = getattr(task, "get_name", lambda: "")() if task is not None else ""
76
+ if not name or re.fullmatch(r"Task-\d+", name):
77
+ return "<unnamed>"
78
+ return name
79
+
80
+
81
+ # ---------------------------------------------------------------------------------- reporter
82
+ class ErrorReporter:
83
+ def __init__(
84
+ self,
85
+ client,
86
+ chat_id: Optional[int],
87
+ *,
88
+ bot_token: str = "",
89
+ secrets=(),
90
+ per_minute: int = 12,
91
+ dedupe_seconds: float = 60.0,
92
+ gap: float = 1.0,
93
+ part_gap: float = 0.6,
94
+ ):
95
+ self.client = client
96
+ self.chat_id = chat_id
97
+ self.bot_token = bot_token
98
+ self.secrets = [s for s in (*secrets, bot_token) if s] # the login token is always hidden too
99
+ self.per_minute = per_minute
100
+ self.dedupe_seconds = dedupe_seconds
101
+ self.gap = gap
102
+ self.part_gap = part_gap
103
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
104
+ self._queue: Optional[asyncio.Queue] = None
105
+ self._task: Optional[asyncio.Task] = None
106
+ self._peer = None
107
+ self._muted_until = 0.0
108
+ self._recent: dict = {} # report key -> [time of the first, number suppressed since]
109
+ self._times: deque = deque() # when reports were accepted (for the per-minute limit)
110
+ self._skipped = 0 # reports dropped by the limit since the last one that went out
111
+
112
+ @property
113
+ def enabled(self) -> bool:
114
+ return bool(self.chat_id)
115
+
116
+ # ------------------------------------------------------------------ life cycle
117
+ def start(self) -> None:
118
+ if not self.enabled or self._task is not None:
119
+ return
120
+ self._loop = asyncio.get_running_loop()
121
+ self._queue = asyncio.Queue(maxsize=100)
122
+ self._task = self._loop.create_task(self._worker(), name="error-reporter")
123
+
124
+ async def stop(self, wait: float = 5.0) -> None:
125
+ """Let queued reports go out (for a few seconds at most), then stop."""
126
+ task, self._task = self._task, None
127
+ if task is None:
128
+ return
129
+ try:
130
+ await asyncio.wait_for(self._queue.join(), wait)
131
+ except Exception:
132
+ pass
133
+ task.cancel()
134
+ try:
135
+ await task
136
+ except BaseException:
137
+ pass
138
+
139
+ # ---------------------------------------------------------------------- input
140
+ def submit(self, title: str, tb: str = "") -> None:
141
+ """Queue a report. Safe to call from any thread; never raises."""
142
+ try:
143
+ loop = self._loop
144
+ if not self.enabled or loop is None or loop.is_closed():
145
+ return
146
+ try:
147
+ here = asyncio.get_running_loop()
148
+ except RuntimeError:
149
+ here = None
150
+ if here is loop:
151
+ self._enqueue(title, tb)
152
+ else:
153
+ loop.call_soon_threadsafe(self._enqueue, title, tb)
154
+ except Exception:
155
+ pass
156
+
157
+ def _enqueue(self, title: str, tb: str) -> None:
158
+ try:
159
+ now = time.monotonic()
160
+ if now < self._muted_until or self._queue is None:
161
+ return
162
+ last_line = next((ln for ln in reversed(tb.splitlines()) if ln.strip()), "")
163
+ key = hashlib.sha1(f"{title}|{last_line}".encode("utf-8", "replace")).hexdigest()
164
+ prev = self._recent.get(key)
165
+ merged = 0
166
+ if prev is not None:
167
+ if now - prev[0] < self.dedupe_seconds:
168
+ prev[1] += 1 # same error again: counted, reported with the next one
169
+ return
170
+ merged = prev[1]
171
+ self._recent[key] = [now, 0]
172
+ if len(self._recent) > 200:
173
+ for k in sorted(self._recent, key=lambda k: self._recent[k][0])[:100]:
174
+ self._recent.pop(k, None)
175
+ while self._times and now - self._times[0] > 60:
176
+ self._times.popleft()
177
+ if len(self._times) >= self.per_minute:
178
+ self._skipped += 1
179
+ return
180
+ self._times.append(now)
181
+ skipped, self._skipped = self._skipped, 0
182
+ try:
183
+ self._queue.put_nowait((title, tb, merged, skipped))
184
+ except asyncio.QueueFull:
185
+ self._skipped += 1 + skipped
186
+ except Exception:
187
+ pass
188
+
189
+ def loop_exception_handler(self, loop, context) -> None:
190
+ """asyncio calls this for exceptions nobody retrieved (set it with loop.set_exception_handler)."""
191
+ try:
192
+ exc = context.get("exception")
193
+ task = context.get("task") or context.get("future")
194
+ if task is not None and exc is not None:
195
+ title = f"Unhandled exception in background task {_task_label(task)}:"
196
+ else:
197
+ title = (context.get("message") or "Unhandled error in the event loop") + ":"
198
+ tb = format_exception(exc) if exc is not None else ""
199
+ self.submit(title, tb)
200
+ except Exception:
201
+ pass
202
+ finally:
203
+ loop.default_exception_handler(context) # keep the normal log line too
204
+
205
+ # --------------------------------------------------------------------- output
206
+ async def _worker(self) -> None:
207
+ assert self._queue is not None
208
+ while True:
209
+ item = await self._queue.get()
210
+ try:
211
+ await self._deliver(*item)
212
+ except asyncio.CancelledError:
213
+ raise
214
+ except Exception as e:
215
+ name = type(e).__name__
216
+ log.warning("could not write to the error log chat: %s %s", name, str(e)[:150])
217
+ if isinstance(e, (ValueError, PermissionError)) or "Forbidden" in name or "Private" in name:
218
+ # the bot is not a member of that chat (or may not write there): stop trying for a while
219
+ self._muted_until = time.monotonic() + MUTE_SECONDS
220
+ self._peer = None
221
+ finally:
222
+ self._queue.task_done()
223
+ await asyncio.sleep(self.gap)
224
+
225
+ async def _deliver(self, title: str, tb: str, merged: int = 0, skipped: int = 0) -> None:
226
+ if self._peer is None:
227
+ self._peer = await self.client.get_input_entity(self.chat_id)
228
+ text = title + (("\n\n" + tb.rstrip("\n")) if tb else "")
229
+ notes = []
230
+ if merged:
231
+ notes.append(f"(+{merged} identical report(s) suppressed)")
232
+ if skipped:
233
+ notes.append(f"({skipped} report(s) were skipped because too many errors came in)")
234
+ if notes:
235
+ text += "\n\n" + "\n".join(notes)
236
+ text = redact(text, self.secrets)
237
+ parts = split_report(text)
238
+ for i, part in enumerate(parts):
239
+ await self.client.send_message(
240
+ self._peer,
241
+ part,
242
+ formatting_entities=[types.MessageEntityPre(0, utf16_len(part), "python")],
243
+ link_preview=False,
244
+ )
245
+ if i < len(parts) - 1:
246
+ await asyncio.sleep(self.part_gap)
247
+
248
+ async def check(self) -> Optional[str]:
249
+ """None when the log chat can be reached, otherwise a short reason (used once at start-up)."""
250
+ if not self.enabled:
251
+ return None
252
+ try:
253
+ self._peer = await self.client.get_input_entity(self.chat_id)
254
+ return None
255
+ except Exception as e:
256
+ return (
257
+ f"{type(e).__name__}: {str(e)[:120]} - add the bot to that chat "
258
+ "(as a member, or as an admin who may post)"
259
+ )
260
+
261
+ async def report_fatal(self, title: str, exc: BaseException) -> None:
262
+ """The bot is going down: send the crash straight away (the queue may not get the time)."""
263
+ if not self.enabled:
264
+ return
265
+ try:
266
+
267
+ async def go() -> None:
268
+ if not self.client.is_connected():
269
+ await self.client.connect()
270
+ if self.bot_token and not await self.client.is_user_authorized():
271
+ await self.client.sign_in(bot_token=self.bot_token)
272
+ await self._deliver(title + ":", format_exception(exc))
273
+
274
+ await asyncio.wait_for(go(), 20)
275
+ except Exception as e:
276
+ log.warning("could not send the crash report: %s %s", type(e).__name__, str(e)[:150])
277
+
278
+
279
+ # ------------------------------------------------------------------------------ logging
280
+ class TelegramLogHandler(logging.Handler):
281
+ """Forwards log records (ERROR and up) to the reporter."""
282
+
283
+ def __init__(self, reporter: ErrorReporter, level: int = logging.ERROR):
284
+ super().__init__(level)
285
+ self.reporter = reporter
286
+
287
+ def emit(self, record: logging.LogRecord) -> None:
288
+ try:
289
+ if record.name.startswith("app.errorlog") or record.name == "asyncio":
290
+ return # our own messages would loop; asyncio's go through loop_exception_handler
291
+ title = record.getMessage()
292
+ tb = ""
293
+ if record.exc_info and record.exc_info[0] is not None:
294
+ tb = "".join(traceback.format_exception(*record.exc_info))
295
+ title += ":"
296
+ if not record.name.startswith(("app", "bot", "__main__")):
297
+ title = f"[{record.name}] {title}"
298
+ self.reporter.submit(title, tb)
299
+ except Exception:
300
+ pass
app/expiry.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Timed deletion: a broadcast with an expiry ("/broadcast 1h") is removed from every channel - and from My posts -
2
+ when its time is up.
3
+
4
+ The deletions are saved in the database (table scheduled_deletes), so a restart loses nothing: posts that came due while
5
+ the bot was off are deleted as soon as it is back. The Expirer wakes up only when something is due; it does not poll the
6
+ database, so a sleeping serverless database stays asleep.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import re
13
+ from datetime import datetime, timedelta
14
+ from typing import Optional
15
+
16
+ from .db import as_utc, utcnow
17
+ from .repost_engine import delete_batch
18
+ from .tgutil import esc, peer_of
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+ MIN_SECONDS = 60
23
+ MAX_SECONDS = 366 * 86400
24
+ MAX_ATTEMPTS = 5
25
+ RETRY_AFTER = 600 # seconds between attempts, times the attempt number
26
+ LOCK_WAIT = 60 # a long job (repost...) is running: look again in a minute
27
+
28
+ _UNITS = {
29
+ "m": 60, "min": 60, "mins": 60, "minute": 60, "minutes": 60,
30
+ "h": 3600, "hr": 3600, "hrs": 3600, "hour": 3600, "hours": 3600,
31
+ "d": 86400, "day": 86400, "days": 86400,
32
+ "w": 604800, "week": 604800, "weeks": 604800,
33
+ } # fmt: skip
34
+ _PART = re.compile(r"(\d+)\s*([a-z]+)")
35
+ DURATION_HELP = "Use minutes, hours or days: 50m, 1h, 5d (or 1d12h). Leave the time out to keep the message forever."
36
+
37
+
38
+ def parse_duration(text: str) -> int:
39
+ """'50m' -> 3000, '1h' -> 3600, '5d' -> 432000, '1d12h' -> 129600 (seconds). ValueError with a message if unusable."""
40
+ t = (text or "").strip().lower().replace(",", " ")
41
+ if not t or not re.fullmatch(r"(?:\d+\s*[a-z]+\s*)+", t):
42
+ raise ValueError(f"I can't read β€œ{(text or '').strip()[:30]}” as a time. {DURATION_HELP}")
43
+ total = 0
44
+ for n, unit in _PART.findall(t):
45
+ if unit not in _UNITS:
46
+ raise ValueError(f"β€œ{n}{unit}” - I don't know the unit β€œ{unit}”. {DURATION_HELP}")
47
+ total += int(n) * _UNITS[unit]
48
+ if total < MIN_SECONDS:
49
+ raise ValueError("The shortest time is 1 minute.")
50
+ if total > MAX_SECONDS:
51
+ raise ValueError("The longest time is 1 year (365d).")
52
+ return total
53
+
54
+
55
+ def human(seconds: int) -> str:
56
+ """3000 -> '50 minutes', 3600 -> '1 hour', 129600 -> '1 day 12 hours'."""
57
+ seconds = int(seconds)
58
+ days, rest = divmod(seconds, 86400)
59
+ hours, rest = divmod(rest, 3600)
60
+ minutes = rest // 60
61
+ parts = []
62
+ for n, word in ((days, "day"), (hours, "hour"), (minutes, "minute")):
63
+ if n:
64
+ parts.append(f"{n} {word}" + ("s" if n != 1 else ""))
65
+ return " ".join(parts[:2]) or "under a minute"
66
+
67
+
68
+ def stamp(dt: datetime) -> str:
69
+ return as_utc(dt).strftime("%d %b %Y, %H:%M UTC")
70
+
71
+
72
+ class Expirer:
73
+ """Deletes scheduled messages when they come due. `start()` runs it in the background."""
74
+
75
+ def __init__(self, ctx, *, notify=None):
76
+ self.ctx = ctx
77
+ self._next: Optional[datetime] = None
78
+ self._wake = asyncio.Event()
79
+ self._task: Optional[asyncio.Task] = None
80
+ self._notify = notify # async fn(user_id, text) used to tell someone a deletion failed for good
81
+
82
+ # ------------------------------------------------------------------------- running
83
+ def start(self) -> None:
84
+ if self._task is None:
85
+ self._task = asyncio.create_task(self.run(), name="expirer")
86
+
87
+ async def stop(self) -> None:
88
+ if self._task is not None:
89
+ self._task.cancel()
90
+ try:
91
+ await self._task
92
+ except (asyncio.CancelledError, Exception):
93
+ pass
94
+ self._task = None
95
+
96
+ def notify(self, when: datetime) -> None:
97
+ """Something was scheduled for `when`: make sure the loop wakes up in time."""
98
+ when = as_utc(when)
99
+ if self._next is None or when < self._next:
100
+ self._next = when
101
+ self._wake.set()
102
+
103
+ async def load(self) -> None:
104
+ """The one look at the database (when the bot starts): when is the first deletion due?"""
105
+ try:
106
+ self._next = await self.ctx.db.next_delete_at()
107
+ except Exception:
108
+ log.exception("could not read the scheduled deletions")
109
+
110
+ async def run(self) -> None:
111
+ await self.load()
112
+ while True:
113
+ delay = None if self._next is None else max(0.0, (self._next - utcnow()).total_seconds())
114
+ try:
115
+ await asyncio.wait_for(self._wake.wait(), timeout=delay)
116
+ except asyncio.TimeoutError:
117
+ pass
118
+ self._wake.clear()
119
+ if self._next is not None and self._next <= utcnow():
120
+ try:
121
+ await self.sweep()
122
+ except asyncio.CancelledError:
123
+ raise
124
+ except Exception:
125
+ log.exception("deleting scheduled messages failed")
126
+ self._next = utcnow() + timedelta(seconds=RETRY_AFTER)
127
+
128
+ # --------------------------------------------------------------------------- work
129
+ async def sweep(self, now: Optional[datetime] = None) -> dict:
130
+ """Delete everything that is due at `now`. Returns {'deleted': n, 'retry': n, 'failed': n}."""
131
+ ctx, db = self.ctx, self.ctx.db
132
+ now = now or utcnow()
133
+ stats = {"deleted": 0, "retry": 0, "failed": 0, "waiting": False}
134
+ due = await db.due_deletes(now)
135
+ if due and ctx.lock.locked(): # a repost / shift is running: don't pull posts out from under it
136
+ stats["waiting"] = True
137
+ self._next = now + timedelta(seconds=LOCK_WAIT)
138
+ return stats
139
+ by_channel: dict = {}
140
+ for row in due:
141
+ by_channel.setdefault(row.channel_id, []).append(row)
142
+ for cid, rows in by_channel.items():
143
+ await self._sweep_channel(cid, rows, now, stats)
144
+ self._next = await db.next_delete_at()
145
+ return stats
146
+
147
+ async def _sweep_channel(self, cid: int, rows: list, now: datetime, stats: dict) -> None:
148
+ ctx, db = self.ctx, self.ctx.db
149
+ ch = await db.get_channel(cid)
150
+ if ch is None:
151
+ for r in rows:
152
+ await db.fail_delete(r.id, "the channel was removed from the bot")
153
+ stats["failed"] += 1
154
+ return
155
+ peer = peer_of(ch)
156
+ ids = sorted({r.message_id for r in rows})
157
+ gone: set = set()
158
+ error: Optional[str] = None
159
+ try:
160
+ for i in range(0, len(ids), 100):
161
+ out = await delete_batch(ctx.client, peer, ids[i : i + 100], None)
162
+ gone |= out.gone
163
+ error = error or out.bot_error
164
+ left = [m for m in ids if m not in gone]
165
+ ub = getattr(ctx, "userbot", None)
166
+ if left and ub is not None and ub.enabled: # the bot may not delete old posts: the userbot tries
167
+ fallback, deleter = await ub.fallback_for(ch)
168
+ try:
169
+ if fallback is not None:
170
+ for i in range(0, len(left), 100):
171
+ out = await delete_batch(ctx.client, peer, left[i : i + 100], fallback)
172
+ gone |= out.gone
173
+ error = out.fallback_error or error
174
+ finally:
175
+ if deleter is not None:
176
+ await deleter.close()
177
+ except Exception as e:
178
+ log.exception("deleting scheduled messages of channel %s failed", cid)
179
+ error = type(e).__name__
180
+ done = [r for r in rows if r.message_id in gone]
181
+ await db.finish_deletes([r.id for r in done])
182
+ await db.forget_posts(cid, sorted(gone))
183
+ stats["deleted"] += len(done)
184
+ for r in rows:
185
+ if r.message_id in gone:
186
+ continue
187
+ why = error or "Telegram did not delete it"
188
+ if r.attempts + 1 >= MAX_ATTEMPTS:
189
+ await db.fail_delete(r.id, why)
190
+ stats["failed"] += 1
191
+ await self._tell(r, ch, why)
192
+ else:
193
+ await db.retry_delete(r.id, at=now + timedelta(seconds=RETRY_AFTER * (r.attempts + 1)), error=why)
194
+ stats["retry"] += 1
195
+
196
+ async def _tell(self, row, ch, why: str) -> None:
197
+ """A deletion failed for good: tell the person who sent the broadcast."""
198
+ text = (
199
+ f"⚠️ I could not delete the expired broadcast post {row.message_id} in <b>{esc(ch.title)}</b> "
200
+ f"({esc(why)}). Delete it by hand, then use β€œOnly forget it in the bot” in /posts."
201
+ )
202
+ try:
203
+ if self._notify is not None:
204
+ await self._notify(row.created_by, text)
205
+ elif row.created_by:
206
+ await self.ctx.client.send_message(row.created_by, text, link_preview=False)
207
+ except Exception:
208
+ log.warning("could not tell user %s about the failed deletion", row.created_by, exc_info=True)
app/handlers/__init__.py ADDED
File without changes
app/handlers/autopost.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/autopost <total> <interval>: post "Episodes 01 to 20", "Episodes 21 to 40", ... with a download button each,
2
+ then ask for the real link of every button. Owners and admins."""
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import re
8
+ import secrets
9
+ import time
10
+ from dataclasses import dataclass, field
11
+ from types import SimpleNamespace
12
+
13
+ from telethon import Button, errors
14
+
15
+ from .. import picker
16
+ from ..autopost import (
17
+ MAX_POSTS,
18
+ PLACEHOLDER_LINK,
19
+ USAGE,
20
+ button_label,
21
+ parse_autopost_args,
22
+ plan_ranges,
23
+ post_buttons,
24
+ post_text,
25
+ ranges_summary,
26
+ title_of,
27
+ )
28
+ from ..common import (
29
+ Ctx,
30
+ UserError,
31
+ clear_state,
32
+ cmd,
33
+ discard_temp,
34
+ edit_callback_message,
35
+ guard,
36
+ on_cb,
37
+ purge_pending,
38
+ say,
39
+ send_post,
40
+ show,
41
+ )
42
+ from ..db import utcnow
43
+ from ..tgutil import esc, explain_rpc, flood_retry, get_rights, peer_of
44
+ from .masslinks import begin_queue
45
+
46
+ log = logging.getLogger(__name__)
47
+
48
+
49
+ @dataclass
50
+ class AutoChoice:
51
+ """/autopost was typed with good numbers; the channel still has to be picked."""
52
+
53
+ user: int
54
+ total: int
55
+ interval: int
56
+ ranges: list
57
+ created: float = field(default_factory=time.monotonic)
58
+
59
+
60
+ @dataclass
61
+ class AutoResult:
62
+ posts: list = field(default_factory=list) # the saved Post rows, in the order they were posted
63
+ failure: str = "" # why it stopped before the end (empty = all posted)
64
+
65
+
66
+ async def post_series(ctx: Ctx, ch, ranges: list, user_id: int, *, delay: float = 1.0, progress=None) -> AutoResult:
67
+ """Send one post per range to `ch` and save each in My posts. Stops at the first post Telegram refuses."""
68
+ res = AutoResult()
69
+ for n, (a, b) in enumerate(ranges, 1):
70
+ text, buttons = post_text(a, b), post_buttons(a, b)
71
+ shape = SimpleNamespace(text=text, entities=[], buttons=buttons, media_file_id=None, link_preview=False)
72
+ try:
73
+ sent = await flood_retry(lambda: send_post(ctx.client, peer_of(ch), shape))
74
+ except errors.RPCError as e:
75
+ res.failure = f"{title_of(a, b)}: {explain_rpc(e)}"
76
+ break
77
+ except Exception as e:
78
+ log.exception("autopost: posting %s failed", title_of(a, b))
79
+ res.failure = f"{title_of(a, b)}: {type(e).__name__}"
80
+ break
81
+ res.posts.append(
82
+ await ctx.db.create_post(
83
+ channel_id=ch.id,
84
+ message_id=sent.id,
85
+ status="sent",
86
+ source="bot",
87
+ created_by=user_id,
88
+ text=text,
89
+ entities=[],
90
+ buttons=buttons,
91
+ link_preview=False,
92
+ sent_at=utcnow(),
93
+ )
94
+ )
95
+ if progress:
96
+ await progress(n)
97
+ if n < len(ranges):
98
+ await asyncio.sleep(delay)
99
+ return res
100
+
101
+
102
+ def register(ctx: Ctx) -> None:
103
+ client, db, cfg = ctx.client, ctx.db, ctx.cfg
104
+
105
+ @client.on(cmd("autopost", args=True))
106
+ @guard(ctx)
107
+ async def h_autopost(event):
108
+ purge_pending(ctx)
109
+ raw = (event.pattern_match.group(1) or "").strip()
110
+ if not raw:
111
+ await say(event, USAGE)
112
+ return
113
+ try:
114
+ total, interval = parse_autopost_args(raw)
115
+ except ValueError as e:
116
+ raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE).replace("&lt;", "<").replace("&gt;", ">"))
117
+ ranges = plan_ranges(total, interval)
118
+ if len(ranges) > MAX_POSTS:
119
+ raise UserError(f"That would be {len(ranges)} posts - at most {MAX_POSTS} at once. Use a bigger interval.")
120
+ chans = await db.list_channels()
121
+ if not chans:
122
+ raise UserError("No channels yet. Register one with /addchannel first.")
123
+ uid = event.sender_id
124
+ await discard_temp(ctx, uid)
125
+ clear_state(ctx, uid)
126
+ token = secrets.token_hex(4)
127
+ ctx.pending[token] = AutoChoice(user=uid, total=total, interval=interval, ranges=ranges)
128
+ await show_picker(event, token, 0)
129
+
130
+ async def show_picker(event, token: str, page: int) -> None:
131
+ choice = ctx.pending.get(token)
132
+ if not isinstance(choice, AutoChoice) or choice.user != event.sender_id:
133
+ raise UserError("That list has expired. Run /autopost again.")
134
+ chans = await db.list_channels()
135
+ if not chans:
136
+ raise UserError("No channels yet. Register one with /addchannel first.")
137
+ first = choice.ranges[0]
138
+ head = (
139
+ f"πŸ“‹ <b>Autopost</b>: {len(choice.ranges)} post(s) for {choice.total} episodes (every {choice.interval})\n"
140
+ f"{ranges_summary(choice.ranges)}\n\n"
141
+ f"Each post says β€œ{esc(title_of(*first))}” with the button β€œ{esc(button_label(*first))}”. The buttons get "
142
+ f"the link {esc(PLACEHOLDER_LINK)} for now; when everything is posted I ask you for the real link of "
143
+ "each button, one after the other.\n\n"
144
+ "πŸ“’ <b>Which channel should I post them in?</b>"
145
+ )
146
+ text, kb = picker.render(
147
+ chans,
148
+ page,
149
+ head=head,
150
+ kind="ap",
151
+ arg=token,
152
+ choose=lambda c: f"apc:{token}:{c.id}",
153
+ extra_rows=[[Button.inline("βœ–οΈ Cancel", f"apx:{token}")]],
154
+ )
155
+ await show(event, text, kb)
156
+
157
+ ctx.pickers["ap"] = show_picker
158
+
159
+ @on_cb(ctx, "apc")
160
+ async def cb_pick(event, parts):
161
+ token, cid = parts[0], int(parts[1])
162
+ choice = ctx.pending.get(token)
163
+ if not isinstance(choice, AutoChoice) or choice.user != event.sender_id:
164
+ raise UserError("That list has expired. Run /autopost again.")
165
+ ch = await db.get_channel(cid)
166
+ if ch is None or not ch.active:
167
+ raise UserError("That channel is not registered any more. Run /autopost again.")
168
+ rights = await get_rights(client, ch)
169
+ if rights is not None and not (rights.admin and rights.post):
170
+ raise UserError("The bot needs the β€œPost messages” admin right in that channel.")
171
+ if ctx.lock.locked():
172
+ raise UserError("Another long job (replace / repost / shift) is still running. Try again in a minute.")
173
+ ctx.pending.pop(token, None) # a second press on the list can't post everything twice
174
+ last = [0.0]
175
+
176
+ async def prog(n):
177
+ if time.monotonic() - last[0] < 3:
178
+ return
179
+ last[0] = time.monotonic()
180
+ try:
181
+ await edit_callback_message(event, f"πŸ“€ Posting in <b>{esc(ch.title)}</b>: {n} of {len(choice.ranges)}…")
182
+ except Exception:
183
+ pass
184
+
185
+ async with ctx.lock:
186
+ res = await post_series(ctx, ch, choice.ranges, event.sender_id, delay=cfg.edit_delay, progress=prog)
187
+ if not res.posts:
188
+ raise UserError(f"Nothing was posted. {res.failure}")
189
+ done = [(p.id, 0, 0) for p in res.posts]
190
+ lines = [
191
+ f"βœ… Posted {len(res.posts)} of {len(choice.ranges)} in <b>{esc(ch.title)}</b>",
192
+ ranges_summary(choice.ranges[: len(res.posts)]),
193
+ f"Their buttons open {esc(PLACEHOLDER_LINK)} until you send the real links.",
194
+ ]
195
+ if res.failure:
196
+ lines.append(f"\n⚠️ Stopped early - {esc(res.failure)}\nThe rest was not posted; run /autopost again for it.")
197
+ await edit_callback_message(event, "\n".join(lines))
198
+ await begin_queue(ctx, event, kind="auto", cid=ch.id, items=done, new=True)
199
+
200
+ @on_cb(ctx, "apx")
201
+ async def cb_cancel(event, parts):
202
+ ctx.pending.pop(parts[0], None)
203
+ await edit_callback_message(event, "Cancelled - nothing was posted.")
app/handlers/backup.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/import (owner only): put a backup made by /export back.
2
+
3
+ The steps: /import β†’ send the file β†’ a preview of what would be added β†’ βœ… Import. Importing only adds, it never
4
+ changes or deletes anything that is here (see app/backup.py for the rules).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ import secrets
10
+ import time
11
+ from dataclasses import dataclass, field
12
+
13
+ from telethon import Button
14
+
15
+ from ..backup import MAX_BYTES, BackupError, ImportPlan, ImportResult, apply_import, parse_backup, plan_import, stamp
16
+ from ..common import (
17
+ Ctx,
18
+ UserError,
19
+ clear_state,
20
+ cmd,
21
+ guard,
22
+ on_cb,
23
+ on_text,
24
+ purge_pending,
25
+ require_owner,
26
+ say,
27
+ set_state,
28
+ show,
29
+ )
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+ ASK = (
34
+ "πŸ“₯ <b>Import a backup</b>\n"
35
+ "Send me the file that /export made (<code>channel-posts-export.json</code>) as your next message - the file "
36
+ "itself, unchanged.\n\n"
37
+ "Importing only <b>adds</b>: channels and posts that are here already are left exactly as they are, and nothing is "
38
+ "deleted. You see what would be added before anything happens. /cancel stops."
39
+ )
40
+
41
+
42
+ @dataclass
43
+ class PendingImport:
44
+ """A backup that was read and is waiting for the owner's OK (or is being imported)."""
45
+
46
+ user: int
47
+ plan: ImportPlan
48
+ running: bool = False
49
+ created: float = field(default_factory=time.monotonic)
50
+
51
+
52
+ def preview_text(plan: ImportPlan) -> str:
53
+ bk = plan.backup
54
+ sent_total = sum(1 for p in bk.posts if p["status"] == "sent")
55
+ drafts_total = len(bk.posts) - sent_total
56
+ made = f" (made {stamp(bk.exported_at)})" if bk.exported_at else ""
57
+ lines = [f"πŸ“₯ <b>Backup file read</b>{made}", ""]
58
+ lines.append(f"πŸ“’ Channels: {len(bk.channels)} in the file - {len(plan.new_channels)} new, {plan.channels_present} here already")
59
+ lines.append(f"πŸ“ Published posts: {sent_total} in the file - {plan.sent_to_add} to add, {plan.posts_present} here already")
60
+ if drafts_total:
61
+ lines.append(f"πŸ—’ Drafts: {drafts_total} in the file - {plan.drafts_to_add} to add, {plan.drafts_present} here already")
62
+ if plan.new_ignored:
63
+ lines.append(f"πŸ™ˆ {len(plan.new_ignored)} post(s) that were made to be forgotten stay forgotten here too")
64
+ if plan.posts_forgotten:
65
+ lines.append(f"πŸ™ˆ {plan.posts_forgotten} post(s) you made this bot forget are not brought back")
66
+ if plan.posts_orphaned:
67
+ lines.append(f"β€’ {plan.posts_orphaned} post(s) belong to a channel that is neither here nor in the file - left out")
68
+ if bk.bad_rows:
69
+ lines.append(f"β€’ {bk.bad_rows} entr{'y' if bk.bad_rows == 1 else 'ies'} of the file could not be read - left out")
70
+ lines.append("")
71
+ if plan.nothing_new:
72
+ lines.append("There is nothing new in this file - everything in it is here already.")
73
+ else:
74
+ lines.append("Nothing that is here now is changed or deleted.")
75
+ if plan.new_channels:
76
+ lines.append(
77
+ "A channel that is new here works only if this bot is an admin there. On a different bot, send "
78
+ "/addchannel for it once afterwards - its posts stay."
79
+ )
80
+ return "\n".join(lines)
81
+
82
+
83
+ def result_text(res: ImportResult) -> str:
84
+ lines = ["βœ… <b>Imported</b>", ""]
85
+ if res.channels_added:
86
+ lines.append(
87
+ f"πŸ“’ {res.channels_added} channel(s) added - check them in /channels "
88
+ "(on a different bot, send /addchannel for each one once so the bot gets its own access)"
89
+ )
90
+ lines.append(f"πŸ“ {res.posts_added} published post(s) added to My posts")
91
+ if res.drafts_added:
92
+ lines.append(f"πŸ—’ {res.drafts_added} draft(s) added")
93
+ if res.marks_added:
94
+ lines.append(f"πŸ™ˆ {res.marks_added} β€œforgotten” mark(s) added")
95
+ if res.skipped_meanwhile:
96
+ lines.append(f"β€’ {res.skipped_meanwhile} post(s) turned up here meanwhile and were left as they are")
97
+ return "\n".join(lines)
98
+
99
+
100
+ def register(ctx: Ctx) -> None:
101
+ client, db = ctx.client, ctx.db
102
+
103
+ @client.on(cmd("import"))
104
+ @guard(ctx, owner=True)
105
+ async def h_import(event):
106
+ set_state(ctx, event.sender_id, "import")
107
+ await say(event, ASK, [[Button.inline("βœ–οΈ Cancel", "cx")]])
108
+
109
+ @on_text(ctx, "import")
110
+ async def got_file(event, st):
111
+ require_owner(ctx, event)
112
+ msg = event.message
113
+ f = getattr(msg, "file", None)
114
+ if f is None:
115
+ raise UserError("Please send the backup FILE (the one /export made), not text. /cancel stops.")
116
+ if (getattr(f, "size", None) or 0) > MAX_BYTES:
117
+ raise UserError(f"That file is larger than {MAX_BYTES // (1024 * 1024)} MB - it is not a backup from /export. Send the right file, or /cancel.")
118
+ note = await say(event, "πŸ“₯ Reading the file…")
119
+ data = await msg.download_media(file=bytes)
120
+ if not isinstance(data, (bytes, bytearray)):
121
+ raise UserError("I could not download that file. Send it again, or /cancel.")
122
+ try:
123
+ plan = await plan_import(db, parse_backup(bytes(data)))
124
+ except BackupError as e:
125
+ raise UserError(f"That file can't be imported: {e}\nSend the right file, or /cancel.")
126
+ clear_state(ctx, event.sender_id)
127
+ purge_pending(ctx)
128
+ if plan.nothing_new:
129
+ await note.edit(preview_text(plan), buttons=None)
130
+ return
131
+ token = secrets.token_hex(4)
132
+ ctx.pending[token] = PendingImport(user=event.sender_id, plan=plan)
133
+ kb = [[Button.inline("βœ… Import", f"imy:{token}"), Button.inline("βœ–οΈ Cancel", f"imx:{token}")]]
134
+ await note.edit(preview_text(plan), buttons=kb)
135
+
136
+ @on_cb(ctx, "imx")
137
+ async def cb_cancel(event, parts):
138
+ require_owner(ctx, event)
139
+ pend = ctx.pending.get(parts[0])
140
+ if isinstance(pend, PendingImport) and not pend.running:
141
+ ctx.pending.pop(parts[0], None)
142
+ await show(event, "Cancelled - nothing was imported.")
143
+
144
+ @on_cb(ctx, "imy")
145
+ async def cb_import(event, parts):
146
+ require_owner(ctx, event)
147
+ pend = ctx.pending.get(parts[0])
148
+ if not isinstance(pend, PendingImport):
149
+ raise UserError("This import has expired (or was done already). Send /import again.")
150
+ if pend.running:
151
+ raise UserError("This import is already running.")
152
+ if ctx.lock.locked():
153
+ raise UserError("Another long job (replace, repost, shift, sync ...) is still running - try again when it has finished.")
154
+ last = [0.0]
155
+
156
+ async def prog(done: int, total: int) -> None:
157
+ if time.monotonic() - last[0] < 3:
158
+ return
159
+ last[0] = time.monotonic()
160
+ try:
161
+ await show(event, f"πŸ“₯ Importing… {done} of {total} post(s)")
162
+ except Exception:
163
+ log.debug("progress update failed", exc_info=True)
164
+
165
+ async with ctx.lock:
166
+ pend.running = True
167
+ try:
168
+ res = await apply_import(db, pend.plan, progress=prog)
169
+ finally:
170
+ ctx.pending.pop(parts[0], None)
171
+ if ctx.syncer is not None:
172
+ ctx.syncer.forget_cache() # the channels that came in are known to the live watch from now on
173
+ await show(event, result_text(res), [[Button.inline("πŸ“š My posts", "pl")]])
app/handlers/basic.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/start /help /cancel /export /userbot, plus the routers for free text and inline-button presses (/import is in backup.py)."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import json
6
+ import logging
7
+
8
+ from telethon import events
9
+
10
+ from ..common import Ctx, UserError, cmd, clear_state, discard_temp, guard, say, show
11
+ from ..picker import PAGE_CB
12
+ from ..richmsg import RICH_HELP, RICH_HELP_HTML
13
+ from ..richtext import CHEAT_SHEET
14
+ from ..tgutil import esc
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ HELP = (
19
+ "<b>Channel Post Bot</b>\n\n"
20
+ "<b>Posts</b>\n"
21
+ "/new - create a post (text or media, with buttons)\n"
22
+ "/posts - your posts and drafts: edit text, caption, media and buttons, or delete them - a published post is deleted in the channel and in My posts (a button post also has β€œMass replace links”)\n"
23
+ "/autopost 114 20 - post β€œEpisodes 01 to 20”, β€œ21 to 40” ... up to 114, each with a download button, then fill in the links\n"
24
+ "/formatting - bold, italic, links, quotes ...: Telegram's own formatting is kept, or type HTML / Markdown instead\n"
25
+ "/rich - rich messages: headings, lists, tables, expandable sections, math, maps, pictures, buttons ... typed as HTML / Markdown, or sent as a Telegram rich message\n"
26
+ "/cancel - stop what you're doing\n\n"
27
+ "<b>Channels</b>\n"
28
+ "/addchannel - register a channel (the bot must be an admin there)\n"
29
+ "/channels - list your channels, or take one out (the bot asks whether its saved posts in My posts are deleted too)\n\n"
30
+ "<b>Owner tools</b>\n"
31
+ "/broadcast [time] - send one message to all channels; with a time (50m, 1h, 5d) it is deleted again from all channels and My posts afterwards\n"
32
+ "/replace <post link> - reply to a new media message to replace that post's media and caption (where Telegram refuses the bot, the userbot does it)\n"
33
+ "/swap @old @new - swap the username inside t.me links (button links and hyperlinks) in all channels\n"
34
+ "/handleswap @old @new - change the username @old written in posts (text, captions, button names) to @new in all channels; links stay\n"
35
+ "/undo - undo the last /swap or /handleswap\n"
36
+ "/repost @old @new - copy every post of a channel in order (links swapped, replies, pins and links between posts kept), then delete the old posts\n"
37
+ "/shift @source @destination [from_id] [to_id] [-c] [-all] [--no-media] - copy posts from one channel into another (buttons kept, listed in My posts); "
38
+ "a channel Telegram restricts (copyright strike) is copied from My posts; "
39
+ "-c: links to the source's posts in all your channels are changed to the copies; -all: the destination also gets the source's name, description and photo; "
40
+ "--no-media: no files, only the text and buttons\n"
41
+ "/sync - compare every channel with My posts right now (posts deleted, edited or added by others, the older posts from before the bot was added; service messages are deleted)\n"
42
+ "/userbot - status of the helper account that, by itself and without asking, deletes and edits the posts the bot is not allowed to\n"
43
+ "/export - download a JSON backup of your channels and posts\n"
44
+ "/import - put a backup made by /export back (only adds: nothing that exists is changed or deleted)"
45
+ "\n/admins - list admins (owner)\n/addadmin 123456789 - add an admin (owner)\n/removeadmin 123456789 - remove an admin (owner)"
46
+ )
47
+
48
+
49
+ def register(ctx: Ctx) -> None:
50
+ client, db = ctx.client, ctx.db
51
+
52
+ @client.on(cmd("admins"))
53
+ @guard(ctx, owner=True)
54
+ async def h_admins(event):
55
+ ids = sorted(ctx.admins | set(ctx.cfg.admins))
56
+ await say(event, "Admins: " + (", ".join(map(str, ids)) if ids else "none"))
57
+
58
+ @client.on(cmd("addadmin"))
59
+ @guard(ctx, owner=True)
60
+ async def h_addadmin(event):
61
+ parts = (event.raw_text or "").split()
62
+ if len(parts) != 2 or not parts[1].isdigit() or int(parts[1]) <= 0:
63
+ raise UserError("Use /addadmin followed by a numeric Telegram user ID.")
64
+ uid = int(parts[1])
65
+ if ctx.cfg.is_owner(uid):
66
+ raise UserError("That user is already an owner.")
67
+ if not await db.add_admin(uid):
68
+ await say(event, f"{uid} is already an admin.")
69
+ return
70
+ ctx.admins.add(uid)
71
+ await say(event, f"Added {uid} as an admin.")
72
+
73
+ @client.on(cmd("removeadmin"))
74
+ @guard(ctx, owner=True)
75
+ async def h_removeadmin(event):
76
+ parts = (event.raw_text or "").split()
77
+ if len(parts) != 2 or not parts[1].isdigit() or int(parts[1]) <= 0:
78
+ raise UserError("Use /removeadmin followed by a numeric Telegram user ID.")
79
+ uid = int(parts[1])
80
+ if not await db.remove_admin(uid):
81
+ await say(event, f"{uid} is not an admin.")
82
+ return
83
+ ctx.admins.discard(uid)
84
+ await say(event, f"Removed {uid} as an admin.")
85
+
86
+ @client.on(cmd("start"))
87
+ @client.on(cmd("help"))
88
+ @guard(ctx)
89
+ async def h_help(event):
90
+ await say(event, HELP)
91
+
92
+ @client.on(cmd("formatting"))
93
+ @guard(ctx)
94
+ async def h_formatting(event):
95
+ await say(event, CHEAT_SHEET)
96
+
97
+ @client.on(cmd("rich"))
98
+ @guard(ctx)
99
+ async def h_rich(event):
100
+ await say(event, RICH_HELP)
101
+ await say(event, RICH_HELP_HTML)
102
+
103
+ @client.on(cmd("cancel"))
104
+ @guard(ctx)
105
+ async def h_cancel(event):
106
+ await discard_temp(ctx, event.sender_id)
107
+ clear_state(ctx, event.sender_id)
108
+ await say(event, "Cancelled.")
109
+
110
+ @client.on(cmd("export"))
111
+ @guard(ctx, owner=True)
112
+ async def h_export(event):
113
+ data = await db.export_all()
114
+ buf = io.BytesIO(json.dumps(data, ensure_ascii=False, indent=1).encode("utf-8"))
115
+ buf.name = "channel-posts-export.json"
116
+ await event.respond(
117
+ f"πŸ“¦ Backup: {len(data['channels'])} channel(s), {len(data['posts'])} post(s). "
118
+ "To put it back (on this bot or a new one), send /import and then this file.",
119
+ file=buf,
120
+ )
121
+
122
+ @client.on(cmd("userbot"))
123
+ @guard(ctx, owner=True)
124
+ async def h_userbot(event):
125
+ ub = ctx.userbot
126
+ if ub is None or not ub.enabled:
127
+ await say(
128
+ event,
129
+ "πŸ€– <b>Userbot: not set up.</b>\n"
130
+ "The bot does its work itself first. If Telegram refuses - deleting posts older than 48 hours, or "
131
+ "editing a post that belongs to another bot (/replace, text and caption edits) - a helper account, "
132
+ "the userbot, takes over by itself, without asking you each time: it joins the channel through an "
133
+ "invite link the bot makes, the bot gives it the β€œDelete messages” or β€œEdit messages of others” right "
134
+ "if it has the β€œAdd new admins” right, and gives the rights back afterwards.\n\n"
135
+ "To set it up: on your own computer run <code>python make_userbot_session.py</code> with a "
136
+ "<b>separate</b> Telegram account, and put the printed text into the bot's secrets as "
137
+ "<code>USERBOT_SESSION</code>. Then send /start to this bot from that account (new media reaches the "
138
+ "userbot through its chat with the bot - that is what makes a replace quick). See the README.",
139
+ )
140
+ return
141
+ if not ub.ready:
142
+ await ub.connect()
143
+ kept = "stays an admin" if ub.keep_admin else "is made admin only while it deletes or edits"
144
+ await say(
145
+ event,
146
+ f"πŸ€– <b>Userbot:</b> {esc(ub.describe())}\nIt {kept} (USERBOT_KEEP_ADMIN).\n"
147
+ "It must have started this bot (/start from that account): new media for an edit goes through its chat "
148
+ "with the bot, which is what makes a big file as quick as a small one.",
149
+ )
150
+
151
+ @client.on(
152
+ events.NewMessage(incoming=True, func=lambda e: e.is_private and not (e.raw_text or "").startswith("/"))
153
+ )
154
+ @guard(ctx)
155
+ async def h_free_text(event):
156
+ st = ctx.state.get(event.sender_id)
157
+ if not st:
158
+ await say(event, "Use /new to create a post or /posts to manage your posts. /help lists everything.")
159
+ return
160
+ fn = ctx.text_handlers.get(st["mode"])
161
+ if fn is None:
162
+ clear_state(ctx, event.sender_id)
163
+ await say(event, "That step is no longer active. Start again with /new.")
164
+ return
165
+ await fn(event, st)
166
+
167
+ @client.on(events.CallbackQuery())
168
+ @guard(ctx)
169
+ async def h_callback(event):
170
+ try:
171
+ await event.answer() # stop the loading spinner right away
172
+ except Exception:
173
+ pass
174
+ data = event.data.decode("utf-8", "replace")
175
+ prefix, *parts = data.split(":")
176
+ fn = ctx.callbacks.get(prefix)
177
+ if fn is None:
178
+ await event.respond("This button is no longer active. Use /new or /posts.")
179
+ return
180
+ await fn(event, parts)
181
+
182
+ async def cb_noop(event, parts):
183
+ await event.answer()
184
+
185
+ async def cb_cancel(event, parts):
186
+ uid = event.sender_id
187
+ await discard_temp(ctx, uid)
188
+ clear_state(ctx, uid)
189
+ await show(event, "Cancelled.")
190
+
191
+ async def cb_channel_page(event, parts):
192
+ """β—€ β–Ά under a channel chooser: draw the same chooser again on another page."""
193
+ kind, arg, page = parts[0], parts[1], int(parts[2])
194
+ draw = ctx.pickers.get(kind)
195
+ if draw is None:
196
+ raise UserError("This list is no longer active. Start the command again.")
197
+ await draw(event, arg, page)
198
+
199
+ ctx.callbacks["noop"] = cb_noop
200
+ ctx.callbacks["cx"] = cb_cancel
201
+ ctx.callbacks[PAGE_CB] = cb_channel_page
app/handlers/broadcast.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/broadcast [time] (also spelled /boardcast): one message to every connected channel. Owner only.
2
+
3
+ With a time (50m, 1h, 5d) the message is deleted again from all the channels - and from My posts - when the time is up;
4
+ without one it stays.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import logging
10
+ import secrets
11
+ import time
12
+ from dataclasses import dataclass, field
13
+ from datetime import datetime, timedelta
14
+ from types import SimpleNamespace
15
+ from typing import Optional
16
+
17
+ from telethon import Button, errors
18
+
19
+ from ..buttons import parse_buttons_text
20
+ from ..common import (
21
+ Ctx,
22
+ UserError,
23
+ clear_state,
24
+ cmd,
25
+ discard_temp,
26
+ edit_callback_message,
27
+ guard,
28
+ on_cb,
29
+ on_text,
30
+ purge_pending,
31
+ require_owner,
32
+ say,
33
+ send_post,
34
+ set_state,
35
+ show,
36
+ )
37
+ from ..db import utcnow
38
+ from ..expiry import human, parse_duration, stamp
39
+ from ..richmsg import block_count, block_labels, is_block_invalid, refused_blocks, rich_of
40
+ from ..tgutil import esc, explain_rpc, flood_retry, peer_of
41
+ from ..ui import CANCEL
42
+ from .panel import markup_note, read_content
43
+
44
+ log = logging.getLogger(__name__)
45
+
46
+ BUTTON_HELP = (
47
+ "βž• <b>Buttons?</b> Send one row per line as <code>Button text - link</code> "
48
+ "(several in one row: separate them with <code> | </code>), or skip."
49
+ )
50
+
51
+
52
+ @dataclass
53
+ class BroadcastDraft:
54
+ """The message is made and previewed; the owner still has to confirm."""
55
+
56
+ user: int
57
+ content: dict # text, entities, media_kind, media_file_id
58
+ buttons: list
59
+ ttl: Optional[int] # seconds until it is deleted again; None = it stays
60
+ created: float = field(default_factory=time.monotonic)
61
+
62
+
63
+ @dataclass
64
+ class BroadcastResult:
65
+ group_id: str
66
+ delete_at: Optional[datetime]
67
+ ttl: Optional[int] = None # seconds it stays; None = for good
68
+ sent: list = field(default_factory=list) # [(channel, message id)]
69
+ failed: list = field(default_factory=list) # [(channel, reason)]
70
+
71
+
72
+ def shape_of(draft: BroadcastDraft) -> SimpleNamespace:
73
+ c = draft.content
74
+ return SimpleNamespace(
75
+ text=c.get("text") or "",
76
+ entities=c.get("entities") or [],
77
+ buttons=draft.buttons,
78
+ media_kind=c.get("media_kind"),
79
+ media_file_id=c.get("media_file_id"),
80
+ link_preview=False,
81
+ )
82
+
83
+
84
+ async def send_broadcast(ctx: Ctx, chans: list, draft: BroadcastDraft, *, delay: float = 1.0, progress=None) -> BroadcastResult:
85
+ """Post the message in every channel, save each copy in My posts and, if it expires, schedule its deletion."""
86
+ db = ctx.db
87
+ delete_at = utcnow() + timedelta(seconds=draft.ttl) if draft.ttl else None
88
+ res = BroadcastResult(group_id=secrets.token_hex(6), delete_at=delete_at, ttl=draft.ttl)
89
+ shape = shape_of(draft)
90
+ for n, ch in enumerate(chans, 1):
91
+ try:
92
+ sent = await flood_retry(lambda: send_post(ctx.client, peer_of(ch), shape))
93
+ except errors.RPCError as e:
94
+ res.failed.append((ch, explain_rpc(e)))
95
+ continue
96
+ except Exception as e:
97
+ log.exception("broadcast: posting in channel %s failed", ch.id)
98
+ res.failed.append((ch, type(e).__name__))
99
+ continue
100
+ await db.create_post(
101
+ channel_id=ch.id,
102
+ message_id=sent.id,
103
+ status="sent",
104
+ source="bot",
105
+ created_by=draft.user,
106
+ text=shape.text,
107
+ entities=shape.entities,
108
+ media_kind=shape.media_kind,
109
+ media_file_id=shape.media_file_id,
110
+ buttons=shape.buttons,
111
+ link_preview=False,
112
+ sent_at=utcnow(),
113
+ )
114
+ res.sent.append((ch, sent.id))
115
+ if delete_at is not None: # saved at once, so a restart in the middle loses nothing
116
+ await db.schedule_deletes(
117
+ [dict(channel_id=ch.id, message_id=sent.id, delete_at=delete_at, group_id=res.group_id, created_by=draft.user)]
118
+ )
119
+ if ctx.expirer is not None:
120
+ ctx.expirer.notify(delete_at)
121
+ if progress:
122
+ await progress(n)
123
+ if n < len(chans):
124
+ await asyncio.sleep(delay)
125
+ return res
126
+
127
+
128
+ def report(res: BroadcastResult, total: int) -> str:
129
+ lines = [f"πŸ“£ <b>Broadcast sent</b> to {len(res.sent)} of {total} channel(s)"]
130
+ lines += [f"βœ… {esc(ch.title)}" for ch, _ in res.sent]
131
+ lines += [f"❌ {esc(ch.title)} - {esc(why)}" for ch, why in res.failed]
132
+ if res.delete_at is not None and res.sent:
133
+ lines += ["", f"πŸ•’ It is deleted from these channels and from My posts in {human(res.ttl)} ({stamp(res.delete_at)})."]
134
+ elif res.sent:
135
+ lines += ["", "πŸ“Œ No time was given, so it stays in the channels."]
136
+ return "\n".join(lines)
137
+
138
+
139
+ def register(ctx: Ctx) -> None:
140
+ client, db, cfg = ctx.client, ctx.db, ctx.cfg
141
+
142
+ @client.on(cmd("broadcast", args=True))
143
+ @client.on(cmd("boardcast", args=True))
144
+ @guard(ctx, owner=True)
145
+ async def h_broadcast(event):
146
+ purge_pending(ctx)
147
+ raw = (event.pattern_match.group(1) or "").strip()
148
+ ttl = None
149
+ if raw:
150
+ try:
151
+ ttl = parse_duration(raw)
152
+ except ValueError as e:
153
+ raise UserError(str(e))
154
+ chans = await db.list_channels()
155
+ if not chans:
156
+ raise UserError("No channels yet. Register one with /addchannel first.")
157
+ uid = event.sender_id
158
+ await discard_temp(ctx, uid)
159
+ set_state(ctx, uid, "bc_content", ttl=ttl)
160
+ when = (
161
+ f"⏳ It is deleted from all channels - and from My posts - {human(ttl)} after it is sent."
162
+ if ttl
163
+ else "πŸ“Œ No time given: it stays in the channels for good. (For a timed one use e.g. <code>/broadcast 1h</code>.)"
164
+ )
165
+ await say(
166
+ event,
167
+ f"πŸ“£ <b>Broadcast</b> to {len(chans)} channel(s)\n{when}\n\n"
168
+ "✍️ <b>Send the message now.</b> Text, or a photo / video / GIF / file with a caption. Formatting is kept "
169
+ "(or type HTML / Markdown - /formatting shows how; rich blocks: /rich).",
170
+ CANCEL,
171
+ )
172
+
173
+ @on_text(ctx, "bc_content")
174
+ async def h_content(event, st):
175
+ m = event.message
176
+ if m.grouped_id and st.get("group") == m.grouped_id:
177
+ return # the other items of an album: only the first one is used
178
+ if m.grouped_id:
179
+ st["group"] = m.grouped_id
180
+ content = await read_content(ctx, event)
181
+ set_state(ctx, event.sender_id, "bc_buttons", ttl=st["ttl"], content=content)
182
+ await say(event, markup_note(content.how) + BUTTON_HELP, [[Button.inline("⏭ No buttons", "brs")], CANCEL[0]])
183
+
184
+ async def confirm_step(event, st, rows: list) -> None:
185
+ uid = event.sender_id
186
+ draft = BroadcastDraft(user=uid, content=st["content"], buttons=rows, ttl=st["ttl"])
187
+ chans = await db.list_channels()
188
+ if not chans:
189
+ clear_state(ctx, uid)
190
+ raise UserError("No channels any more. Register one with /addchannel first.")
191
+ shape = shape_of(draft)
192
+ try:
193
+ await send_post(client, await event.get_input_chat(), shape) # the preview
194
+ except errors.RPCError as e:
195
+ rich, which = rich_of(shape), ""
196
+ if rich is not None and rich.fmt == "blocks" and is_block_invalid(e): # name the blocks Telegram won't take
197
+ bad = await refused_blocks(client, await event.get_input_chat(), rich)
198
+ if bad:
199
+ which = f"\nIt won't take these blocks (of {block_count(rich)}): {block_labels(rich, bad)}."
200
+ raise UserError("❌ " + explain_rpc(e) + which + "\nThe message can't be sent like this - send it again.")
201
+ token = secrets.token_hex(4)
202
+ ctx.pending[token] = draft
203
+ clear_state(ctx, uid)
204
+ names = "\n".join(f"β€’ {esc(c.title)}" for c in chans[:15]) + (f"\nβ€’ … and {len(chans) - 15} more" if len(chans) > 15 else "")
205
+ when = (
206
+ f"⏳ Deleted again {human(draft.ttl)} after sending."
207
+ if draft.ttl
208
+ else "πŸ“Œ Permanent (no time given)."
209
+ )
210
+ await say(
211
+ event,
212
+ f"πŸ‘† That is the message. Send it to <b>{len(chans)}</b> channel(s)?\n{names}\n\n{when}",
213
+ [[Button.inline("πŸ“£ Send to all channels", f"brc:{token}")], [Button.inline("βœ–οΈ Cancel", f"brn:{token}")]],
214
+ )
215
+
216
+ @on_text(ctx, "bc_buttons")
217
+ async def h_buttons(event, st):
218
+ if event.message.grouped_id:
219
+ return
220
+ try:
221
+ rows = parse_buttons_text(event.raw_text or "")
222
+ except ValueError as e:
223
+ raise UserError(f"❌ {e}\n\nTry again, or tap β€œNo buttons”.")
224
+ if not rows:
225
+ raise UserError("Send at least one button as β€œText - link”, or tap β€œNo buttons”.")
226
+ await confirm_step(event, st, rows)
227
+
228
+ @on_cb(ctx, "brs")
229
+ async def cb_no_buttons(event, parts):
230
+ require_owner(ctx, event)
231
+ st = ctx.state.get(event.sender_id)
232
+ if not st or st.get("mode") != "bc_buttons":
233
+ raise UserError("That step is no longer active. Start again with /broadcast.")
234
+ await confirm_step(event, st, [])
235
+
236
+ @on_cb(ctx, "brn")
237
+ async def cb_cancel(event, parts):
238
+ require_owner(ctx, event)
239
+ ctx.pending.pop(parts[0], None)
240
+ await show(event, "Cancelled - nothing was sent.")
241
+
242
+ @on_cb(ctx, "brc")
243
+ async def cb_send(event, parts):
244
+ require_owner(ctx, event)
245
+ token = parts[0]
246
+ draft = ctx.pending.get(token)
247
+ if not isinstance(draft, BroadcastDraft) or draft.user != event.sender_id:
248
+ raise UserError("That broadcast has expired. Start again with /broadcast.")
249
+ chans = await db.list_channels()
250
+ if not chans:
251
+ raise UserError("No channels any more. Register one with /addchannel first.")
252
+ if ctx.lock.locked():
253
+ raise UserError("Another long job (replace / repost / shift) is still running. Try again in a minute.")
254
+ ctx.pending.pop(token, None) # a second press can't send it twice
255
+ last = [0.0]
256
+
257
+ async def prog(n):
258
+ if time.monotonic() - last[0] < 3:
259
+ return
260
+ last[0] = time.monotonic()
261
+ try:
262
+ await edit_callback_message(event, f"πŸ“£ Sending… {n} of {len(chans)} channel(s)")
263
+ except Exception:
264
+ pass
265
+
266
+ async with ctx.lock:
267
+ res = await send_broadcast(ctx, chans, draft, delay=cfg.edit_delay, progress=prog)
268
+ await edit_callback_message(event, report(res, len(chans)))
app/handlers/channels.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Channel registration: /addchannel, /channels."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import re
6
+
7
+ from telethon import Button, events, types
8
+
9
+ from .. import picker
10
+ from ..channelref import parse_channel_ref
11
+ from ..common import Ctx, UserError, clear_state, cmd, guard, on_cb, on_text, require_owner, say, set_state, show
12
+ from ..tgutil import esc, get_rights
13
+ from ..ui import CANCEL
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ ADD_HELP = (
18
+ "πŸ“’ <b>Add a channel</b>\n"
19
+ "1. Make the bot an admin of the channel with the rights <i>Post messages</i>, <i>Edit messages of others</i> "
20
+ "and <i>Delete messages</i>.\n"
21
+ "2. Then <b>forward any post from that channel to me</b>, or send its @username (public channels).\n\n"
22
+ "Tip for private channels: if forwarding doesn't work, post something in the channel while the bot is "
23
+ "running, then forward that post."
24
+ )
25
+ NEEDS_ACCESS = (
26
+ "I can see the channel, but Telegram hasn't given me its access details yet. Post something in the "
27
+ "channel while the bot is running (or send the @username if it's public), then forward a post again."
28
+ )
29
+
30
+
31
+ def rights_line(r) -> str:
32
+ if r is None:
33
+ return "rights unknown"
34
+ if not r.admin:
35
+ return "⚠️ not an admin there"
36
+ ok = lambda v: "βœ…" if v else "❌" # noqa: E731
37
+ return f"post {ok(r.post)} Β· edit others' posts {ok(r.edit)} Β· delete {ok(r.delete)}"
38
+
39
+
40
+ def register(ctx: Ctx) -> None:
41
+ client, db = ctx.client, ctx.db
42
+
43
+ # remember channels whose full details (access hash) we have seen in updates
44
+ @client.on(events.NewMessage(func=lambda e: bool(e.is_channel) and not e.is_group))
45
+ async def watch_channels(event):
46
+ try:
47
+ chat = await event.get_chat()
48
+ if isinstance(chat, types.Channel) and chat.access_hash and not getattr(chat, "min", False):
49
+ prev = ctx.seen_channels.get(chat.id)
50
+ ctx.seen_channels[chat.id] = chat
51
+ if prev is None or prev.access_hash != chat.access_hash:
52
+ await db.touch_channel_hash(chat.id, chat.access_hash)
53
+ except Exception: # pragma: no cover
54
+ log.debug("channel watcher failed", exc_info=True)
55
+
56
+ @client.on(cmd("addchannel"))
57
+ @guard(ctx, owner=True)
58
+ async def h_addchannel(event):
59
+ set_state(ctx, event.sender_id, "add_channel")
60
+ await say(event, ADD_HELP, CANCEL)
61
+
62
+ @on_text(ctx, "add_channel")
63
+ async def h_add_channel(event, st):
64
+ m = event.message
65
+ ent = None
66
+ fwd = m.forward
67
+ if fwd is not None and isinstance(getattr(fwd, "chat", None), types.Channel):
68
+ ent = fwd.chat
69
+ if getattr(ent, "min", False) or not getattr(ent, "access_hash", None):
70
+ ent = ctx.seen_channels.get(ent.id, ent)
71
+ else:
72
+ ref = parse_channel_ref(m.raw_text or "")
73
+ if ref is None:
74
+ raise UserError("Forward a post from the channel to me, or send its @username.")
75
+ if isinstance(ref, int):
76
+ ent = ctx.seen_channels.get(ref)
77
+ if ent is None:
78
+ try:
79
+ ent = await client.get_entity(ref if isinstance(ref, str) else types.PeerChannel(ref))
80
+ except Exception:
81
+ ent = None
82
+ if not isinstance(ent, types.Channel):
83
+ raise UserError("I couldn't find that channel.\n\n" + re.sub(r"<[^>]+>", "", ADD_HELP))
84
+ if not ent.broadcast:
85
+ raise UserError("That is a group, not a channel. Only channels are supported.")
86
+ if not ent.access_hash or getattr(ent, "min", False):
87
+ raise UserError(NEEDS_ACCESS)
88
+ rights = await get_rights(client, ent)
89
+ if rights is not None and not rights.admin:
90
+ raise UserError("The bot is not an admin of that channel yet. Add it as an admin, then try again.")
91
+ await db.save_channel(ent.id, ent.access_hash, ent.title or "", ent.username, event.sender_id)
92
+ clear_state(ctx, event.sender_id)
93
+ warn = ""
94
+ if rights is not None and not (rights.post and rights.edit and rights.delete):
95
+ warn = "\n\n⚠️ Missing rights: give the bot <i>Post</i>, <i>Edit messages of others</i> and <i>Delete</i> so everything works."
96
+ await say(
97
+ event,
98
+ f"βœ… Added <b>{esc(ent.title or '')}</b>\n{rights_line(rights)}{warn}\n\nCreate a post with /new.",
99
+ )
100
+
101
+ async def show_channels(event, arg: str = "", page: int = 0) -> None:
102
+ """The list of channels; the owner's number buttons choose one to remove."""
103
+ chans = await db.list_channels()
104
+ if not chans:
105
+ raise UserError("No channels yet. Use /addchannel.")
106
+ owner = ctx.cfg.is_owner(event.sender_id)
107
+ text, kb = picker.render(
108
+ chans,
109
+ page,
110
+ head="πŸ“’ <b>Your channels</b>",
111
+ kind="ch",
112
+ choose=(lambda c: f"chd:{c.id}") if owner else None,
113
+ with_username=True,
114
+ hint="To take a channel out of the bot, tap its number.",
115
+ )
116
+ await show(event, text, kb or None)
117
+
118
+ ctx.pickers["ch"] = show_channels
119
+
120
+ @client.on(cmd("channels"))
121
+ @guard(ctx)
122
+ async def h_channels(event):
123
+ await show_channels(event)
124
+
125
+ @on_cb(ctx, "chd")
126
+ async def cb_remove_channel(event, parts):
127
+ """A number was tapped: ask what becomes of the channel's saved posts before it is taken out of the bot."""
128
+ require_owner(ctx, event)
129
+ ch = await db.get_channel(int(parts[0]))
130
+ if ch is None or not ch.active:
131
+ await show_channels(event)
132
+ return
133
+ back = Button.inline("πŸ”™ Back", f"{picker.PAGE_CB}:ch::0")
134
+ n = await db.count_channel_posts(ch.id)
135
+ if not n: # nothing saved: nothing to ask about
136
+ await show(
137
+ event,
138
+ f"βž– Take <b>{esc(ch.title)}</b> out of the bot?\nIt has no saved posts. You can add it again with /addchannel.",
139
+ [[Button.inline("βœ… Yes, remove it", f"chy:{ch.id}:0"), back]],
140
+ )
141
+ return
142
+ await show(
143
+ event,
144
+ f"βž– Take <b>{esc(ch.title)}</b> out of the bot.\n\n"
145
+ f"Do you also want to delete its saved posts - the {n} post(s) My posts holds for this channel? "
146
+ "Nothing is deleted in the channel itself.",
147
+ [
148
+ [Button.inline("πŸ—‘ Yes, delete them too", f"chy:{ch.id}:1"), Button.inline("πŸ“¦ No, keep them", f"chy:{ch.id}:0")],
149
+ [back],
150
+ ],
151
+ )
152
+
153
+ @on_cb(ctx, "chy")
154
+ async def cb_remove_channel_yes(event, parts):
155
+ """chy:<channel>:1 removes the channel and deletes its saved posts, chy:<channel>:0 (or an old button without the
156
+ second part) removes only the channel and keeps them."""
157
+ require_owner(ctx, event)
158
+ cid = int(parts[0])
159
+ wipe = len(parts) > 1 and parts[1] == "1"
160
+ ch = await db.get_channel(cid)
161
+ name = f"<b>{esc(ch.title)}</b>" if ch is not None else "The channel"
162
+ await db.set_channel_active(cid, False)
163
+ gone = 0
164
+ sy = ctx.syncer
165
+ if sy is not None:
166
+ sy.forget_cache()
167
+ if wipe:
168
+ await show(event, f"⏳ Deleting the saved posts of {name}…")
169
+ # no look at the channel may be saving posts while they are deleted (it would bring some back)
170
+ if sy is not None:
171
+ async with sy.exclusive():
172
+ gone = await db.delete_channel_data(cid)
173
+ else:
174
+ gone = await db.delete_channel_data(cid)
175
+ ctx.sync_ignore.difference_update({k for k in ctx.sync_ignore if k[0] == cid})
176
+ text = (
177
+ f"βœ… {name} was removed from the bot, and its {gone} saved post(s) were deleted from My posts. Nothing was deleted "
178
+ "in the channel. If you add it again with /addchannel, its posts are read in again."
179
+ )
180
+ else:
181
+ text = f"βœ… {name} was removed from the bot. Its saved posts are kept; add it again with /addchannel and they are there again."
182
+ await show(event, text)
app/handlers/checkbtn.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check buttons (owner only): compare the buttons saved in the bot with what a channel really shows, and repair."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import time
6
+
7
+ from telethon import Button, errors
8
+
9
+ from ..buttons_sync import fix_buttons, scan_buttons
10
+ from ..common import Ctx, UserError, on_cb, require_owner, show
11
+ from ..tgutil import esc
12
+
13
+ log = logging.getLogger(__name__)
14
+ SAMPLE = 12
15
+
16
+
17
+ def register(ctx: Ctx) -> None:
18
+ client, db, cfg = ctx.client, ctx.db, ctx.cfg
19
+
20
+ async def load(parts):
21
+ ch = await db.get_channel(int(parts[0]))
22
+ if ch is None:
23
+ raise UserError("That channel is not registered.")
24
+ if ctx.lock.locked():
25
+ raise UserError("Another long job (replace / repost) is still running.")
26
+ return ch
27
+
28
+ def throttled(event, make_text, every: float = 3.0):
29
+ last = [0.0]
30
+
31
+ async def upd(obj, force: bool = False) -> None:
32
+ now = time.monotonic()
33
+ if not force and now - last[0] < every:
34
+ return
35
+ last[0] = now
36
+ try:
37
+ await show(event, make_text(obj))
38
+ except errors.MessageNotModifiedError:
39
+ pass
40
+ except Exception:
41
+ log.debug("progress update failed", exc_info=True)
42
+
43
+ return upd
44
+
45
+ @on_cb(ctx, "pk")
46
+ async def cb_check(event, parts):
47
+ require_owner(ctx, event)
48
+ ch = await load(parts)
49
+ title = esc(ch.title)
50
+ async with ctx.lock:
51
+ await show(event, f"πŸ”§ Checking the buttons of <b>{title}</b>…")
52
+ posts = await db.sent_posts(ch.id)
53
+ scan = await scan_buttons(
54
+ client, ch, posts, progress=throttled(event, lambda s: f"πŸ”§ Checking <b>{title}</b>: {s.fine + len(s.bad) + len(s.gone)}/{s.total}…")
55
+ )
56
+ lines = [f"πŸ”§ <b>{title}</b> - checked {scan.total} post(s) that have link buttons."]
57
+ kb = []
58
+ if not scan.total:
59
+ lines.append("None of the saved posts has link buttons, so there is nothing to check.")
60
+ else:
61
+ lines.append(f"βœ… {scan.fine} show their buttons correctly.")
62
+ if scan.bad:
63
+ ids = ", ".join(f"#{p.message_id}" for p, _, _ in scan.bad[:SAMPLE])
64
+ more = "…" if len(scan.bad) > SAMPLE else ""
65
+ lines.append(
66
+ f"⚠️ <b>{len(scan.bad)}</b> are saved with buttons here, but the channel shows them without those buttons "
67
+ f"(or with different links): {ids}{more}"
68
+ )
69
+ kb.append([Button.inline(f"πŸ”§ Fix {len(scan.bad)} post(s)", f"pkf:{ch.id}")])
70
+ elif scan.total:
71
+ lines.append("Everything matches.")
72
+ if scan.gone:
73
+ ids = ", ".join(f"#{p.message_id}" for p in scan.gone[:SAMPLE])
74
+ lines.append(
75
+ f"ℹ️ {len(scan.gone)} saved post(s) no longer exist in the channel ({ids}{'…' if len(scan.gone) > SAMPLE else ''})."
76
+ )
77
+ kb.append([Button.inline("πŸ”™ Back", f"pc:{ch.id}:0")])
78
+ await show(event, "\n".join(lines), kb)
79
+
80
+ @on_cb(ctx, "pkf")
81
+ async def cb_fix(event, parts):
82
+ require_owner(ctx, event)
83
+ ch = await load(parts)
84
+ title = esc(ch.title)
85
+ async with ctx.lock:
86
+ await show(event, f"πŸ”§ Looking again at <b>{title}</b>…")
87
+ scan = await scan_buttons(client, ch, await db.sent_posts(ch.id))
88
+ if not scan.bad:
89
+ res = None
90
+ else:
91
+ total = len(scan.bad)
92
+ res = await fix_buttons(
93
+ client,
94
+ ch,
95
+ scan.bad,
96
+ delay=cfg.edit_delay,
97
+ progress=throttled(event, lambda r: f"πŸ”§ Fixing <b>{title}</b>: {r.fixed + r.already}/{total}…"),
98
+ )
99
+ if res is None:
100
+ text = f"βœ… <b>{title}</b>: all buttons match now - nothing to fix."
101
+ else:
102
+ lines = [f"πŸ”§ <b>{title}</b> - put the saved buttons back on <b>{res.fixed}</b> post(s)."]
103
+ if res.nudged:
104
+ lines.append(f"{res.nudged} of them needed a second edit before Telegram showed the buttons.")
105
+ if res.already:
106
+ lines.append(f"{res.already} were already fine when I got to them.")
107
+ if res.gone:
108
+ lines.append(f"{res.gone} no longer exist in the channel.")
109
+ if res.failed:
110
+ sample = ", ".join(f"#{m} {esc(n)}" for m, n in res.failed[:8])
111
+ lines.append(f"⚠️ <b>{len(res.failed)} failed</b> ({sample}{'…' if len(res.failed) > 8 else ''}).")
112
+ if res.aborted:
113
+ lines.append(f"Stopped early: Telegram refused {esc(res.aborted)} several times in a row.")
114
+ text = "\n".join(lines)
115
+ await show(event, text, [[Button.inline("πŸ”§ Check again", f"pk:{ch.id}"), Button.inline("πŸ”™ Back", f"pc:{ch.id}:0")]])
app/handlers/create.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/new: create a post, with the episode-range auto-suggestion."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+
6
+ from telethon import Button
7
+
8
+ from .. import picker
9
+ from ..buttons import norm_url, parse_buttons_text, set_field
10
+ from ..common import Ctx, UserError, clear_state, cmd, discard_temp, guard, on_cb, on_text, say, set_state, show
11
+ from ..suggest import make_suggestion
12
+ from ..tgutil import esc, short
13
+ from ..ui import CANCEL, KIND_NAME
14
+ from .panel import markup_note, read_content, show_panel
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ BUTTON_HELP = (
19
+ "βž• <b>Now the buttons</b>\n"
20
+ "Send one row per line as <code>Button text - link</code>.\n"
21
+ "Several buttons in one row: separate them with <code> | </code>.\n\n"
22
+ "Example:\n<code>Download Episodes 01 to 20 - https://t.me/yourbot?start=abc</code>\n\n"
23
+ "Or send /skip to post without buttons."
24
+ )
25
+
26
+
27
+ def register(ctx: Ctx) -> None:
28
+ client, db = ctx.client, ctx.db
29
+
30
+ async def ask_content(event, cid: int) -> None:
31
+ set_state(ctx, event.sender_id, "new_content", cid=cid)
32
+ await show(
33
+ event,
34
+ "✍️ <b>Send the post now.</b>\nText, or a photo / video / GIF / file with a caption. "
35
+ "Formatting (bold, links, spoilers...) is kept. No Telegram editor at hand? Type HTML or Markdown - /formatting shows how; "
36
+ "headings, lists, tables, math and the other rich blocks: /rich.",
37
+ CANCEL,
38
+ )
39
+
40
+ async def start_for_channel(event, cid: int) -> None:
41
+ ch = await db.get_channel(cid)
42
+ if ch is None:
43
+ raise UserError("That channel is not registered. Use /addchannel.")
44
+ sug = await make_suggestion(db, cid)
45
+ if sug is None:
46
+ await ask_content(event, cid)
47
+ return
48
+ lines = [
49
+ f"πŸ’‘ <b>Suggestion for {esc(ch.title)}</b>",
50
+ f"Your last button post: <code>{esc(sug.prev_label)}</code>",
51
+ "The next one would be:",
52
+ ]
53
+ if (sug.text or "").strip():
54
+ lines.append(f"β€’ Message: <i>{esc(short(sug.text, 120))}</i>")
55
+ lines.append(f"β€’ Button: <code>{esc(sug.new_label)}</code>")
56
+ if sug.media_kind:
57
+ lines.append(f"β€’ Media: same {KIND_NAME.get(sug.media_kind, 'file')} as that post (you can change it before publishing)")
58
+ lines.append("\nUse it and I'll only ask for the button link.")
59
+ kb = [
60
+ [Button.inline("βœ… Use suggestion", f"ns:{cid}"), Button.inline("✏️ Customize", f"nn:{cid}")],
61
+ CANCEL[0],
62
+ ]
63
+ await show(event, "\n".join(lines), kb)
64
+
65
+ async def ask_link(event, post, pos) -> None:
66
+ r, c = pos
67
+ label = post.buttons[r][c]["t"]
68
+ await say(
69
+ event,
70
+ f"πŸ”— Send the link for the button <code>{esc(label)}</code>\n"
71
+ "(for example <code>https://t.me/yourbot?start=abc</code>)",
72
+ CANCEL,
73
+ )
74
+
75
+ @client.on(cmd("new"))
76
+ @guard(ctx)
77
+ async def h_new(event):
78
+ uid = event.sender_id
79
+ await discard_temp(ctx, uid)
80
+ clear_state(ctx, uid)
81
+ chans = await db.list_channels()
82
+ if not chans:
83
+ raise UserError("No channels yet. Register one with /addchannel first.")
84
+ if len(chans) == 1:
85
+ await start_for_channel(event, chans[0].id)
86
+ return
87
+ await show_picker(event, "", 0)
88
+
89
+ async def show_picker(event, arg: str, page: int) -> None:
90
+ chans = await db.list_channels()
91
+ if not chans:
92
+ raise UserError("No channels yet. Register one with /addchannel first.")
93
+ text, kb = picker.render(
94
+ chans, page, head="πŸ“’ <b>Which channel is this post for?</b>", kind="nc", choose=lambda c: f"nc:{c.id}", extra_rows=CANCEL
95
+ )
96
+ await show(event, text, kb)
97
+
98
+ ctx.pickers["nc"] = show_picker
99
+
100
+ @on_cb(ctx, "nc")
101
+ async def cb_channel(event, parts):
102
+ await discard_temp(ctx, event.sender_id)
103
+ await start_for_channel(event, int(parts[0]))
104
+
105
+ @on_cb(ctx, "nn")
106
+ async def cb_customize(event, parts):
107
+ await ask_content(event, int(parts[0]))
108
+
109
+ @on_cb(ctx, "ns")
110
+ async def cb_use_suggestion(event, parts):
111
+ uid, cid = event.sender_id, int(parts[0])
112
+ sug = await make_suggestion(db, cid)
113
+ if sug is None:
114
+ raise UserError("There is nothing to suggest any more - send the post yourself with /new.")
115
+ await discard_temp(ctx, uid)
116
+ post = await db.create_post(
117
+ channel_id=cid,
118
+ created_by=uid,
119
+ status="draft",
120
+ source="bot",
121
+ text=sug.text,
122
+ entities=sug.entities,
123
+ buttons=sug.buttons,
124
+ media_kind=sug.media_kind,
125
+ media_file_id=sug.media_file_id,
126
+ link_preview=False,
127
+ )
128
+ set_state(ctx, uid, "new_link", pid=post.id, pending=list(sug.pending), temp=True)
129
+ await show(event, f"βœ… Using the suggestion: <code>{esc(sug.new_label)}</code>")
130
+ await ask_link(event, post, sug.pending[0])
131
+
132
+ @on_text(ctx, "new_link")
133
+ async def h_new_link(event, st):
134
+ url = norm_url(event.raw_text or "")
135
+ if not url:
136
+ raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc")
137
+ post = await db.get_post(st["pid"])
138
+ if post is None:
139
+ clear_state(ctx, event.sender_id)
140
+ raise UserError("That draft is gone. Start again with /new.")
141
+ r, c = st["pending"][0]
142
+ post = await db.update_post(post.id, buttons=set_field(post.buttons, r, c, u=url))
143
+ st["pending"] = st["pending"][1:]
144
+ if st["pending"]:
145
+ await ask_link(event, post, st["pending"][0])
146
+ return
147
+ clear_state(ctx, event.sender_id)
148
+ await show_panel(ctx, event, post.id, note="βœ… Ready. Preview it, or tap <b>Publish</b>.", new=True)
149
+
150
+ @on_text(ctx, "new_content")
151
+ async def h_new_content(event, st):
152
+ m = event.message
153
+ if m.grouped_id and st.get("group") == m.grouped_id:
154
+ return # the other items of an album: only the first one is used
155
+ if m.grouped_id:
156
+ st["group"] = m.grouped_id
157
+ content = await read_content(ctx, event)
158
+ post = await db.create_post(
159
+ channel_id=st["cid"],
160
+ created_by=event.sender_id,
161
+ status="draft",
162
+ source="bot",
163
+ buttons=[],
164
+ link_preview=False,
165
+ **content,
166
+ )
167
+ set_state(ctx, event.sender_id, "new_buttons", pid=post.id, temp=True)
168
+ await say(event, markup_note(content.how) + BUTTON_HELP, CANCEL)
169
+
170
+ @on_text(ctx, "new_buttons")
171
+ async def h_new_buttons(event, st):
172
+ if event.message.grouped_id:
173
+ return
174
+ try:
175
+ rows = parse_buttons_text(event.raw_text or "")
176
+ except ValueError as e:
177
+ raise UserError(f"❌ {e}\n\nTry again, or send /skip.")
178
+ if not rows:
179
+ raise UserError("Send at least one button as β€œText - link”, or /skip.")
180
+ await db.update_post(st["pid"], buttons=rows)
181
+ clear_state(ctx, event.sender_id)
182
+ await show_panel(ctx, event, st["pid"], note="βœ… Ready. Preview it, or tap <b>Publish</b>.", new=True)
183
+
184
+ @client.on(cmd("skip"))
185
+ @guard(ctx)
186
+ async def h_skip(event):
187
+ st = ctx.state.get(event.sender_id)
188
+ if not st or st["mode"] != "new_buttons":
189
+ raise UserError("There is nothing to skip right now.")
190
+ clear_state(ctx, event.sender_id)
191
+ await show_panel(ctx, event, st["pid"], note="βœ… Ready (no buttons). Preview it, or tap <b>Publish</b>.", new=True)
app/handlers/masslinks.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """New links, one button after the other.
2
+
3
+ * "Mass replace links" in the panel of a published button post: the bot asks for a new link for that post's button and,
4
+ after each answer, for the next button post of the channel (posts without a link button are skipped).
5
+ * /autopost uses the same steps to ask for the real link of every button it posted.
6
+
7
+ The position in the list lives in the user's state; each answer changes the button in the channel at once.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+
13
+ from telethon import Button, errors
14
+
15
+ from ..buttons import link_positions, norm_url, set_field
16
+ from ..common import Ctx, UserError, clear_state, is_cb, on_cb, on_text, say, set_state, show
17
+ from ..tgutil import build_markup, edit_raw, esc, explain_rpc, flood_retry, peer_of, post_link, short
18
+ from .panel import load_post
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+ MODE = "link_queue"
23
+ HEADINGS = {"mass": "πŸ”— <b>Mass replace links</b>", "auto": "πŸ”— <b>Links for the new posts</b>"}
24
+
25
+
26
+ async def set_link(ctx: Ctx, post, ch, r: int, c: int, url: str):
27
+ """Point button (r, c) of a published post at `url`: the buttons of the channel message change (only the buttons,
28
+ the text stays as it is), then the saved post follows."""
29
+ rows = set_field(post.buttons, r, c, u=url)
30
+ if post.status == "sent" and post.message_id:
31
+ try:
32
+ await flood_retry(lambda: edit_raw(ctx.client, peer_of(ch), post.message_id, markup=build_markup(rows)))
33
+ except errors.MessageNotModifiedError:
34
+ pass # it already had that link
35
+ except errors.RPCError as e:
36
+ raise UserError("❌ " + explain_rpc(e) + "\nThe link of this button was NOT changed.")
37
+ return await ctx.db.update_post(post.id, buttons=rows)
38
+
39
+
40
+ def mass_items(posts) -> list:
41
+ """[(post id, row, column)] of every link button in `posts`, in the order given."""
42
+ return [[p.id, r, c] for p in posts for r, c in link_positions(p.buttons)]
43
+
44
+
45
+ async def current_target(ctx: Ctx, st: dict):
46
+ """(post, channel, row, column) the list is at, moving past buttons that are gone; None when the list is finished."""
47
+ while st["i"] < len(st["items"]):
48
+ pid, r, c = st["items"][st["i"]]
49
+ post = await ctx.db.get_post(pid)
50
+ if post is not None and post.status == "sent" and post.message_id and (r, c) in link_positions(post.buttons):
51
+ ch = await ctx.db.get_channel(post.channel_id)
52
+ if ch is not None:
53
+ return post, ch, r, c
54
+ st["i"] += 1
55
+ st["gone"] += 1
56
+ return None
57
+
58
+
59
+ def summary(st: dict, stopped: bool) -> str:
60
+ left = max(0, len(st["items"]) - st["i"]) if stopped else 0
61
+ bits = [f"{st['done']} link(s) replaced"]
62
+ if st["skipped"]:
63
+ bits.append(f"{st['skipped']} skipped")
64
+ if st["gone"]:
65
+ bits.append(f"{st['gone']} button(s) no longer there")
66
+ if left:
67
+ bits.append(f"{left} not asked")
68
+ return ("Stopped. " if stopped else "βœ… <b>All done.</b> ") + ", ".join(bits) + "."
69
+
70
+
71
+ def prompt_for(st: dict, post, ch, r: int, c: int) -> str:
72
+ total = len(st["items"])
73
+ b = post.buttons[r][c]
74
+ lines = [f"{HEADINGS[st['kind']]} Β· <b>{esc(ch.title)}</b> ({st['i'] + 1} of {total})", ""]
75
+ where = f"Post #{post.id}"
76
+ if post.message_id:
77
+ where = f'<a href="{post_link(ch, post.message_id)}">Post #{post.id}</a>'
78
+ several = len(link_positions(post.buttons))
79
+ label = f"β€œ{esc(short(b.get('t') or '', 60))}”"
80
+ lines.append(f"{where} Β· button {label}" + (f" (button {r + 1}.{c + 1} of {several} links)" if several > 1 else ""))
81
+ lines.append(f"Now: <code>{esc(b.get('u') or '')}</code>")
82
+ lines += ["", "πŸ”— Send the new link for this button."]
83
+ return "\n".join(lines)
84
+
85
+
86
+ async def ask(ctx: Ctx, event, st: dict, lead: str = "", *, new: bool = True) -> None:
87
+ """Ask for the next link, or finish. `lead` (what just happened) goes in front, in the same message."""
88
+ tgt = await current_target(ctx, st)
89
+ kb_done = [[Button.inline("πŸ“š My posts", "pl")]]
90
+ send = say if (new or not is_cb(event)) else show
91
+ if tgt is None:
92
+ clear_state(ctx, event.sender_id)
93
+ await send(event, (lead + "\n\n" if lead else "") + summary(st, False), kb_done)
94
+ return
95
+ post, ch, r, c = tgt
96
+ kb = [[Button.inline("⏭ Skip this one", f"lqs:{st['i']}"), Button.inline("βœ–οΈ Cancel", "lqx")]]
97
+ await send(event, (lead + "\n\n" if lead else "") + prompt_for(st, post, ch, r, c), kb)
98
+
99
+
100
+ async def begin_queue(ctx: Ctx, event, *, kind: str, cid: int, items: list, lead: str = "", new: bool = True) -> None:
101
+ """Start asking: `items` is [(post id, row, column)] in the order the links are wanted."""
102
+ st = set_state(ctx, event.sender_id, MODE, kind=kind, cid=cid, items=[list(i) for i in items], i=0, done=0, skipped=0, gone=0)
103
+ await ask(ctx, event, st, lead, new=new)
104
+
105
+
106
+ def register(ctx: Ctx) -> None:
107
+ db = ctx.db
108
+
109
+ # ------------------------------------------------------------- the panel option
110
+ @on_cb(ctx, "mlp")
111
+ async def cb_mass_start(event, parts):
112
+ post, ch = await load_post(ctx, parts[0])
113
+ if post.status != "sent" or not post.message_id:
114
+ raise UserError("Mass replace works on published posts only.")
115
+ if not link_positions(post.buttons):
116
+ raise UserError("This post has no button with a link.")
117
+ posts = await db.sent_posts_from(ch.id, post.message_id)
118
+ await begin_queue(ctx, event, kind="mass", cid=ch.id, items=mass_items(posts), new=False)
119
+
120
+ # ---------------------------------------------------------------- the answers
121
+ @on_text(ctx, MODE)
122
+ async def h_link(event, st):
123
+ url = norm_url(event.raw_text or "")
124
+ if not url:
125
+ raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc")
126
+ tgt = await current_target(ctx, st)
127
+ if tgt is None: # everything this list was about has vanished meanwhile
128
+ await ask(ctx, event, st)
129
+ return
130
+ post, ch, r, c = tgt
131
+ label = post.buttons[r][c].get("t") or ""
132
+ await set_link(ctx, post, ch, r, c, url)
133
+ st["i"] += 1
134
+ st["done"] += 1
135
+ await ask(ctx, event, st, f"βœ… <b>{esc(short(label, 40))}</b> now opens <code>{esc(url)}</code>")
136
+
137
+ def live(event, parts):
138
+ st = ctx.state.get(event.sender_id)
139
+ if not st or st.get("mode") != MODE:
140
+ raise UserError("That list is no longer active.")
141
+ if parts and parts[0].isdigit() and int(parts[0]) != st["i"]:
142
+ raise UserError("That button belongs to an earlier step - use the newest message.")
143
+ return st
144
+
145
+ @on_cb(ctx, "lqs")
146
+ async def cb_skip(event, parts):
147
+ st = live(event, parts)
148
+ st["i"] += 1
149
+ st["skipped"] += 1
150
+ await ask(ctx, event, st, "⏭ Skipped.", new=False)
151
+
152
+ @on_cb(ctx, "lqx")
153
+ async def cb_stop(event, parts):
154
+ st = ctx.state.get(event.sender_id)
155
+ if not st or st.get("mode") != MODE:
156
+ await show(event, "Cancelled.")
157
+ return
158
+ clear_state(ctx, event.sender_id)
159
+ await show(event, summary(st, True), [[Button.inline("πŸ“š My posts", "pl")]])
app/handlers/panel.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers shared by the create and post-management handlers (not a handler module itself)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Optional
5
+
6
+ from telethon import types
7
+
8
+ from ..buttons import valid
9
+ from ..common import Ctx, UserError, is_cb, say, show
10
+ from ..richmsg import Rich, RichError, check as check_rich, entry as rich_entry, plain_of, read_typed, received
11
+ from ..richtext import message_text
12
+ from ..tgutil import classify_media, pack_file_id, ser_entities, utf16_len
13
+ from ..ui import button_keyboard, button_text, panel_keyboard, panel_text
14
+
15
+ CAPTION_MAX = 1024
16
+ TEXT_MAX = 4096
17
+
18
+
19
+ async def load_post(ctx: Ctx, pid):
20
+ post = await ctx.db.get_post(int(pid))
21
+ if post is None:
22
+ raise UserError("That post no longer exists.")
23
+ ch = await ctx.db.get_channel(post.channel_id)
24
+ if ch is None:
25
+ raise UserError("Its channel was removed from the bot. Add it again with /addchannel.")
26
+ return post, ch
27
+
28
+
29
+ async def show_panel(ctx: Ctx, event, pid, note=None, new: bool = False) -> None:
30
+ post, ch = await load_post(ctx, pid)
31
+ text, kb = panel_text(post, ch, note), panel_keyboard(post)
32
+ if new or not is_cb(event):
33
+ await say(event, text, kb)
34
+ else:
35
+ await show(event, text, kb)
36
+
37
+
38
+ async def show_button_screen(ctx: Ctx, event, pid, r: int, c: int, new: bool = False) -> None:
39
+ post, _ = await load_post(ctx, pid)
40
+ if not valid(post.buttons or [], r, c):
41
+ await show_panel(ctx, event, pid, new=new)
42
+ return
43
+ text, kb = button_text(post, r, c), button_keyboard(post, r, c)
44
+ if new or not is_cb(event):
45
+ await say(event, text, kb)
46
+ else:
47
+ await show(event, text, kb)
48
+
49
+
50
+ def check_lengths(text: str, has_media: bool) -> None:
51
+ n = utf16_len(text or "")
52
+ if has_media and n > CAPTION_MAX:
53
+ raise UserError(f"A caption can have at most {CAPTION_MAX} characters (yours has {n}).")
54
+ if not has_media and n > TEXT_MAX:
55
+ raise UserError(f"A text post can have at most {TEXT_MAX} characters (yours has {n}).")
56
+
57
+
58
+ class Content(dict):
59
+ """Post fields (text, entities, media_kind, media_file_id).
60
+
61
+ `how` says what the text was read as: "html" or "markdown" (turned into formatting), "rich" (a rich message sent
62
+ natively, kept as it is), "rich-html" / "rich-markdown" (typed, and Telegram builds the blocks), or None."""
63
+
64
+ how = None
65
+
66
+
67
+ def markup_note(how, sep: str = "\n\n") -> str:
68
+ """A line for the owner when their text was read as HTML or Markdown, followed by `sep` (empty otherwise)."""
69
+ if not how:
70
+ return ""
71
+ if how == "rich":
72
+ return f"🧩 Rich message kept as it is - πŸ‘ Preview shows it.{sep}"
73
+ if how.startswith("rich-"):
74
+ lang = "HTML" if how == "rich-html" else "Markdown"
75
+ return f"🧩 Rich message read from {lang} - πŸ‘ Preview shows what Telegram makes of it (/rich).{sep}"
76
+ return f"🎨 Formatting read from {'HTML' if how == 'html' else 'Markdown'} - see /formatting.{sep}"
77
+
78
+
79
+ def is_rich_how(how) -> bool:
80
+ return bool(how) and how.startswith("rich")
81
+
82
+
83
+ def read_text(m, markup: bool = True, rich: Optional[Rich] = None, allow_rich: bool = True) -> tuple:
84
+ """(text, entities, how) of what the owner sent - see Content.how.
85
+
86
+ A rich message (`rich`: sent natively, kept block for block) or text typed as HTML / Markdown that needs blocks
87
+ becomes a rich post: `text` is its plain-text version and its only entity is the rich entry. Otherwise it is an
88
+ ordinary text with Telegram's own formatting, or HTML / Markdown turned into formatting. A message that has
89
+ Telegram formatting of its own is used as it is. `allow_rich` is False where a rich message can't be (a caption)."""
90
+ how = None
91
+ if rich is not None:
92
+ if not allow_rich:
93
+ raise UserError("A caption can't be a rich message. Rich messages are for text posts.")
94
+ how = "rich"
95
+ elif allow_rich and markup and not ser_entities(m.entities):
96
+ rich = read_typed(m.raw_text or "")
97
+ how = f"rich-{rich.fmt}" if rich is not None else None
98
+ if rich is None:
99
+ return message_text(m, markup)
100
+ try:
101
+ check_rich(rich)
102
+ except RichError as e:
103
+ raise UserError(str(e))
104
+ return plain_of(rich), [rich_entry(rich)], how
105
+
106
+
107
+ async def read_native(ctx: Ctx, event) -> Optional[Rich]:
108
+ """The rich message the owner sent natively (or forwarded), or None for an ordinary message."""
109
+ try:
110
+ return await received(ctx.client, event)
111
+ except RichError as e:
112
+ raise UserError(str(e))
113
+
114
+
115
+ def extract_content(m, markup: bool = True, rich: Optional[Rich] = None) -> Content:
116
+ """A message from the user -> post fields (text, entities, media).
117
+
118
+ Telegram's own formatting is kept as it is; without any, `markup` lets HTML or Markdown in the text become formatting
119
+ (or a rich message, when it has blocks only those have). `rich`: the message is a rich message sent natively."""
120
+ kind = classify_media(m)
121
+ if m.media and kind is None and not isinstance(m.media, types.MessageMediaWebPage):
122
+ raise UserError("That kind of message can't be used in a post. Send text, a photo, video, GIF, audio or a file.")
123
+ text, entities, how = read_text(m, markup, rich if not kind else None, allow_rich=not kind)
124
+ if not kind and not text.strip() and not is_rich_how(how):
125
+ raise UserError("Send some text, or a photo / video / GIF / file.")
126
+ if not is_rich_how(how):
127
+ check_lengths(text, bool(kind))
128
+ content = Content(text=text, entities=entities, media_kind=kind, media_file_id=pack_file_id(m) if kind else None)
129
+ content.how = how
130
+ return content
131
+
132
+
133
+ async def read_content(ctx: Ctx, event) -> Content:
134
+ """extract_content for a message that just arrived (a rich message sent natively is read, in full, first)."""
135
+ return extract_content(event.message, ctx.cfg.markup_input, await read_native(ctx, event))
app/handlers/posts.py ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/posts: list, open and edit posts (text, caption, media, buttons), publish drafts, delete."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+
6
+ from telethon import Button, errors
7
+
8
+ from .. import picker
9
+ from ..buttons import (
10
+ MAX_ROW,
11
+ add_button,
12
+ count,
13
+ delete_button,
14
+ missing_links,
15
+ move_button,
16
+ norm_url,
17
+ parse_buttons_text,
18
+ set_field,
19
+ valid,
20
+ )
21
+ from ..common import (
22
+ Ctx,
23
+ UserError,
24
+ apply_edit,
25
+ apply_edit_reported,
26
+ clear_state,
27
+ cmd,
28
+ edit_report_text,
29
+ guard,
30
+ on_cb,
31
+ on_text,
32
+ say,
33
+ send_post,
34
+ set_state,
35
+ show,
36
+ )
37
+ from ..db import utcnow
38
+ from ..repost_engine import delete_batch
39
+ from ..richmsg import (
40
+ block_count,
41
+ block_labels,
42
+ digest,
43
+ entry as rich_entry,
44
+ is_block_invalid,
45
+ is_rich,
46
+ pack_blocks,
47
+ plain_of,
48
+ refused_blocks,
49
+ rich_of,
50
+ unpack_blocks,
51
+ without_blocks,
52
+ )
53
+ from ..tgutil import classify_media, esc, explain_rpc, pack_file_id, peer_of, post_link
54
+ from ..ui import CANCEL, post_label
55
+ from ..userbot import delete_problem_text
56
+ from .panel import (
57
+ check_lengths,
58
+ is_rich_how,
59
+ load_post,
60
+ markup_note,
61
+ read_native,
62
+ read_text,
63
+ show_button_screen,
64
+ show_panel,
65
+ )
66
+
67
+ log = logging.getLogger(__name__)
68
+ PAGE = 8
69
+ UPDATED = "βœ… Updated in the channel."
70
+
71
+
72
+ def register(ctx: Ctx) -> None:
73
+ client, db = ctx.client, ctx.db
74
+
75
+ def note_for(post, report=None) -> str:
76
+ extra = edit_report_text(report)
77
+ return (UPDATED if post.status == "sent" else "βœ… Saved.") + (f"\n{extra}" if extra else "")
78
+
79
+ # ------------------------------------------------------------------ lists
80
+ async def channel_chooser(event, arg: str = "", page: int = 0) -> None:
81
+ chans = await db.list_channels()
82
+ drafts = [[Button.inline("πŸ’Ύ Drafts (all channels)", "pc:d:0")]]
83
+ if not chans:
84
+ await show(event, "πŸ“š <b>My posts</b>\n\nNo channels yet. Add one with /addchannel.", drafts)
85
+ return
86
+ text, kb = picker.render(
87
+ chans, page, head="πŸ“š <b>My posts</b> - pick a channel:", kind="ps", choose=lambda c: f"pc:{c.id}:0", extra_rows=drafts
88
+ )
89
+ await show(event, text, kb)
90
+
91
+ ctx.pickers["ps"] = channel_chooser
92
+
93
+ @client.on(cmd("posts"))
94
+ @guard(ctx)
95
+ async def h_posts(event):
96
+ await channel_chooser(event)
97
+
98
+ @on_cb(ctx, "pl")
99
+ async def cb_channel_chooser(event, parts):
100
+ await channel_chooser(event)
101
+
102
+ @on_cb(ctx, "pc")
103
+ async def cb_list(event, parts):
104
+ key, page = parts[0], int(parts[1])
105
+ if key == "d":
106
+ cid, status, title = None, "draft", "Drafts"
107
+ else:
108
+ cid, status = int(key), None
109
+ ch = await db.get_channel(cid)
110
+ title = ch.title if ch else "Channel"
111
+ rows, total = await db.list_posts(cid, status, page * PAGE, PAGE)
112
+ pages = max(1, -(-total // PAGE))
113
+ if page >= pages:
114
+ page = pages - 1
115
+ rows, total = await db.list_posts(cid, status, page * PAGE, PAGE)
116
+ kb = [[Button.inline(post_label(p), f"po:{p.id}")] for p in rows]
117
+ if pages > 1:
118
+ # "Prev" is always there: on the first page it jumps to the last one
119
+ nav = [Button.inline("⬅️ Prev", f"pc:{key}:{(page - 1) % pages}"), Button.inline(f"{page + 1}/{pages}", "noop")]
120
+ if page < pages - 1:
121
+ nav.append(Button.inline("Next ➑️", f"pc:{key}:{page + 1}"))
122
+ kb.append(nav)
123
+ if cid is not None and ctx.cfg.is_owner(event.sender_id):
124
+ kb.append([Button.inline("πŸ”§ Check buttons", f"pk:{cid}")])
125
+ kb.append([Button.inline("πŸ”™ Channels", "pl")])
126
+ head = f"πŸ“š <b>{esc(title)}</b> - {total} post(s)"
127
+ if not rows:
128
+ head += "\n\nNothing here yet. Create a post with /new."
129
+ await show(event, head, kb)
130
+
131
+ @on_cb(ctx, "po")
132
+ async def cb_open(event, parts):
133
+ clear_state(ctx, event.sender_id)
134
+ await show_panel(ctx, event, parts[0])
135
+
136
+ # ------------------------------------------------------------ text / caption
137
+ @on_cb(ctx, "et")
138
+ async def cb_edit_text(event, parts):
139
+ post, _ = await load_post(ctx, parts[0])
140
+ set_state(ctx, event.sender_id, "edit_text", pid=post.id)
141
+ what = "caption" if post.media_kind else "text"
142
+ more = "" if post.media_kind else " Rich messages (headings, lists, tables ...) too: /rich."
143
+ await say(event, f"✏️ Send the new {what}. Formatting is kept - or type HTML / Markdown (/formatting shows how).{more}", CANCEL)
144
+
145
+ @on_text(ctx, "edit_text")
146
+ async def h_edit_text(event, st):
147
+ m = event.message
148
+ if classify_media(m):
149
+ raise UserError("Send text only here. To change the media, use πŸ–Ό Media.")
150
+ post, ch = await load_post(ctx, st["pid"])
151
+ native = await read_native(ctx, event)
152
+ text, entities, how = read_text(m, ctx.cfg.markup_input, native, allow_rich=not post.media_kind)
153
+ if not post.media_kind and not text.strip() and not is_rich_how(how):
154
+ raise UserError("A text post can't be empty.")
155
+ if not is_rich_how(how):
156
+ check_lengths(text, bool(post.media_kind))
157
+ post, report = await apply_edit_reported(ctx, post, ch, text=text, entities=entities)
158
+ clear_state(ctx, event.sender_id)
159
+ await show_panel(ctx, event, post.id, note=markup_note(how, "\n") + note_for(post, report), new=True)
160
+
161
+ # ------------------------------------------------------------------- media
162
+ @on_cb(ctx, "em")
163
+ async def cb_edit_media(event, parts):
164
+ post, _ = await load_post(ctx, parts[0])
165
+ if is_rich(post):
166
+ raise UserError(
167
+ "A rich message has no media slot. Put pictures into the text itself (see /rich), "
168
+ "or send new text without rich blocks first."
169
+ )
170
+ set_state(ctx, event.sender_id, "edit_media", pid=post.id)
171
+ extra = "" if post.media_kind else "\nThe current text becomes its caption."
172
+ await say(event, f"πŸ–Ό Send the new photo / video / GIF / audio / file.{extra}", CANCEL)
173
+
174
+ @on_text(ctx, "edit_media")
175
+ async def h_edit_media(event, st):
176
+ m = event.message
177
+ if m.grouped_id and st.get("group") == m.grouped_id:
178
+ return
179
+ if m.grouped_id:
180
+ st["group"] = m.grouped_id
181
+ kind = classify_media(m)
182
+ if not kind:
183
+ raise UserError("Send a photo, video, GIF, audio file or document.")
184
+ post, ch = await load_post(ctx, st["pid"])
185
+ check_lengths(post.text or "", True)
186
+
187
+ async def notify(text: str) -> None:
188
+ await say(event, text)
189
+
190
+ post, report = await apply_edit_reported(
191
+ ctx, post, ch, replace_media=True, notify=notify, media_kind=kind, media_file_id=pack_file_id(m)
192
+ )
193
+ clear_state(ctx, event.sender_id)
194
+ await show_panel(ctx, event, post.id, note=note_for(post, report), new=True)
195
+
196
+ @on_cb(ctx, "rm")
197
+ async def cb_remove_media(event, parts):
198
+ post, ch = await load_post(ctx, parts[0])
199
+ if post.status != "draft":
200
+ raise UserError("Media can't be removed from a published post - Telegram doesn't allow it.")
201
+ if not (post.text or "").strip():
202
+ raise UserError("Add some text first, then remove the media (a post needs text or media).")
203
+ await db.update_post(post.id, media_kind=None, media_file_id=None)
204
+ await show_panel(ctx, event, post.id, note="βœ… Media removed.")
205
+
206
+ @on_cb(ctx, "lp")
207
+ async def cb_link_preview(event, parts):
208
+ post, ch = await load_post(ctx, parts[0])
209
+ post = await apply_edit(ctx, post, ch, link_preview=not post.link_preview)
210
+ await show_panel(ctx, event, post.id)
211
+
212
+ # ----------------------------------------------------------------- buttons
213
+ async def commit_buttons(event, post, ch, rows, *, new_msg: bool = True, note: str = None):
214
+ post = await apply_edit(ctx, post, ch, buttons=rows)
215
+ await show_panel(ctx, event, post.id, note=note or note_for(post), new=new_msg)
216
+ return post
217
+
218
+ @on_cb(ctx, "ba")
219
+ async def cb_add_button(event, parts):
220
+ post, _ = await load_post(ctx, parts[0])
221
+ if count(post.buttons) >= 100:
222
+ raise UserError("A post can have at most 100 buttons.")
223
+ set_state(ctx, event.sender_id, "btn_add_text", pid=post.id)
224
+ await say(
225
+ event,
226
+ "βž• Send the button as <code>Button text - link</code>, or just the button text and I'll ask for the link.",
227
+ CANCEL,
228
+ )
229
+
230
+ async def place_button(event, pid, btn: dict) -> None:
231
+ post, ch = await load_post(ctx, pid)
232
+ if post.buttons and len(post.buttons[-1]) < MAX_ROW:
233
+ set_state(ctx, event.sender_id, "btn_place", pid=post.id, btn=btn)
234
+ await say(
235
+ event,
236
+ f"Where should <code>{esc(btn['t'])}</code> go?",
237
+ [
238
+ [Button.inline("⬇️ New row", f"bk:{post.id}:n"), Button.inline("➑️ Same row", f"bk:{post.id}:s")],
239
+ CANCEL[0],
240
+ ],
241
+ )
242
+ return
243
+ clear_state(ctx, event.sender_id)
244
+ await commit_buttons(event, post, ch, add_button(post.buttons, btn, True))
245
+
246
+ @on_text(ctx, "btn_add_text")
247
+ async def h_btn_add_text(event, st):
248
+ txt = (event.raw_text or "").strip()
249
+ if not txt:
250
+ raise UserError("Send the button text.")
251
+ try:
252
+ rows = parse_buttons_text(txt)
253
+ except ValueError:
254
+ rows = []
255
+ if rows:
256
+ if len(rows) == 1 and len(rows[0]) == 1:
257
+ await place_button(event, st["pid"], rows[0][0])
258
+ return
259
+ raise UserError("That's several buttons. Send one at a time, or use πŸ“‹ Set buttons to replace them all.")
260
+ if len(txt) > 64:
261
+ raise UserError("Keep the button text under 64 characters.")
262
+ set_state(ctx, event.sender_id, "btn_add_url", pid=st["pid"], text=txt)
263
+ await say(event, f"πŸ”— Now send the link for <code>{esc(txt)}</code>.", CANCEL)
264
+
265
+ @on_text(ctx, "btn_add_url")
266
+ async def h_btn_add_url(event, st):
267
+ url = norm_url(event.raw_text or "")
268
+ if not url:
269
+ raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc")
270
+ await place_button(event, st["pid"], {"t": st["text"], "u": url})
271
+
272
+ @on_cb(ctx, "bk")
273
+ async def cb_place(event, parts):
274
+ st = ctx.state.get(event.sender_id)
275
+ if not st or st.get("mode") != "btn_place" or str(st.get("pid")) != parts[0]:
276
+ raise UserError("That step expired. Tap βž• Button again.")
277
+ post, ch = await load_post(ctx, parts[0])
278
+ rows = add_button(post.buttons, st["btn"], new_row=(parts[1] == "n"))
279
+ clear_state(ctx, event.sender_id)
280
+ await commit_buttons(event, post, ch, rows, new_msg=False)
281
+
282
+ @on_cb(ctx, "bp")
283
+ async def cb_paste(event, parts):
284
+ post, _ = await load_post(ctx, parts[0])
285
+ set_state(ctx, event.sender_id, "btn_paste", pid=post.id)
286
+ warn = ""
287
+ if any(b.get("raw") for r in post.buttons for b in r):
288
+ warn = "\n⚠️ This also removes buttons made by other bots (like reactions)."
289
+ await say(
290
+ event,
291
+ "πŸ“‹ Send <b>all</b> the buttons - one row per line as <code>Text - link</code>, "
292
+ "with <code> | </code> between buttons in one row. This replaces the current buttons." + warn,
293
+ CANCEL,
294
+ )
295
+
296
+ @on_text(ctx, "btn_paste")
297
+ async def h_btn_paste(event, st):
298
+ try:
299
+ rows = parse_buttons_text(event.raw_text or "")
300
+ except ValueError as e:
301
+ raise UserError(f"❌ {e}\n\nTry again.")
302
+ if not rows:
303
+ raise UserError("Send at least one button as β€œText - link”.")
304
+ post, ch = await load_post(ctx, st["pid"])
305
+ clear_state(ctx, event.sender_id)
306
+ await commit_buttons(event, post, ch, rows)
307
+
308
+ @on_cb(ctx, "bc")
309
+ async def cb_clear(event, parts):
310
+ await show(
311
+ event,
312
+ "Remove <b>all</b> buttons from this post?",
313
+ [[Button.inline("🧹 Yes, remove", f"bcy:{parts[0]}"), Button.inline("↩️ Back", f"po:{parts[0]}")]],
314
+ )
315
+
316
+ @on_cb(ctx, "bcy")
317
+ async def cb_clear_yes(event, parts):
318
+ post, ch = await load_post(ctx, parts[0])
319
+ await commit_buttons(event, post, ch, [], new_msg=False)
320
+
321
+ @on_cb(ctx, "bs")
322
+ async def cb_select(event, parts):
323
+ clear_state(ctx, event.sender_id)
324
+ await show_button_screen(ctx, event, parts[0], int(parts[1]), int(parts[2]))
325
+
326
+ @on_cb(ctx, "bt")
327
+ async def cb_btn_text(event, parts):
328
+ set_state(ctx, event.sender_id, "btn_text", pid=parts[0], r=int(parts[1]), c=int(parts[2]))
329
+ await say(event, "✏️ Send the new button text.", CANCEL)
330
+
331
+ @on_text(ctx, "btn_text")
332
+ async def h_btn_text(event, st):
333
+ txt = (event.raw_text or "").strip()
334
+ if not txt:
335
+ raise UserError("Send the new button text.")
336
+ if len(txt) > 64:
337
+ raise UserError("Keep the button text under 64 characters.")
338
+ post, ch = await load_post(ctx, st["pid"])
339
+ if not valid(post.buttons, st["r"], st["c"]):
340
+ raise UserError("That button no longer exists.")
341
+ post = await apply_edit(ctx, post, ch, buttons=set_field(post.buttons, st["r"], st["c"], t=txt))
342
+ clear_state(ctx, event.sender_id)
343
+ await show_button_screen(ctx, event, post.id, st["r"], st["c"], new=True)
344
+
345
+ @on_cb(ctx, "bu")
346
+ async def cb_btn_url(event, parts):
347
+ set_state(ctx, event.sender_id, "btn_url", pid=parts[0], r=int(parts[1]), c=int(parts[2]))
348
+ await say(event, "πŸ”— Send the new link for this button.", CANCEL)
349
+
350
+ @on_text(ctx, "btn_url")
351
+ async def h_btn_url(event, st):
352
+ url = norm_url(event.raw_text or "")
353
+ if not url:
354
+ raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc")
355
+ post, ch = await load_post(ctx, st["pid"])
356
+ if not valid(post.buttons, st["r"], st["c"]):
357
+ raise UserError("That button no longer exists.")
358
+ post = await apply_edit(ctx, post, ch, buttons=set_field(post.buttons, st["r"], st["c"], u=url))
359
+ clear_state(ctx, event.sender_id)
360
+ await show_button_screen(ctx, event, post.id, st["r"], st["c"], new=True)
361
+
362
+ @on_cb(ctx, "bm")
363
+ async def cb_move(event, parts):
364
+ pid, r, c, d = parts[0], int(parts[1]), int(parts[2]), parts[3]
365
+ post, ch = await load_post(ctx, pid)
366
+ rows, nr, nc = move_button(post.buttons, r, c, d)
367
+ if rows == post.buttons:
368
+ return # already at the edge
369
+ post = await apply_edit(ctx, post, ch, buttons=rows)
370
+ await show_button_screen(ctx, event, post.id, nr, nc)
371
+
372
+ @on_cb(ctx, "bd")
373
+ async def cb_btn_delete(event, parts):
374
+ post, ch = await load_post(ctx, parts[0])
375
+ rows = delete_button(post.buttons, int(parts[1]), int(parts[2]))
376
+ await commit_buttons(event, post, ch, rows, new_msg=False)
377
+
378
+ # ------------------------------------------------------- preview / publish
379
+ async def rich_refusal(event, post, e, typed: str, tail: str = "") -> None:
380
+ """Telegram refused to make a rich message of the post: say why.
381
+
382
+ A rich message that was typed (HTML / Markdown) is Telegram's to read: `typed` tells the owner to check the syntax. One
383
+ that was made in Telegram and sent to the bot is kept block by block, and Telegram does not say which block it
384
+ dislikes - so the blocks are tried out, in the owner's chat and quietly, to tell which ones it won't take (see
385
+ richmsg.refused_blocks). A draft can then go on without those: the βœ‚οΈ button. `tail` closes the message."""
386
+ rich = rich_of(post)
387
+ head = "❌ " + explain_rpc(e)
388
+ if rich is None or rich.fmt != "blocks":
389
+ raise UserError(f"{head}\n{typed}")
390
+ if not is_block_invalid(e):
391
+ raise UserError(f"{head}\nTelegram could not make that rich message.\n{tail}".strip())
392
+ bad = await refused_blocks(client, await event.get_input_chat(), rich)
393
+ if not bad:
394
+ raise UserError(
395
+ f"{head}\nI could not tell which block it is - /rich shows how to type the message as HTML / Markdown instead.\n{tail}".strip()
396
+ )
397
+ if len(bad) >= block_count(rich):
398
+ raise UserError(
399
+ f"{head}\nIt won't take any block of that message as it is - /rich shows how to type it as HTML / Markdown instead.\n{tail}".strip()
400
+ )
401
+ lines = [
402
+ esc(head),
403
+ f"It won't take these blocks (of {block_count(rich)}): {esc(block_labels(rich, bad))}. The others are fine.",
404
+ ]
405
+ if tail:
406
+ lines.append(esc(tail))
407
+ buttons = []
408
+ if post.status == "draft":
409
+ lines.append("βœ‚οΈ <b>Leave those out</b> keeps the rest of the message as the post.")
410
+ buttons.append([Button.inline("βœ‚οΈ Leave those out", f"rx:{post.id}:{digest(rich)}:{pack_blocks(bad)}")])
411
+ buttons.append([Button.inline("↩️ Back", f"po:{post.id}")])
412
+ await say(event, "\n".join(lines), buttons)
413
+
414
+ @on_cb(ctx, "rx")
415
+ async def cb_leave_out(event, parts):
416
+ post, ch = await load_post(ctx, parts[0])
417
+ rich = rich_of(post)
418
+ if post.status != "draft" or rich is None or rich.fmt != "blocks" or parts[1] != digest(rich):
419
+ raise UserError("The post is not the one that was checked any more - press πŸ‘ Preview again.")
420
+ total = block_count(rich)
421
+ drop = [i for i in unpack_blocks(parts[2]) if i < total]
422
+ if not drop:
423
+ raise UserError("Those blocks are not in the post any more.")
424
+ if len(drop) >= total:
425
+ raise UserError("Nothing would be left of the message. Send it again in another form, or as HTML / Markdown (/rich).")
426
+ kept = without_blocks(rich, drop)
427
+ post = await apply_edit(ctx, post, ch, text=plain_of(kept), entities=[rich_entry(kept)])
428
+ await show_panel(ctx, event, post.id, note=f"βœ‚οΈ Left out: {esc(block_labels(rich, drop))}.\nπŸ‘ Preview shows what is left.")
429
+
430
+ @on_cb(ctx, "pv")
431
+ async def cb_preview(event, parts):
432
+ post, _ = await load_post(ctx, parts[0])
433
+ if not (post.text or "").strip() and not post.media_file_id and not is_rich(post):
434
+ raise UserError("The post is empty.")
435
+ try:
436
+ await send_post(client, await event.get_input_chat(), post)
437
+ except errors.RPCError as e:
438
+ if not is_rich(post):
439
+ raise
440
+ await rich_refusal(event, post, e, typed="Telegram could not make that rich message - see /rich for the syntax.")
441
+ return
442
+ miss = missing_links(post.buttons)
443
+ if miss:
444
+ await say(event, f"πŸ‘† Preview. ⚠️ {miss} button(s) without a link are not shown.")
445
+
446
+ @on_cb(ctx, "pb")
447
+ async def cb_publish(event, parts):
448
+ post, ch = await load_post(ctx, parts[0])
449
+ if post.status != "draft":
450
+ raise UserError("This post is already published.")
451
+ if missing_links(post.buttons):
452
+ raise UserError("Some buttons (⚠️) have no link yet. Open them and add a link first.")
453
+ if not (post.text or "").strip() and not post.media_file_id and not is_rich(post):
454
+ raise UserError("The post is empty.")
455
+ await show(
456
+ event,
457
+ f"Publish this post to <b>{esc(ch.title)}</b>?",
458
+ [[Button.inline("πŸš€ Yes, publish", f"pby:{post.id}"), Button.inline("↩️ Back", f"po:{post.id}")]],
459
+ )
460
+
461
+ @on_cb(ctx, "pby")
462
+ async def cb_publish_yes(event, parts):
463
+ post, ch = await load_post(ctx, parts[0])
464
+ if post.status != "draft":
465
+ raise UserError("This post is already published.")
466
+ try:
467
+ sent = await send_post(client, peer_of(ch), post)
468
+ except errors.RPCError as e:
469
+ if is_rich(post):
470
+ await rich_refusal(event, post, e, typed="The post was NOT published.", tail="The post was NOT published.")
471
+ return
472
+ raise UserError("❌ " + explain_rpc(e) + "\nThe post was NOT published.")
473
+ await db.release_slot(ch.id, sent.id, keep_pid=post.id) # the sync may have picked the message up a moment ago
474
+ post = await db.update_post(post.id, status="sent", message_id=sent.id, sent_at=utcnow())
475
+ await show(
476
+ event,
477
+ f"βœ… <b>Published</b> in <b>{esc(ch.title)}</b>\n<a href=\"{post_link(ch, sent.id)}\">Open the post</a>",
478
+ [
479
+ [Button.inline("πŸ“ Manage this post", f"po:{post.id}")],
480
+ [Button.inline("βž• New post", f"nc:{ch.id}")],
481
+ ],
482
+ )
483
+
484
+ # ----------------------------------------------------------------- delete
485
+ @on_cb(ctx, "dl")
486
+ async def cb_delete(event, parts):
487
+ post, ch = await load_post(ctx, parts[0])
488
+ back = Button.inline("↩️ Back", f"po:{post.id}")
489
+ if post.status == "draft":
490
+ await show(event, "Discard this draft?", [[Button.inline("πŸ—‘ Yes, discard", f"dly:{post.id}:b"), back]])
491
+ return
492
+ await show(
493
+ event,
494
+ f"Delete this post from <b>{esc(ch.title)}</b>?\n\n"
495
+ "πŸ—‘ <b>Delete from channel</b> - deletes it in the channel and removes it, with its data, from My posts.\n"
496
+ "🧹 <b>Only forget it in the bot</b> - the post stays in the channel; only My posts forgets it.",
497
+ [
498
+ [Button.inline("πŸ—‘ Delete from channel", f"dly:{post.id}:a")],
499
+ [Button.inline("🧹 Only forget it in the bot", f"dly:{post.id}:b")],
500
+ [back],
501
+ ],
502
+ )
503
+
504
+ @on_cb(ctx, "dly")
505
+ async def cb_delete_yes(event, parts):
506
+ post, ch = await load_post(ctx, parts[0])
507
+ note = "πŸ—‘ Done."
508
+ if post.status == "sent" and parts[1] == "a":
509
+ # The bot deletes the post; where Telegram refuses it (an age limit on old posts, a missing right) the userbot
510
+ # takes over at once - nothing is asked first.
511
+ fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None)
512
+ try:
513
+ out = await delete_batch(client, peer_of(ch), [post.message_id], fallback)
514
+ finally:
515
+ if deleter is not None:
516
+ await deleter.close()
517
+ if post.message_id not in out.gone:
518
+ why = delete_problem_text(
519
+ ctx.userbot, bot_error=out.bot_error, fallback_error=out.fallback_error, tried=out.tried_userbot
520
+ )
521
+ raise UserError(
522
+ f"Telegram did not delete that message. {why}\n"
523
+ "The post is still in My posts. Delete it by hand in the channel, then use β€œOnly forget it in the bot”."
524
+ )
525
+ # gone from the channel: it goes from My posts too, with what hangs on it (a timed deletion ...)
526
+ await db.forget_posts(post.channel_id, [post.message_id])
527
+ note = "πŸ—‘ Done - deleted in the channel and removed from My posts."
528
+ if out.by_userbot:
529
+ note += "\nThe bot was not allowed to delete it, so the userbot did."
530
+ if post.status == "sent" and post.message_id and parts[1] == "b":
531
+ ctx.sync_ignore.add((post.channel_id, post.message_id)) # forgotten on purpose: the sync must not bring it back
532
+ await db.ignore_post(post.channel_id, post.message_id) # ... not even after a restart
533
+ await db.delete_post(post.id)
534
+ await show(event, note, [[Button.inline("πŸ“š My posts", "pl")]])
app/handlers/replace.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/replace media, /swap links, /handleswap and /undo (owner only)."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import re
6
+ import secrets
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from urllib.parse import urlparse
10
+
11
+ from telethon import Button, errors
12
+
13
+ from ..common import (
14
+ Ctx,
15
+ UserError,
16
+ apply_edit_reported,
17
+ cmd,
18
+ edit_callback_message,
19
+ edit_report_text,
20
+ guard,
21
+ on_cb,
22
+ purge_pending,
23
+ require_owner,
24
+ say,
25
+ show,
26
+ )
27
+ from ..linkswap import normalize_username
28
+ from ..replace_engine import ApplyResult, ChannelScan, ScanOptions, apply_channel, scan_channel, undo_batch
29
+ from ..richmsg import is_rich
30
+ from ..richtext import message_text
31
+ from ..sync_engine import SyncOptions, sync_ids
32
+ from ..tgutil import classify_media, esc, explain_rpc, get_rights, pack_file_id
33
+ from ..channelref import parse_channel_ref
34
+ from .panel import check_lengths, markup_note
35
+
36
+ log = logging.getLogger(__name__)
37
+
38
+ USAGE = (
39
+ "Usage: <code>/swap @old @new</code>\n"
40
+ "Options: <code>--channel @name</code> (only that channel), <code>--last 200</code> (only the newest 200 "
41
+ "post ids), <code>--posts</code> (also change t.me/old/123 post links), <code>--no-typed</code> (don't touch "
42
+ "links typed in the text)."
43
+ )
44
+
45
+
46
+ USAGE_HANDLES = (
47
+ "Usage: <code>/handleswap @old @new</code>\n"
48
+ "Finds the posts that mention the username <code>@old</code> (in their text or caption, and in button names) in all "
49
+ "channels and changes it to <code>@new</code>. Only usernames change: links, hyperlinks and button links are left alone.\n"
50
+ "Options: <code>--channel @name</code> (only that channel), <code>--last 200</code> (only the newest 200 post ids)."
51
+ )
52
+ HANDLE_PREFIX = "hs" # ids of /handleswap runs start with this, so /undo can word its question right
53
+
54
+
55
+ @dataclass
56
+ class Job:
57
+ user: int
58
+ opts: ScanOptions
59
+ scans: list
60
+ running: bool = False
61
+ created: float = field(default_factory=time.monotonic)
62
+
63
+
64
+ def parse_replace_args(raw: str, *, handles: bool = False) -> tuple:
65
+ toks = (raw or "").split()
66
+ flags = {"channel": None, "last": None, "posts": False, "typed": None}
67
+ pos: list = []
68
+ i = 0
69
+ while i < len(toks):
70
+ t = toks[i]
71
+ if t == "--channel" and i + 1 < len(toks):
72
+ flags["channel"] = toks[i + 1]
73
+ i += 2
74
+ elif t == "--last" and i + 1 < len(toks):
75
+ if not toks[i + 1].isdigit() or int(toks[i + 1]) < 1:
76
+ raise ValueError("--last needs a number, for example --last 200")
77
+ flags["last"] = int(toks[i + 1])
78
+ i += 2
79
+ elif t == "--posts" and not handles:
80
+ flags["posts"] = True
81
+ i += 1
82
+ elif t == "--no-typed" and not handles:
83
+ flags["typed"] = False
84
+ i += 1
85
+ elif t.startswith("--"):
86
+ raise ValueError(f"Unknown option {t}")
87
+ else:
88
+ pos.append(t)
89
+ i += 1
90
+ if len(pos) != 2:
91
+ raise ValueError("Give the old and the new username.")
92
+ old, new = normalize_username(pos[0]), normalize_username(pos[1])
93
+ if not old or not new:
94
+ raise ValueError("Usernames look like @name (letters, digits and underscores).")
95
+ if old.lower() == new.lower():
96
+ raise ValueError("The old and the new username are the same.")
97
+ return old, new, flags
98
+
99
+
100
+ def pick_channels(chans: list, ref) -> list:
101
+ if not ref:
102
+ return chans
103
+ r = parse_channel_ref(ref)
104
+ out = [c for c in chans if (isinstance(r, int) and c.id == r) or (isinstance(r, str) and (c.username or "").lower() == r.lower())]
105
+ if not out:
106
+ raise ValueError("That channel isn't registered (see /channels).")
107
+ return out
108
+
109
+
110
+ def parse_post_link(value: str):
111
+ """Return (public username or private channel id, message id) for Telegram post links."""
112
+ try:
113
+ u = urlparse(value if "://" in value else "https://" + value)
114
+ bits = [x for x in u.path.strip("/").split("/") if x]
115
+ if u.netloc.lower() not in {"t.me", "www.t.me", "telegram.me", "www.telegram.me"}:
116
+ return None
117
+ if bits and bits[0] == "c" and len(bits) == 3 and bits[1].isdigit() and bits[2].isdigit():
118
+ # Telegram's t.me/c URL uses the same positive channel ID stored by Telethon and in our database.
119
+ return int(bits[1]), int(bits[2])
120
+ if bits and bits[0] == "s":
121
+ bits = bits[1:]
122
+ if len(bits) == 2 and bits[1].isdigit() and re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{3,}", bits[0]):
123
+ return bits[0].lower(), int(bits[1])
124
+ except Exception:
125
+ pass
126
+ return None
127
+
128
+
129
+ def handles_summary(job: Job) -> str:
130
+ o = job.opts
131
+ lines = [f"πŸ”Ž <b>Scan finished</b> - swap the username <code>@{esc(o.old)}</code> β†’ <code>@{esc(o.new)}</code>"]
132
+ total = 0
133
+ for s in job.scans:
134
+ head = f"\n<b>{esc(s.channel.title)}</b>"
135
+ if s.error:
136
+ lines.append(f"{head}\n⚠️ {esc(s.error)}")
137
+ continue
138
+ block = f"{head} - looked at post ids {s.first}-{s.scanned}"
139
+ if s.total == 0:
140
+ block += "\nNothing to change."
141
+ else:
142
+ t = sum(i.typed for i in s.infos.values())
143
+ b = sum(i.buttons for i in s.infos.values())
144
+ what = f"{t} mention(s) in the text" + (f", {b} in button names" if b else "")
145
+ block += f"\n{s.total} post(s) to change: {what}"
146
+ if s.foreign:
147
+ block += f"\nβ€’ {s.foreign} of them were not posted by this bot"
148
+ cb = sum(1 for i in s.infos.values() if i.callbacks)
149
+ if cb:
150
+ block += f"\nβ€’ {cb} carry other bots' buttons (e.g. reactions) - those stay as they are"
151
+ if s.skipped_post_links:
152
+ block += f"\nβ€’ left {s.skipped_post_links} mention(s) that are part of a link alone"
153
+ if s.not_editable:
154
+ block += f"\n⚠️ {s.not_editable} post(s) by others can't be edited: the bot lacks β€œEdit messages of others” here"
155
+ total += s.total
156
+ lines.append(block)
157
+ lines.append(f"\n<b>Total: {total} post(s).</b>")
158
+ if total:
159
+ lines.append("Nothing has been changed yet. Every edit is logged, so /undo can restore the old versions.")
160
+ return "\n".join(lines)
161
+
162
+
163
+ def summary_text(job: Job) -> str:
164
+ if job.opts.mode == "handles":
165
+ return handles_summary(job)
166
+ o = job.opts
167
+ lines = [f"πŸ”Ž <b>Scan finished</b> - replace <code>@{esc(o.old)}</code> β†’ <code>@{esc(o.new)}</code>"]
168
+ total = 0
169
+ for s in job.scans:
170
+ head = f"\n<b>{esc(s.channel.title)}</b>"
171
+ if s.error:
172
+ lines.append(f"{head}\n⚠️ {esc(s.error)}")
173
+ continue
174
+ block = f"{head} - looked at post ids {s.first}-{s.scanned}"
175
+ if s.total == 0:
176
+ block += "\nNothing to change."
177
+ else:
178
+ b = sum(i.buttons for i in s.infos.values())
179
+ h = sum(i.links for i in s.infos.values())
180
+ t = sum(i.typed for i in s.infos.values())
181
+ block += f"\n{s.total} post(s) to change: {b} button link(s), {h} hyperlink(s), {t} typed link(s)"
182
+ if s.foreign:
183
+ block += f"\nβ€’ {s.foreign} of them were not posted by this bot"
184
+ fb = sum(1 for i in s.infos.values() if not i.mine and i.buttons)
185
+ if fb:
186
+ block += f"\nβ€’ {fb} are button posts made by someone else - Telegram may refuse to edit those; /repost can re-post them with the new links instead"
187
+ cb = sum(1 for i in s.infos.values() if i.callbacks)
188
+ if cb:
189
+ block += f"\nβ€’ {cb} carry other bots' buttons (e.g. reactions) - those stay as they are"
190
+ if s.skipped_post_links:
191
+ block += f"\nβ€’ skipped {s.skipped_post_links} link(s) to channel posts (t.me/{o.old}/123) - use --posts to change them too"
192
+ if s.not_editable:
193
+ block += f"\n⚠️ {s.not_editable} post(s) by others can't be edited: the bot lacks β€œEdit messages of others” here"
194
+ total += s.total
195
+ lines.append(block)
196
+ lines.append(f"\n<b>Total: {total} post(s).</b>")
197
+ if total:
198
+ lines.append("Nothing has been changed yet. Every edit is logged, so /undo can restore the old versions.")
199
+ return "\n".join(lines)
200
+
201
+
202
+ def register(ctx: Ctx) -> None:
203
+ client, db, cfg = ctx.client, ctx.db, ctx.cfg
204
+ lock = ctx.lock
205
+
206
+ def make_updater(event):
207
+ last = [0.0]
208
+
209
+ async def upd(text: str, force: bool = False) -> None:
210
+ now = time.monotonic()
211
+ if not force and now - last[0] < 3:
212
+ return
213
+ last[0] = now
214
+ try:
215
+ await edit_callback_message(event, text)
216
+ except errors.MessageNotModifiedError:
217
+ pass
218
+ except Exception:
219
+ log.debug("progress update failed", exc_info=True)
220
+
221
+ return upd
222
+
223
+ # ------------------------------------------------------------------ /replace media
224
+ @client.on(cmd("replace", args=True))
225
+ @guard(ctx, owner=True)
226
+ async def h_replace(event):
227
+ purge_pending(ctx)
228
+ raw = (event.pattern_match.group(1) or "").strip()
229
+ if not raw:
230
+ await say(event, "Reply to a new photo, video, or file with <code>/replace &lt;channel post link&gt;</code>.")
231
+ return
232
+ # File replacement mode: reply to a media message with /replace <link to the saved post>.
233
+ link_bits = parse_post_link(raw) if len(raw.split()) == 1 else None
234
+ if link_bits:
235
+ reply = await event.get_reply_message()
236
+ if reply is None:
237
+ raise UserError("Reply to the new photo, video, or file, then send /replace <channel post link>.")
238
+ kind = classify_media(reply)
239
+ if not kind:
240
+ raise UserError("The replied-to message must contain a photo, video, GIF, audio file, or document.")
241
+ ref, message_id = link_bits
242
+ channels = await db.list_channels()
243
+ channel = next((c for c in channels if c.id == ref), None) if isinstance(ref, int) else next(
244
+ (c for c in channels if (c.username or "").lower() == ref), None
245
+ )
246
+ if channel is None:
247
+ raise UserError("That post link is not from a registered channel. Check /channels.")
248
+ post = await db.find_by_message(channel.id, message_id)
249
+ if post is None:
250
+ report = await sync_ids(
251
+ ctx.client,
252
+ db,
253
+ channel,
254
+ [message_id],
255
+ SyncOptions(history=False, grace=0, delete_services=False, ignore=ctx.sync_ignore),
256
+ adopt_ids={message_id},
257
+ )
258
+ post = await db.find_by_message(channel.id, message_id)
259
+ if post is None:
260
+ if report.error:
261
+ raise UserError(f"I couldn't read that post: {report.error}")
262
+ if report.restricted:
263
+ raise UserError("Telegram is currently holding that post back, so I can't replace its media.")
264
+ if report.unsupported:
265
+ raise UserError("That post can't be saved in My posts, so its media can't be replaced here.")
266
+ raise UserError("That post no longer exists in the channel, or I can't add it to My posts.")
267
+ if post.status != "sent":
268
+ raise UserError("That post is not published yet.")
269
+ if is_rich(post):
270
+ raise UserError("That post is a rich message - it has no media or caption to replace. Edit its text in My posts.")
271
+ caption, entities, how = message_text(reply, cfg.markup_input) # Telegram's formatting, or HTML / Markdown
272
+ check_lengths(caption, True)
273
+
274
+ async def notify(text: str) -> None:
275
+ await say(event, text)
276
+
277
+ _, report = await apply_edit_reported(
278
+ ctx, post, channel, replace_media=True, notify=notify, media_kind=kind, media_file_id=pack_file_id(reply),
279
+ text=caption, entities=entities,
280
+ )
281
+ extra = edit_report_text(report)
282
+ await say(
283
+ event,
284
+ markup_note(how)
285
+ + f"βœ… Replaced the media in <b>{esc(channel.title)}</b> and updated My posts."
286
+ + (f"\n{extra}" if extra else ""),
287
+ )
288
+ return
289
+ raise UserError("Use /replace with a channel post link, replying to the new media. Username swaps use /swap.")
290
+
291
+ # ------------------------------------------------------------------ /swap usernames in links
292
+ @client.on(cmd("swap", args=True))
293
+ @guard(ctx, owner=True)
294
+ async def h_swap(event):
295
+ purge_pending(ctx)
296
+ raw = (event.pattern_match.group(1) or "").strip()
297
+ if not raw:
298
+ await say(event, USAGE)
299
+ return
300
+ try:
301
+ old, new, flags = parse_replace_args(raw)
302
+ chans = pick_channels(await db.list_channels(), flags["channel"])
303
+ except ValueError as e:
304
+ raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE))
305
+ if not chans:
306
+ raise UserError("No channels registered yet. Use /addchannel.")
307
+ opts = ScanOptions(
308
+ old=old,
309
+ new=new,
310
+ include_typed=cfg.replace_typed_links if flags["typed"] is None else flags["typed"],
311
+ include_posts=flags["posts"],
312
+ last=flags["last"],
313
+ )
314
+ await begin_scan(event, opts, chans)
315
+
316
+ # ---------------------------------------------------------------- /handleswap
317
+ @client.on(cmd("handleswap", args=True))
318
+ @guard(ctx, owner=True)
319
+ async def h_handleswap(event):
320
+ purge_pending(ctx)
321
+ raw = (event.pattern_match.group(1) or "").strip()
322
+ if not raw:
323
+ await say(event, USAGE_HANDLES)
324
+ return
325
+ try:
326
+ old, new, flags = parse_replace_args(raw, handles=True)
327
+ chans = pick_channels(await db.list_channels(), flags["channel"])
328
+ except ValueError as e:
329
+ raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE_HANDLES))
330
+ if not chans:
331
+ raise UserError("No channels registered yet. Use /addchannel.")
332
+ await begin_scan(event, ScanOptions(old=old, new=new, last=flags["last"], mode="handles"), chans)
333
+
334
+ async def begin_scan(event, opts, chans) -> None:
335
+ """Read the channels, show what would change and wait for the owner's yes."""
336
+ if lock.locked():
337
+ raise UserError("Another /swap, /handleswap or /undo is still running - wait for it to finish.")
338
+ async with lock:
339
+ status = await say(event, f"πŸ” Scanning {len(chans)} channel(s)…")
340
+ last_edit = [0.0]
341
+ scans = []
342
+ for ch in chans:
343
+ rights = await get_rights(client, ch)
344
+ if rights is not None and not rights.admin:
345
+ s = await _empty_scan(ch, "The bot is not an admin here any more.")
346
+ scans.append(s)
347
+ continue
348
+ can_edit = True if rights is None else rights.edit
349
+
350
+ async def prog(scan, title=ch.title):
351
+ now = time.monotonic()
352
+ if now - last_edit[0] < 3:
353
+ return
354
+ last_edit[0] = now
355
+ try:
356
+ await status.edit(f"πŸ” Scanning <b>{esc(title)}</b>: post id {scan.scanned} of {scan.top or '?'}…")
357
+ except Exception:
358
+ pass
359
+
360
+ try:
361
+ scan = await scan_channel(
362
+ client, ch, opts, can_edit_others=can_edit, mine_ids=await db.mine_message_ids(ch.id), progress=prog
363
+ )
364
+ except errors.RPCError as e:
365
+ scan = await _empty_scan(ch, explain_rpc(e))
366
+ scan.rights = rights
367
+ scans.append(scan)
368
+ job = Job(user=event.sender_id, opts=opts, scans=scans)
369
+ token = secrets.token_hex(4)
370
+ ctx.pending[token] = job
371
+ total = sum(s.total for s in scans)
372
+ kb = None
373
+ if total:
374
+ kb = [[Button.inline(f"βœ… Apply to {total} post(s)", f"rp:{token}:y"), Button.inline("βœ–οΈ Cancel", f"rp:{token}:n")]]
375
+ try:
376
+ await status.edit(summary_text(job), buttons=kb, link_preview=False)
377
+ except Exception:
378
+ await say(event, summary_text(job), kb)
379
+
380
+ async def _empty_scan(ch, error: str):
381
+ return ChannelScan(channel=ch, error=error)
382
+
383
+ @on_cb(ctx, "rp")
384
+ async def cb_replace(event, parts):
385
+ require_owner(ctx, event)
386
+ token, action = parts[0], parts[1]
387
+ job = ctx.pending.get(token)
388
+ if not isinstance(job, Job) or job.user != event.sender_id:
389
+ raise UserError("That scan has expired. Run /swap again.")
390
+ if action == "n":
391
+ ctx.pending.pop(token, None)
392
+ await show(event, "Cancelled - nothing was changed.")
393
+ return
394
+ if job.running or lock.locked():
395
+ raise UserError("It is already running.")
396
+ job.running = True
397
+ upd = make_updater(event)
398
+ o = job.opts
399
+ batch_id = (HANDLE_PREFIX if o.mode == "handles" else "") + secrets.token_hex(6)
400
+ totals = ApplyResult()
401
+ stopped: list = []
402
+ async with lock:
403
+ await db.create_batch(batch_id, o.old, o.new, event.sender_id)
404
+ todo = sum(s.total for s in job.scans)
405
+ done_before = 0
406
+ for s in job.scans:
407
+ if not s.infos:
408
+ continue
409
+
410
+ async def prog(res, s=s, base=done_before):
411
+ await upd(f"⏳ <b>{esc(s.channel.title)}</b> - {base + res.edited}/{todo} edited…")
412
+
413
+ try:
414
+ res = await apply_channel(
415
+ client, db, s, o, batch_id, event.sender_id, edit_delay=cfg.edit_delay, progress=prog
416
+ )
417
+ except Exception as e:
418
+ log.exception("apply failed in %s", s.channel.id)
419
+ totals.failed.append((0, f"{s.channel.title}: {type(e).__name__}"))
420
+ continue
421
+ done_before += res.edited
422
+ totals.edited += res.edited
423
+ totals.unchanged += res.unchanged
424
+ totals.missing += res.missing
425
+ totals.no_perm += res.no_perm
426
+ totals.failed += res.failed
427
+ if res.aborted:
428
+ stopped.append((s.channel.title, res.aborted))
429
+ ctx.pending.pop(token, None)
430
+ what = "username swap " if o.mode == "handles" else ""
431
+ lines = [f"βœ… <b>Done</b> - {what}<code>@{esc(o.old)}</code> β†’ <code>@{esc(o.new)}</code>", f"β€’ edited: <b>{totals.edited}</b>"]
432
+ if totals.unchanged:
433
+ lines.append(f"β€’ already fine / changed meanwhile: {totals.unchanged}")
434
+ if totals.missing:
435
+ lines.append(f"β€’ deleted meanwhile: {totals.missing}")
436
+ if totals.no_perm:
437
+ lines.append(f"β€’ skipped (no permission): {totals.no_perm}")
438
+ if totals.failed:
439
+ sample = ", ".join(f"#{m} {esc(n)}" for m, n in totals.failed[:8])
440
+ lines.append(f"β€’ <b>failed: {len(totals.failed)}</b> ({sample}{'…' if len(totals.failed) > 8 else ''})")
441
+ names = {n for _, n in totals.failed}
442
+ if names & {"MessageAuthorRequiredError", "InlineBotRequiredError", "ChatAdminRequiredError", "MessageIdInvalidError"}:
443
+ lines.append(
444
+ " Telegram doesn't let this bot edit those posts."
445
+ + ("" if o.mode == "handles" else " Use /repost to post them again with the new links.")
446
+ )
447
+ for title, name in stopped:
448
+ lines.append(f"⚠️ Stopped early in <b>{esc(title)}</b>: Telegram refused 5 edits in a row ({esc(name)}).")
449
+ undo_label = "↩️ Undo this swap" if o.mode == "handles" else "↩️ Undo this replace"
450
+ kb = [[Button.inline(undo_label, f"ruc:{batch_id}")]] if totals.edited else None
451
+ if kb:
452
+ try:
453
+ await edit_callback_message(event, "\n".join(lines), kb)
454
+ except errors.MessageNotModifiedError:
455
+ pass
456
+ else:
457
+ await upd("\n".join(lines), force=True)
458
+
459
+ # -------------------------------------------------------------------- /undo
460
+ async def ask_undo(event, batch) -> None:
461
+ n = await db.count_batch_changes(batch.id)
462
+ what = "username swap" if batch.id.startswith(HANDLE_PREFIX) else "replace"
463
+ await say(
464
+ event,
465
+ f"↩️ Undo the {what} <code>@{esc(batch.old_username)}</code> β†’ <code>@{esc(batch.new_username)}</code>?\n"
466
+ f"{n} post(s) will be put back exactly as they were before.",
467
+ [[Button.inline("βœ… Yes, undo", f"ru:{batch.id}"), Button.inline("βœ–οΈ No", "cx")]],
468
+ )
469
+
470
+ @client.on(cmd("undo"))
471
+ @guard(ctx, owner=True)
472
+ async def h_undo(event):
473
+ batch = await db.last_batch()
474
+ if batch is None:
475
+ raise UserError("There is nothing to undo - no /swap or /handleswap run yet.")
476
+ await ask_undo(event, batch)
477
+
478
+ @on_cb(ctx, "ruc")
479
+ async def cb_undo_ask(event, parts):
480
+ require_owner(ctx, event)
481
+ batch = await db.get_batch(parts[0])
482
+ if batch is None or batch.undone:
483
+ raise UserError("That replace was already undone.")
484
+ await ask_undo(event, batch)
485
+
486
+ @on_cb(ctx, "ru")
487
+ async def cb_undo(event, parts):
488
+ require_owner(ctx, event)
489
+ if lock.locked():
490
+ raise UserError("Another /swap, /handleswap or /undo is still running.")
491
+ upd = make_updater(event)
492
+ async with lock:
493
+ await upd("⏳ Restoring…", force=True)
494
+
495
+ async def prog(res):
496
+ await upd(f"⏳ Restoring… {res.restored} done")
497
+
498
+ res = await undo_batch(client, db, parts[0], edit_delay=cfg.edit_delay, progress=prog)
499
+ text = f"↩️ Restored <b>{res.restored}</b> post(s)."
500
+ if res.failed:
501
+ text += f"\n⚠️ {len(res.failed)} could not be restored (" + ", ".join(f"#{m} {esc(n)}" for m, n in res.failed[:6]) + ")."
502
+ await upd(text, force=True)
app/handlers/repost.py ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/repost: copy a whole channel in order (links swapped on the way), then remove the old posts. Owner only."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import re
6
+ import secrets
7
+ import time
8
+ from dataclasses import dataclass, field
9
+
10
+ from telethon import Button, errors
11
+
12
+ from .. import picker
13
+ from ..common import Ctx, UserError, cmd, edit_callback_message, guard, on_cb, purge_pending, require_owner, say, show
14
+ from ..crosslinks import CrossResult, progress_text, relink_after_repost, report_lines, restore_after_undo
15
+ from ..linkswap import normalize_username
16
+ from ..profile_copy import profile_lines
17
+ from ..repost_engine import RepostOptions, RepostPlan, delete_copies, plan_repost, run_repost, saved_lookup
18
+ from ..tgutil import esc, get_rights, post_link
19
+ from ..userbot import delete_problem_text
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+ USAGE = (
24
+ "Usage: <code>/repost @old @new</code>\n"
25
+ "Copies every post of a channel, in order, to the end of the channel and swaps the username inside "
26
+ "t.me links on the way. Leave out the usernames to copy without changing links. "
27
+ "You pick the channel with buttons afterwards.\n"
28
+ "Options: <code>--last 5</code> (trial: only the newest 5 post ids), "
29
+ "<code>--posts</code> (also change t.me/old/123 post links), <code>--no-typed</code>.\n\n"
30
+ "Links to the old posts - in this channel and in all your other connected channels - are pointed at the copies "
31
+ "afterwards.\n"
32
+ "Nothing is deleted by /repost itself: you decide about the old posts after checking the copies."
33
+ )
34
+
35
+
36
+ @dataclass
37
+ class RepostChoice:
38
+ """/repost was typed; the owner still has to pick the channel."""
39
+
40
+ user: int
41
+ opts: RepostOptions
42
+ created: float = field(default_factory=time.monotonic)
43
+
44
+
45
+ @dataclass
46
+ class RepostJob:
47
+ user: int
48
+ ch: object
49
+ opts: RepostOptions
50
+ plan: object = None
51
+ running: bool = False
52
+ stop: bool = False
53
+ mig_id: str = ""
54
+ created: float = field(default_factory=time.monotonic)
55
+
56
+
57
+ def parse_repost_args(raw: str) -> tuple:
58
+ toks = (raw or "").split()
59
+ flags = {"last": None, "posts": False, "typed": None}
60
+ pos: list = []
61
+ i = 0
62
+ while i < len(toks):
63
+ t = toks[i]
64
+ if t == "--channel":
65
+ raise ValueError("/repost no longer takes --channel: send the command without it and pick the channel with the buttons.")
66
+ elif t == "--last" and i + 1 < len(toks):
67
+ if not toks[i + 1].isdigit() or int(toks[i + 1]) < 1:
68
+ raise ValueError("--last needs a number, for example --last 5")
69
+ flags["last"] = int(toks[i + 1])
70
+ i += 2
71
+ elif t == "--posts":
72
+ flags["posts"] = True
73
+ i += 1
74
+ elif t == "--no-typed":
75
+ flags["typed"] = False
76
+ i += 1
77
+ elif t.startswith("--"):
78
+ raise ValueError(f"Unknown option {t}")
79
+ else:
80
+ pos.append(t)
81
+ i += 1
82
+ old = new = None
83
+ if pos:
84
+ if len(pos) != 2:
85
+ raise ValueError("Give both usernames (@old @new), or none to copy without changing links.")
86
+ old, new = normalize_username(pos[0]), normalize_username(pos[1])
87
+ if not old or not new:
88
+ raise ValueError("Usernames look like @name (letters, digits and underscores).")
89
+ if old.lower() == new.lower():
90
+ raise ValueError("The old and the new username are the same.")
91
+ return old, new, flags
92
+
93
+
94
+ def plan_text(p: RepostPlan, o: RepostOptions, title: str, delay: float) -> str:
95
+ kinds = f"{p.text} text, {p.media} media"
96
+ if p.polls:
97
+ kinds += f", {p.polls} poll(s)"
98
+ if p.other:
99
+ kinds += f", {p.other} other"
100
+ lines = [
101
+ f"🧱 <b>Repost plan - {esc(title)}</b>",
102
+ f"Post ids {p.first}-{p.last}: <b>{p.units} posts</b> to copy ({p.messages} messages, {p.albums} album(s)) - {kinds}",
103
+ ]
104
+ if p.service:
105
+ lines.append(f"β€’ {p.service} service message(s) (like β€œpinned a message”) can't be copied and are skipped")
106
+ if p.polls:
107
+ lines.append("β€’ polls are copied without their votes")
108
+ if o.swaps:
109
+ lines.append(
110
+ f"β€’ <code>@{esc(o.old)}</code> β†’ <code>@{esc(o.new)}</code> in {p.link_posts} post(s): "
111
+ f"{p.n_buttons} button link(s), {p.n_links} hyperlink(s), {p.n_typed} typed link(s)"
112
+ )
113
+ if p.dropped_posts:
114
+ lines.append(f"β€’ {p.dropped_posts} post(s) carry other bots' buttons (reactions...) - those are not copied")
115
+ lines += held_plan_lines(p, title)
116
+ if p.post_links:
117
+ lines.append(
118
+ f"β€’ {p.post_links} link(s) in {p.post_link_posts} post(s) point at other posts of this channel: "
119
+ "they are pointed at the new copies (a link to a post that doesn't exist stays as it is)"
120
+ )
121
+ lines.append(
122
+ "β€’ afterwards every link to an old post - a hyperlink, a typed link or a button, in ANY of your connected "
123
+ "channels - is pointed at the copy (the old posts themselves are not touched)"
124
+ )
125
+ if p.replies:
126
+ lines.append(f"β€’ {p.replies} post(s) answer another post: each copy answers the copy of that post")
127
+ if p.pinned:
128
+ lines.append(
129
+ f"β€’ {p.pinned} pinned post(s): their copies are pinned at the end "
130
+ "(the bot needs the β€œEdit messages of others” right for that)"
131
+ )
132
+ minutes = max(1, round(p.eta_seconds(delay) / 60))
133
+ lines += [
134
+ "",
135
+ "<b>How:</b> posts without buttons, replies or links to change are copied by Telegram itself, so they stay "
136
+ "exactly as they are. Posts with buttons, links to change or a reply are posted again with their text, "
137
+ "formatting, media and buttons in one go, and each one is read back to make sure its buttons are really "
138
+ "there. Copies go to the end of the channel silently, in the original order, and are registered in My posts.",
139
+ "",
140
+ "<b>Not kept:</b> original dates, view counts, reactions, comments and poll votes.",
141
+ f"Time: about {minutes} min. Please don't post in the channel meanwhile.",
142
+ "<b>Nothing is deleted in this step.</b>",
143
+ ]
144
+ if p.partial:
145
+ lines.append("Trial run: afterwards you can remove the copies again.")
146
+ return "\n".join(lines)
147
+
148
+
149
+ def held_plan_lines(p: RepostPlan, title: str, *, shift: bool = False) -> list:
150
+ """Plan lines about posts Telegram restricts (a copyright strike: the channel is "unavailable", or its posts are
151
+ marked or shown as a notice)."""
152
+ lines = []
153
+ name = esc(title)
154
+ said = f" (β€œ{esc(p.held_why)}”)" if p.held_why else ""
155
+ if p.channel_restricted and shift:
156
+ lines.append(f"β€’ ⚠️ Telegram restricts {name} itself: β€œ{esc(p.channel_restricted)}”")
157
+ elif p.channel_restricted:
158
+ lines.append(
159
+ f"β€’ ⚠️ Telegram restricts {name} itself: β€œ{esc(p.channel_restricted)}”. Telegram may hide what is posted into "
160
+ "such a channel as well, so a repost here may not bring the posts back. To save a struck channel use "
161
+ "/shift: it copies the posts from My posts into another channel."
162
+ )
163
+ if p.held_saved and p.no_media:
164
+ lines.append(
165
+ f"β€’ πŸ“‹ {p.held_saved} post(s) of {name} are restricted by Telegram{said}. They are copied from what My posts "
166
+ "saved of them - text, formatting and buttons - not from what Telegram shows now."
167
+ )
168
+ elif p.held_saved:
169
+ lines.append(
170
+ f"β€’ πŸ“‹ {p.held_saved} post(s) of {name} are restricted by Telegram{said}. They are copied from what My posts "
171
+ "saved of them - text, formatting, buttons and media - not from what Telegram shows now (a file that "
172
+ "Telegram refuses goes out without it)."
173
+ )
174
+ if p.live_restricted and shift:
175
+ lines.append(
176
+ f"β€’ ⚠️ {p.live_restricted} restricted post(s) of {name} have no saved copy in My posts, but Telegram still "
177
+ "hands out their content, so they are copied as they are now."
178
+ )
179
+ elif p.live_restricted:
180
+ lines.append(
181
+ f"β€’ ⚠️ Telegram marks {p.live_restricted} post(s) of {name} as restricted but still hands out their content, "
182
+ "so they are copied as they are now."
183
+ )
184
+ if p.held_skipped and shift:
185
+ lines.append(
186
+ f"β€’ ⚠️ Telegram shows only its notice for {p.held_skipped} more post(s) of {name}{said} and My posts has no "
187
+ "saved copy of them, so they are skipped and the shift will show as not complete. If you have a backup made "
188
+ "before that, put it back with /import and run /shift again."
189
+ )
190
+ elif p.held_skipped:
191
+ lines.append(
192
+ f"β€’ ⚠️ Telegram holds back {p.held_skipped} post(s) of {name}{said} - it shows a notice instead of them. "
193
+ "Copying the notice would be wrong, so they are skipped, and the old posts can't be deleted afterwards "
194
+ "(the repost will show as not complete)."
195
+ )
196
+ if p.channel_restricted or p.held_saved or p.live_restricted:
197
+ lines.append("β€’ The new posts are read back: if Telegram itself hides them, the report says so.")
198
+ return lines
199
+
200
+
201
+ def held_notes(res) -> list:
202
+ """Lines about the posts Telegram restricts, for the end of a repost or shift."""
203
+ notes = []
204
+
205
+ def sample(ids, n=8):
206
+ return ", ".join(f"#{i}" for i in ids[:n]) + ("…" if len(ids) > n else "")
207
+
208
+ what = "text, formatting and buttons" if getattr(res, "no_media", False) else "text, formatting, buttons and media"
209
+ if res.from_db:
210
+ if res.from_saved:
211
+ notes.append(
212
+ f"πŸ“‹ The source can't be read, so {res.from_saved} post(s) were copied from what My posts saved of them: "
213
+ f"{what} - without replies, pins and albums."
214
+ )
215
+ elif res.from_saved:
216
+ notes.append(
217
+ f"πŸ“‹ {res.from_saved} post(s) are restricted by Telegram. They were copied from what My posts saved of "
218
+ f"them: {what}."
219
+ )
220
+ if res.media_lost:
221
+ notes.append(
222
+ f"⚠️ {len(res.media_lost)} of them went out without their media, because Telegram refuses the saved file "
223
+ f"({sample(res.media_lost)})."
224
+ )
225
+ if res.live_restricted and res.used_saved:
226
+ notes.append(
227
+ f"⚠️ {res.live_restricted} restricted post(s) had no saved copy in My posts, so they were copied as Telegram "
228
+ "hands them out (their content was intact)."
229
+ )
230
+ elif res.live_restricted:
231
+ notes.append(
232
+ f"⚠️ Telegram marks {res.live_restricted} post(s) as restricted but still handed out their content, so they "
233
+ "were copied as they are."
234
+ )
235
+ if res.held_back and res.used_saved:
236
+ notes.append(
237
+ f"⚠️ {len(res.held_back)} post(s): Telegram shows only its notice and My posts has no saved copy of them, so "
238
+ f"they were not copied ({sample(res.held_back)}). Put a backup made before that back with /import, then use "
239
+ "β€œTry the rest again”."
240
+ )
241
+ elif res.held_back:
242
+ notes.append(
243
+ f"⚠️ {len(res.held_back)} post(s) are held back by Telegram - it shows a notice instead of them "
244
+ f"({sample(res.held_back)}). Copying the notice would be wrong, so they were not copied and the old posts are "
245
+ "not deleted."
246
+ )
247
+ return notes
248
+
249
+
250
+ def no_media_notes(res) -> list:
251
+ """Lines about the files that /shift --no-media left out."""
252
+ if not getattr(res, "no_media", False):
253
+ return []
254
+ notes = []
255
+ if res.files_left_out:
256
+ notes.append(f"🚫 {res.files_left_out} post(s) were copied as text only - their file was left out (--no-media).")
257
+ if res.file_only:
258
+ ids = ", ".join(f"#{i}" for i in res.file_only[:8]) + ("…" if len(res.file_only) > 8 else "")
259
+ notes.append(f"🚫 {len(res.file_only)} post(s) are only a file, so there was nothing to copy of them ({ids}).")
260
+ return notes
261
+
262
+
263
+ def hidden_notes(res, *, shift: bool = False) -> list:
264
+ """Lines about new posts that TELEGRAM itself hides (they were read back after posting)."""
265
+ if not getattr(res, "hidden", None):
266
+ return []
267
+ k, n = len(res.hidden), res.checked
268
+ with_file = sum(1 for _, has in res.hidden if has)
269
+ plain = k - with_file
270
+ why = f" (β€œ{esc(res.hidden_why)}”)" if res.hidden_why else ""
271
+ lines = [
272
+ f"⚠️ <b>Telegram itself hides {k} of the {n} new post(s) I read back</b>{why}: right after they were created they "
273
+ "carry its restriction mark, so its apps show the notice instead of them. The bot did not copy a notice - it "
274
+ "never posts one: Telegram marks these posts itself, because of something in them or because of the destination."
275
+ ]
276
+ if with_file:
277
+ hint = (
278
+ " <code>/shift … --no-media</code> copies the text and buttons without the files."
279
+ if shift
280
+ else ""
281
+ )
282
+ lines.append(
283
+ f"β€’ {with_file} post(s) of these carry a file. Telegram may hide a message that carries a file it has "
284
+ f"blocked for copyright, wherever it is posted.{hint}"
285
+ )
286
+ if plain:
287
+ lines.append(
288
+ f"β€’ {plain} post(s) of these have no file: Telegram hides them for their text or links, or because it "
289
+ "restricts the new channel too."
290
+ )
291
+ if getattr(res, "dst_restricted", None):
292
+ lines.append(f"β€’ Telegram restricts the destination channel itself: β€œ{esc(res.dst_restricted)}”.")
293
+ if getattr(res, "hidden_stop", False):
294
+ lines.append(
295
+ f"⏹ <b>I stopped after {res.copied_units} post(s)</b>: Telegram hides every new copy I read back, so going on "
296
+ "would only add more posts nobody can see. Nothing else was posted. ▢️ <b>Continue anyway</b> copies the rest; "
297
+ "↩️ <b>Undo</b> removes the copies."
298
+ )
299
+ lines.append("The saved posts in My posts are intact. Undo removes the new copies again.")
300
+ return lines
301
+
302
+
303
+ def hidden_progress(res) -> str:
304
+ """One line for the running progress message when Telegram hides what was just posted."""
305
+ if not getattr(res, "hidden", None):
306
+ return ""
307
+ why = f" (β€œ{esc(res.hidden_why)}”)" if res.hidden_why else ""
308
+ return f"\n⚠️ Telegram itself hides {len(res.hidden)} of the {res.checked} new posts checked so far{why}. ⏹ Stop is below."
309
+
310
+
311
+ def finishing_notes(res, *, shift: bool = False) -> list:
312
+ """Lines about answers, links and pins for the end of a repost or shift."""
313
+ notes = held_notes(res) + no_media_notes(res) + hidden_notes(res, shift=shift)
314
+ if res.replies:
315
+ notes.append(f"↩️ {res.replies} post(s) answer the copy of the post they answered.")
316
+ if res.reply_lost:
317
+ notes.append(f"{res.reply_lost} post(s) could only be copied without their reply (their media can't be rebuilt).")
318
+ if res.reply_dropped:
319
+ notes.append(f"{res.reply_dropped} post(s) answered a post that is not there any more, so they answer nothing.")
320
+ fin = res.final
321
+ if fin is not None:
322
+ if fin.relinked:
323
+ notes.append(f"πŸ”— {fin.links} link(s) in {fin.relinked} post(s) now point at the new copies.")
324
+ if fin.failed:
325
+ sample = ", ".join(f"#{i} {esc(n)}" for i, n in fin.failed[:5])
326
+ notes.append(f"{len(fin.failed)} post(s) could not get their links updated ({sample}).")
327
+ if fin.pinned:
328
+ notes.append(f"πŸ“Œ {fin.pinned} pinned post(s) are pinned again.")
329
+ if fin.pin_error:
330
+ notes.append(
331
+ f"πŸ“Œ {fin.pin_wanted - fin.pinned} copy/copies could not be pinned ({esc(fin.pin_error)}). Give the bot the "
332
+ "β€œEdit messages of others” right, or pin them by hand."
333
+ )
334
+ if res.final_error:
335
+ notes.append(f"Links and pins could not be finished ({esc(res.final_error)}).")
336
+ if res.profile is not None:
337
+ notes += profile_lines(res.profile)
338
+ if res.profile_error:
339
+ notes.append(f"The name, description and photo could not be copied ({esc(res.profile_error)}).")
340
+ if res.cross is not None:
341
+ notes += report_lines(res.cross)
342
+ if res.cross_error:
343
+ notes.append(
344
+ f"Links in your other channels could not be updated ({esc(res.cross_error)}). "
345
+ "Press β€œπŸ”— Update links again” to try once more."
346
+ )
347
+ return notes
348
+
349
+
350
+ def register(ctx: Ctx) -> None:
351
+ client, db, cfg = ctx.client, ctx.db, ctx.cfg
352
+
353
+ # ---------------------------------------------------------------- views
354
+ async def view_for(mig):
355
+ """Text and buttons describing where a repost stands."""
356
+ ch = await db.get_channel(mig.channel_id)
357
+ c = await db.migration_counts(mig.id)
358
+ name = esc(ch.title) if ch else str(mig.channel_id)
359
+ swap = f" (<code>@{esc(mig.old_username)}</code> β†’ <code>@{esc(mig.new_username)}</code>)" if mig.old_username else ""
360
+ first_copy = ""
361
+ if ch and c["first_new"]:
362
+ first_copy = f'\n<a href="{post_link(ch, c["first_new"])}">First copy</a>'
363
+ undo = [Button.inline("↩️ Undo - remove the copies", f"rpu:{mig.id}")]
364
+ links = [Button.inline("πŸ”— Update links again", f"rpl:{mig.id}")]
365
+ if mig.status == "copied" and not mig.partial:
366
+ text = (
367
+ f"βœ… <b>{name}: all posts copied in order</b>{swap}\n{c['copied']} messages are now at the end of the channel "
368
+ f"and in My posts.{first_copy}\n\nLook at the end of the channel and check a few posts: formatting, "
369
+ "buttons, media. If it looks right, delete the old posts. If not, undo: the copies are removed and the "
370
+ "originals were never touched."
371
+ )
372
+ kb = [[Button.inline("πŸ—‘ Delete the old posts", f"rpd:{mig.id}")], links, undo]
373
+ elif mig.status == "copied":
374
+ text = (
375
+ f"βœ… <b>{name}: trial finished</b>{swap}\n{c['copied']} message(s) copied.{first_copy}\n"
376
+ "Check them. Remove them again, or close this trial and keep them."
377
+ )
378
+ kb = [links, undo, [Button.inline("βœ… Close, keep the copies", f"rpk:{mig.id}")]]
379
+ elif mig.status == "stopped":
380
+ text = f"⏹ <b>{name}: stopped</b>{swap}\n{c['copied']} message(s) copied so far.{first_copy}"
381
+ kb = [[Button.inline("▢️ Continue", f"rpc:{mig.id}")], undo]
382
+ elif mig.status == "copying":
383
+ text = f"⏳ <b>{name}</b>: a repost was running when the bot stopped. {c['copied']} message(s) copied.{first_copy}"
384
+ kb = [[Button.inline("▢️ Continue", f"rpc:{mig.id}")], undo]
385
+ else: # incomplete
386
+ text = (
387
+ f"⚠️ <b>{name}: not everything was copied</b>{swap}\n{c['copied']} message(s) copied.{first_copy}\n"
388
+ "Old posts are only deleted once everything is copied, so nothing is lost. Try the rest again, "
389
+ "or undo."
390
+ )
391
+ kb = [[Button.inline("πŸ” Try the rest again", f"rpc:{mig.id}")], undo]
392
+ return text, kb
393
+
394
+ # --------------------------------------------------------------- /repost
395
+ @client.on(cmd("repost", args=True))
396
+ @guard(ctx, owner=True)
397
+ async def h_repost(event):
398
+ purge_pending(ctx)
399
+ raw = (event.pattern_match.group(1) or "").strip()
400
+ if not raw:
401
+ mig = await db.open_migration()
402
+ if mig is not None:
403
+ text, kb = await view_for(mig)
404
+ await say(event, "Unfinished repost:\n\n" + text, kb)
405
+ else:
406
+ await say(event, USAGE)
407
+ return
408
+ try:
409
+ old, new, flags = parse_repost_args(raw)
410
+ except ValueError as e:
411
+ raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE))
412
+ chans = await db.list_channels()
413
+ if not chans:
414
+ raise UserError("No channels registered yet. Use /addchannel.")
415
+ opts = RepostOptions(
416
+ old=old,
417
+ new=new,
418
+ include_typed=cfg.replace_typed_links if flags["typed"] is None else flags["typed"],
419
+ include_posts=flags["posts"],
420
+ last=flags["last"],
421
+ )
422
+ token = secrets.token_hex(4)
423
+ ctx.pending[token] = RepostChoice(user=event.sender_id, opts=opts)
424
+ await show_picker(event, token, 0)
425
+
426
+ async def show_picker(event, token: str, page: int) -> None:
427
+ require_owner(ctx, event)
428
+ choice = ctx.pending.get(token)
429
+ if not isinstance(choice, RepostChoice) or choice.user != event.sender_id:
430
+ raise UserError("That list has expired. Run /repost again.")
431
+ chans = await db.list_channels()
432
+ if not chans:
433
+ raise UserError("No channels registered yet. Use /addchannel.")
434
+ opts = choice.opts
435
+ what = (
436
+ f"swap <code>@{esc(opts.old)}</code> β†’ <code>@{esc(opts.new)}</code> in the links"
437
+ if opts.swaps
438
+ else "copy without changing any link"
439
+ )
440
+ if opts.last:
441
+ what += f", trial: only the newest {opts.last} post ids"
442
+ text, kb = picker.render(
443
+ chans,
444
+ page,
445
+ head=f"πŸ“’ <b>Which channel should I repost?</b>\nPlan: {what}.",
446
+ kind="rp",
447
+ arg=token,
448
+ choose=lambda c: f"rpch:{token}:{c.id}",
449
+ extra_rows=[[Button.inline("βœ–οΈ Cancel", f"rpn:{token}")]],
450
+ )
451
+ await show(event, text, kb)
452
+
453
+ ctx.pickers["rp"] = show_picker
454
+
455
+ @on_cb(ctx, "rpch")
456
+ async def cb_pick(event, parts):
457
+ require_owner(ctx, event)
458
+ token, cid = parts[0], int(parts[1])
459
+ choice = ctx.pending.get(token)
460
+ if not isinstance(choice, RepostChoice) or choice.user != event.sender_id:
461
+ raise UserError("That list has expired. Run /repost again.")
462
+ ch = await db.get_channel(cid)
463
+ if ch is None or not ch.active:
464
+ raise UserError("That channel is not registered any more. Run /repost again.")
465
+ mig = await db.open_migration(ch.id)
466
+ if mig is not None:
467
+ ctx.pending.pop(token, None)
468
+ text, kb = await view_for(mig)
469
+ await edit_callback_message(
470
+ event, "There is an unfinished repost for this channel. Finish or undo it first.\n\n" + text, kb
471
+ )
472
+ return
473
+ rights = await get_rights(client, ch)
474
+ if rights is not None and not (rights.admin and rights.post):
475
+ raise UserError("The bot needs the β€œPost messages” admin right in that channel.")
476
+ if ctx.lock.locked():
477
+ raise UserError("Another long job (replace / repost) is still running.")
478
+ ctx.pending.pop(token, None) # a second press on the list can't start a second plan
479
+ opts = choice.opts
480
+ last = [0.0]
481
+
482
+ async def prog(p):
483
+ if time.monotonic() - last[0] < 3:
484
+ return
485
+ last[0] = time.monotonic()
486
+ try:
487
+ await edit_callback_message(event, f"πŸ” Reading <b>{esc(ch.title)}</b>: post id {p.scanned}…")
488
+ except Exception:
489
+ pass
490
+
491
+ async with ctx.lock:
492
+ await edit_callback_message(event, f"πŸ” Reading <b>{esc(ch.title)}</b>…")
493
+ plan = await plan_repost(client, ch, opts, progress=prog, saved=saved_lookup(db, ch.id))
494
+ if plan.error:
495
+ await edit_callback_message(event, f"⚠️ {esc(plan.error)}")
496
+ return
497
+ job = RepostJob(user=event.sender_id, ch=ch, opts=opts, plan=plan)
498
+ ctx.pending[token] = job
499
+ kb = [[Button.inline("▢️ Start copying", f"rpa:{token}"), Button.inline("βœ–οΈ Cancel", f"rpn:{token}")]]
500
+ await edit_callback_message(event, plan_text(plan, opts, ch.title, cfg.edit_delay), kb)
501
+
502
+ @on_cb(ctx, "rpn")
503
+ async def cb_cancel(event, parts):
504
+ require_owner(ctx, event)
505
+ ctx.pending.pop(parts[0], None)
506
+ await edit_callback_message(event, "Cancelled - nothing was copied or deleted.")
507
+
508
+ # ------------------------------------------------------------------ copy
509
+ async def run_copy(event, job: RepostJob) -> None:
510
+ mig = await db.get_migration(job.mig_id)
511
+ ch = job.ch
512
+ job.running, job.stop = True, False
513
+ ctx.pending[f"job:{mig.id}"] = job
514
+ total = job.plan.units if job.plan else None
515
+ last = [0.0]
516
+
517
+ async def prog(res):
518
+ if res.phase in ("copy", "links") and time.monotonic() - last[0] < 4:
519
+ return
520
+ last[0] = time.monotonic()
521
+ done = res.copied_units + res.skipped_done
522
+ of = f"/{total}" if total else ""
523
+ if res.phase == "links" and res.cross is not None:
524
+ body = f"βœ… Copied {done}{of} posts.\n" + progress_text(res.cross)
525
+ elif res.phase == "finish":
526
+ body = f"πŸ”— Copied {done}{of} posts. Now pointing links at the new copies and pinning…"
527
+ else:
528
+ body = f"⏳ Copying <b>{esc(ch.title)}</b>: {done}{of} posts…\nThe old posts stay untouched."
529
+ body += hidden_progress(res)
530
+ try:
531
+ await edit_callback_message(event, body, [[Button.inline("⏹ Stop", f"rps:{mig.id}")]])
532
+ except errors.MessageNotModifiedError:
533
+ pass
534
+ except Exception:
535
+ log.debug("progress update failed", exc_info=True)
536
+
537
+ try:
538
+ async with ctx.lock:
539
+ await db.set_migration_status(mig.id, "copying")
540
+ res = await run_repost(
541
+ client, db, ch, mig, event.sender_id, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop
542
+ )
543
+ finally:
544
+ job.running = False
545
+ status = "stopped" if res.stopped else ("incomplete" if (res.failed or res.aborted or res.held_back) else "copied")
546
+ await db.set_migration_status(mig.id, status)
547
+ mig = await db.get_migration(mig.id)
548
+ text, kb = await view_for(mig)
549
+ notes = []
550
+ if res.copied_units:
551
+ notes.append(
552
+ f"{res.forwarded} post(s) were copied by Telegram, {res.rebuilt} were posted again with their buttons."
553
+ )
554
+ if res.repaired:
555
+ notes.append(f"{res.repaired} post(s) needed their buttons set again after posting - they show them now.")
556
+ if res.failed:
557
+ sample = ", ".join(f"#{i} {esc(n)}" for i, n in res.failed[:6])
558
+ notes.append(f"<b>{len(res.failed)} post(s) failed</b> ({sample}{'…' if len(res.failed) > 6 else ''}).")
559
+ if any(n == "ButtonsNotShown" for _, n in res.failed):
560
+ notes.append(
561
+ "ButtonsNotShown: Telegram did not show the buttons on the new post, so that copy was removed again. "
562
+ "The original is untouched - use β€œTry the rest again”."
563
+ )
564
+ if res.aborted:
565
+ notes.append(f"Stopped early because of {esc(res.aborted)}.")
566
+ notes += finishing_notes(res)
567
+ await edit_callback_message(event, text + ("\n\n" + "\n".join(notes) if notes else ""), kb)
568
+
569
+ @on_cb(ctx, "rpa")
570
+ async def cb_start(event, parts):
571
+ require_owner(ctx, event)
572
+ job = ctx.pending.get(parts[0])
573
+ if not isinstance(job, RepostJob) or job.user != event.sender_id:
574
+ raise UserError("That plan has expired. Run /repost again.")
575
+ if job.running or ctx.lock.locked():
576
+ raise UserError("A long job is already running.")
577
+ if await db.open_migration(job.ch.id) is not None:
578
+ raise UserError("There is already an unfinished repost for this channel.")
579
+ p, o = job.plan, job.opts
580
+ job.mig_id = secrets.token_hex(6)
581
+ await db.create_migration(
582
+ job.mig_id, job.ch.id, old=o.old, new=o.new, include_typed=o.include_typed, include_posts=o.include_posts,
583
+ first_id=p.first, last_id=p.last, partial=p.partial, user_id=event.sender_id,
584
+ )
585
+ ctx.pending.pop(parts[0], None)
586
+ await run_copy(event, job)
587
+
588
+ @on_cb(ctx, "rpc")
589
+ async def cb_continue(event, parts):
590
+ require_owner(ctx, event)
591
+ mig = await db.get_migration(parts[0])
592
+ if mig is None or mig.status not in ("stopped", "incomplete", "copying"):
593
+ raise UserError("There is nothing to continue.")
594
+ if ctx.lock.locked():
595
+ raise UserError("A long job is already running.")
596
+ ch = await db.get_channel(mig.channel_id)
597
+ if ch is None:
598
+ raise UserError("That channel is not registered any more.")
599
+ opts = RepostOptions(old=mig.old_username, new=mig.new_username, include_typed=mig.include_typed, include_posts=mig.include_posts)
600
+ await run_copy(event, RepostJob(user=event.sender_id, ch=ch, opts=opts, mig_id=mig.id))
601
+
602
+ @on_cb(ctx, "rps")
603
+ async def cb_stop(event, parts):
604
+ require_owner(ctx, event)
605
+ job = ctx.pending.get(f"job:{parts[0]}")
606
+ if isinstance(job, RepostJob) and job.running:
607
+ job.stop = True
608
+ await event.respond("⏹ Stopping after the post that is being worked on…")
609
+ else:
610
+ await event.respond("Nothing is running.")
611
+
612
+ # ------------------------------------------------------------ links again
613
+ @on_cb(ctx, "rpl")
614
+ async def cb_links(event, parts):
615
+ """Look through every connected channel once more for links to the old posts and point them at the copies."""
616
+ require_owner(ctx, event)
617
+ mig, ch = await load(parts)
618
+ if mig.status not in ("copied", "old_deleted"):
619
+ raise UserError("Links can be updated once everything is copied.")
620
+ if ctx.lock.locked():
621
+ raise UserError("A long job is already running.")
622
+ job = RepostJob(user=event.sender_id, ch=ch, opts=RepostOptions(), mig_id=mig.id, running=True)
623
+ ctx.pending[f"job:{mig.id}"] = job
624
+ cross, last = CrossResult(), [0.0]
625
+
626
+ async def prog(c):
627
+ if time.monotonic() - last[0] < 4:
628
+ return
629
+ last[0] = time.monotonic()
630
+ try:
631
+ await edit_callback_message(event, progress_text(c), [[Button.inline("⏹ Stop", f"rps:{mig.id}")]])
632
+ except errors.MessageNotModifiedError:
633
+ pass
634
+ except Exception:
635
+ log.debug("progress update failed", exc_info=True)
636
+
637
+ error = None
638
+ try:
639
+ async with ctx.lock:
640
+ await edit_callback_message(event, "πŸ”— Looking for links to the old posts in your channels…")
641
+ await relink_after_repost(
642
+ client, db, ch, mig, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop, result=cross
643
+ )
644
+ except Exception as e: # the posts are fine; only the links were not (all) updated
645
+ log.exception("pointing the links at the copies failed")
646
+ error = type(e).__name__
647
+ finally:
648
+ job.running = False
649
+ ctx.pending.pop(f"job:{mig.id}", None)
650
+ notes = report_lines(cross)
651
+ if error:
652
+ notes.append(f"Links could not be updated ({esc(error)}).")
653
+ if not notes:
654
+ notes.append("πŸ”— There is nothing to change.")
655
+ again = [Button.inline("πŸ”— Update links again", f"rpl:{mig.id}")]
656
+ if mig.status == "copied":
657
+ text, kb = await view_for(mig)
658
+ await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb)
659
+ else:
660
+ await edit_callback_message(event, f"πŸ”— <b>{esc(ch.title)}</b>\n" + "\n".join(notes), [again])
661
+
662
+ # ----------------------------------------------------- delete old / undo
663
+ async def load(parts):
664
+ mig = await db.get_migration(parts[0])
665
+ if mig is None:
666
+ raise UserError("I don't know that repost any more.")
667
+ ch = await db.get_channel(mig.channel_id)
668
+ if ch is None:
669
+ raise UserError("That channel is not registered any more.")
670
+ return mig, ch
671
+
672
+ @on_cb(ctx, "rpb")
673
+ async def cb_back(event, parts):
674
+ mig, _ = await load(parts)
675
+ text, kb = await view_for(mig)
676
+ await edit_callback_message(event, text, kb)
677
+
678
+ @on_cb(ctx, "rpd")
679
+ async def cb_delete_ask(event, parts):
680
+ require_owner(ctx, event)
681
+ mig, ch = await load(parts)
682
+ if mig.status != "copied" or mig.partial:
683
+ raise UserError("Old posts can only be deleted after a complete, successful copy.")
684
+ c = await db.migration_counts(mig.id)
685
+ await edit_callback_message(
686
+ event,
687
+ f"πŸ—‘ <b>Delete {c['old_left']} old message(s) from {esc(ch.title)}?</b>\n"
688
+ "Only originals that have a copy are deleted. This can't be undone. The copies stay and become the channel: "
689
+ "nothing is lost, they are already there.",
690
+ [[Button.inline(f"πŸ—‘ Yes, delete {c['old_left']}", f"rpdy:{mig.id}"), Button.inline("↩️ Back", f"rpb:{mig.id}")]],
691
+ )
692
+
693
+ def userbot_lines(deleter) -> str:
694
+ notes = getattr(deleter, "notes", None) or []
695
+ return ("\n" + "\n".join(f"β€’ {esc(n)}" for n in notes)) if notes else ""
696
+
697
+ @on_cb(ctx, "rpdy")
698
+ async def cb_delete_old(event, parts):
699
+ require_owner(ctx, event)
700
+ mig, ch = await load(parts)
701
+ if mig.status not in ("copied", "old_deleted") or mig.partial:
702
+ raise UserError("Old posts can only be deleted after a complete, successful copy.")
703
+ if ctx.lock.locked():
704
+ raise UserError("A long job is already running.")
705
+ last = [0.0]
706
+
707
+ async def prog(r):
708
+ if time.monotonic() - last[0] < 3:
709
+ return
710
+ last[0] = time.monotonic()
711
+ try:
712
+ await edit_callback_message(event, f"πŸ—‘ Deleting old posts… {r.deleted} done")
713
+ except Exception:
714
+ pass
715
+
716
+ fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None)
717
+ try:
718
+ async with ctx.lock:
719
+ res = await delete_copies(client, db, ch, mig, "old", delay=0.5, progress=prog, fallback=fallback)
720
+ finally:
721
+ if deleter is not None:
722
+ await deleter.close()
723
+ c = await db.migration_counts(mig.id)
724
+ extra = userbot_lines(deleter)
725
+ by = f" ({res.by_userbot} of them by the userbot)" if res.by_userbot else ""
726
+ if res.remaining == 0 and not res.error:
727
+ await db.set_migration_status(mig.id, "old_deleted")
728
+ await edit_callback_message(
729
+ event,
730
+ f"βœ… <b>Done.</b> {res.deleted} old message(s) deleted{by}. The channel now consists of the copies "
731
+ f"(from <a href=\"{post_link(ch, c['first_new'])}\">here</a>), and they are all in My posts.{extra}",
732
+ [[Button.inline("πŸ”— Update links again", f"rpl:{mig.id}")]],
733
+ )
734
+ return
735
+ why = esc(
736
+ delete_problem_text(
737
+ ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot
738
+ )
739
+ )
740
+ await edit_callback_message(
741
+ event,
742
+ f"⚠️ Deleted {res.deleted}{by}, {res.remaining} old message(s) are still there. {why}{extra}\n"
743
+ f"The copies are complete. You can delete the rest by hand: they are the messages with an id below "
744
+ f"{c['first_new']}. Then close this repost.",
745
+ [[Button.inline("πŸ” Try again", f"rpdy:{mig.id}")], [Button.inline("βœ… Close this repost", f"rpk:{mig.id}")]],
746
+ )
747
+
748
+ @on_cb(ctx, "rpu")
749
+ async def cb_undo_ask(event, parts):
750
+ require_owner(ctx, event)
751
+ mig, ch = await load(parts)
752
+ c = await db.migration_counts(mig.id)
753
+ if mig.status in ("old_deleted", "copies_deleted", "closed") or c["old_left"] < c["copied"]:
754
+ raise UserError("Some originals are already deleted, so removing the copies would delete your content. Undo is not possible any more.")
755
+ await edit_callback_message(
756
+ event,
757
+ f"↩️ <b>Remove the {c['new_left']} copied message(s) from {esc(ch.title)}?</b>\nThe original posts stay as they are.",
758
+ [[Button.inline("↩️ Yes, remove the copies", f"rpuy:{mig.id}"), Button.inline("Back", f"rpb:{mig.id}")]],
759
+ )
760
+
761
+ @on_cb(ctx, "rpuy")
762
+ async def cb_undo(event, parts):
763
+ require_owner(ctx, event)
764
+ mig, ch = await load(parts)
765
+ c = await db.migration_counts(mig.id)
766
+ if mig.status in ("old_deleted", "copies_deleted", "closed") or c["old_left"] < c["copied"]:
767
+ raise UserError("Undo is not possible any more.")
768
+ if ctx.lock.locked():
769
+ raise UserError("A long job is already running.")
770
+ fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None)
771
+ back = CrossResult()
772
+ last = [0.0]
773
+
774
+ async def prog(c):
775
+ if time.monotonic() - last[0] < 4:
776
+ return
777
+ last[0] = time.monotonic()
778
+ try:
779
+ await edit_callback_message(event, progress_text(c, title="Pointing links back at the original posts"))
780
+ except Exception:
781
+ log.debug("progress update failed", exc_info=True)
782
+
783
+ try:
784
+ async with ctx.lock:
785
+ try: # links that were pointed at the copies would be left without a post: point them back first
786
+ await restore_after_undo(client, db, ch, mig, delay=cfg.edit_delay, progress=prog, result=back)
787
+ except Exception:
788
+ log.exception("pointing the links back at the original posts failed")
789
+ back.stopped = True
790
+ res = await delete_copies(client, db, ch, mig, "new", delay=0.5, fallback=fallback)
791
+ finally:
792
+ if deleter is not None:
793
+ await deleter.close()
794
+ link_notes = report_lines(back, back=True)
795
+ link_text = ("\n" + "\n".join(link_notes)) if link_notes else ""
796
+ if res.remaining == 0 and not res.error:
797
+ await db.set_migration_status(mig.id, "copies_deleted")
798
+ await edit_callback_message(
799
+ event,
800
+ f"↩️ Done. {res.deleted} copied message(s) removed; the original posts were not touched."
801
+ f"{userbot_lines(deleter)}{link_text}",
802
+ )
803
+ else:
804
+ why = esc(
805
+ delete_problem_text(
806
+ ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot
807
+ )
808
+ )
809
+ await edit_callback_message(
810
+ event,
811
+ f"⚠️ Removed {res.deleted}, {res.remaining} copy/copies are still there. {why}{link_text}",
812
+ [[Button.inline("πŸ” Try again", f"rpuy:{mig.id}")]],
813
+ )
814
+
815
+ @on_cb(ctx, "rpk")
816
+ async def cb_close(event, parts):
817
+ require_owner(ctx, event)
818
+ mig, _ = await load(parts)
819
+ await db.set_migration_status(mig.id, "closed")
820
+ await edit_callback_message(event, "βœ… Closed. Nothing else will be changed in that channel by this repost.")
app/handlers/shift.py ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/shift <source> <destination> [from_id] [to_id]: copy posts from one channel into another. Owner only."""
2
+ from __future__ import annotations
3
+
4
+ import logging
5
+ import re
6
+ import secrets
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from typing import Optional
10
+
11
+ from telethon import Button, errors
12
+
13
+ from ..channelref import ChannelRef, resolve_channel
14
+ from ..common import Ctx, UserError, cmd, edit_callback_message, guard, on_cb, purge_pending, require_owner, say
15
+ from ..crosslinks import CrossResult, progress_text, relink_after_shift, report_lines, restore_after_shift_undo
16
+ from ..profile_copy import profile_lines
17
+ from ..repost_engine import RepostOptions, RepostPlan, RepostResult, plan_repost, saved_lookup
18
+ from ..shift_engine import delete_shift_copies, plan_from_my_posts, run_shift, shift_profile, source_of
19
+ from ..tgutil import esc, explain_rpc, get_rights, post_link
20
+ from ..userbot import delete_problem_text
21
+ from .repost import finishing_notes, held_plan_lines, hidden_progress
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+ USAGE = (
26
+ "Usage: <code>/shift &lt;source&gt; &lt;destination&gt; [from_id] [to_id]</code>\n"
27
+ "Copies posts from one channel into another - text, formatting, media, albums, buttons, replies - and registers "
28
+ "the copies in My posts. The source is only read: nothing in it is changed or deleted.\n\n"
29
+ "A channel can be given as <code>@username</code>, a t.me link, its id (<code>-100…</code>) or an invite link "
30
+ "(the bot must be a member). The bot must be an admin of the destination (Post messages).\n\n"
31
+ "<code>/shift @source @destination</code> - every post\n"
32
+ "<code>/shift @source @destination 15 20</code> - only the posts with message ids 15 to 20\n"
33
+ "<code>/shift @source @destination 15</code> - only post 15\n\n"
34
+ "A channel that Telegram restricts (a copyright strike: β€œThis channel is unavailable due to copyright "
35
+ "infringement”, its posts shown as β€œThis message couldn't be displayed on your device due to copyright "
36
+ "infringement”) is copied from what My posts saved of it - every post that has a saved copy, however intact "
37
+ "Telegram's version looks. Telegram's notice is never copied. A post without a saved copy is copied as Telegram "
38
+ "hands it out if it is still the post itself, and skipped if only the notice is left.\n\n"
39
+ "Three extras, each optional, in any order, with or without a range:\n"
40
+ "<code>-c</code> - afterwards every link to a post of the source - in ANY of your connected channels - is pointed "
41
+ "at the copy in the destination\n"
42
+ "<code>-all</code> - afterwards the destination gets the source's name, description and profile photo\n"
43
+ "<code>--no-media</code> - no file is copied: every post goes out as its text with its formatting and buttons "
44
+ "(use it when Telegram hides the copies because of their files)\n"
45
+ "<code>/shift @source @destination -c -all</code> does the first two."
46
+ )
47
+
48
+
49
+ @dataclass
50
+ class ShiftFlags:
51
+ """The optional extras of /shift."""
52
+
53
+ links: bool = False # -c: links to the source's posts, in all connected channels, follow the copies
54
+ profile: bool = False # -all: the destination gets the source's name, description and profile photo
55
+ no_media: bool = False # --no-media: the copies get no files (text, formatting and buttons only)
56
+
57
+
58
+ @dataclass
59
+ class ShiftJob:
60
+ """A shift that was planned and is waiting for the owner's OK (or is running)."""
61
+
62
+ user: int
63
+ src: ChannelRef
64
+ dst: ChannelRef
65
+ plan: RepostPlan
66
+ already: int = 0 # posts of the range that an earlier shift copied into this destination
67
+ flags: ShiftFlags = field(default_factory=ShiftFlags)
68
+ running: bool = False
69
+ stop: bool = False
70
+ shift_id: str = ""
71
+ created: float = field(default_factory=time.monotonic)
72
+
73
+
74
+ _OPTION = re.compile(r"^[-\u2013\u2014]{1,2}([A-Za-z][A-Za-z0-9_-]*)$") # phone keyboards turn "--" into a long dash
75
+
76
+
77
+ def parse_shift_args(raw: str) -> tuple:
78
+ """-> (source text, destination text, first id or None, last id or None, ShiftFlags).
79
+
80
+ -c, -all and --no-media can stand anywhere, in any order ("- all" with a space is understood too, and so are
81
+ -nomedia and a long dash in place of --); a channel id such as -1001234567890 is not an option."""
82
+ text = re.sub(r"(?<!\S)([-\u2013\u2014]{1,2})\s+(all|c|no[-_]?media)(?!\S)", r"\1\2", raw or "", flags=re.I)
83
+ flags, toks = ShiftFlags(), []
84
+ for t in text.split():
85
+ m = _OPTION.match(t)
86
+ if m is None:
87
+ toks.append(t)
88
+ continue
89
+ name = re.sub(r"[-_]", "", m.group(1)).lower()
90
+ if name == "c":
91
+ flags.links = True
92
+ elif name == "all":
93
+ flags.profile = True
94
+ elif name == "nomedia":
95
+ flags.no_media = True
96
+ else:
97
+ raise ValueError(f"Unknown option {t}. The options are -c, -all and --no-media.")
98
+ if len(toks) < 2 or len(toks) > 4:
99
+ raise ValueError("Give the source and the destination channel, and optionally the first and the last message id.")
100
+ nums: list = []
101
+ for t in toks[2:]:
102
+ if not t.isdigit() or int(t) < 1:
103
+ raise ValueError(f"β€œ{t}” is not a message id. Message ids are positive numbers, for example 15 20.")
104
+ nums.append(int(t))
105
+ first = last = None
106
+ if len(nums) == 1:
107
+ first = last = nums[0]
108
+ elif len(nums) == 2:
109
+ first, last = min(nums), max(nums)
110
+ return toks[0], toks[1], first, last, flags
111
+
112
+
113
+ def plan_text(
114
+ p: RepostPlan, src: ChannelRef, dst: ChannelRef, already: int, delay: float, flags: Optional[ShiftFlags] = None,
115
+ others: int = 0, info_right: bool = True,
116
+ ) -> str:
117
+ kinds = f"{p.text} text, {p.media} media"
118
+ if p.polls:
119
+ kinds += f", {p.polls} poll(s)"
120
+ if p.other:
121
+ kinds += f", {p.other} other"
122
+ lines = [
123
+ "πŸ“¦ <b>Shift plan</b>",
124
+ f"From <b>{esc(src.title)}</b> β†’ <b>{esc(dst.title)}</b>",
125
+ f"Post ids {p.first}-{p.last}: <b>{p.units} posts</b> to copy ({p.messages} messages, {p.albums} album(s)) - {kinds}",
126
+ ]
127
+ if p.service:
128
+ lines.append(f"β€’ {p.service} service message(s) (like β€œpinned a message”) can't be copied and are skipped")
129
+ if p.polls:
130
+ lines.append("β€’ polls are copied without their votes")
131
+ if p.dropped_posts:
132
+ lines.append(f"β€’ {p.dropped_posts} post(s) carry other bots' buttons (reactions...) - those are not copied")
133
+ lines += held_plan_lines(p, src.title, shift=True)
134
+ if p.no_media:
135
+ note = "β€’ 🚫 <b>--no-media</b>: no file is copied - every post goes out as its text with its formatting and buttons"
136
+ if p.files_left_out:
137
+ note += f". {p.files_left_out} post(s) carry a file that stays out"
138
+ if p.file_only:
139
+ note += f"; {p.file_only} post(s) are only a file, so there is nothing to copy of them and they are skipped"
140
+ lines.append(note + ".")
141
+ if p.post_links:
142
+ lines.append(
143
+ f"β€’ {p.post_links} link(s) in {p.post_link_posts} post(s) point at other posts of {esc(src.title)}: those that "
144
+ "are shifted too will point at their copies"
145
+ )
146
+ if p.replies:
147
+ lines.append(f"β€’ {p.replies} post(s) answer another post: the copy answers the copy (if that post is shifted too)")
148
+ if already:
149
+ lines.append(
150
+ f"β€’ ⚠️ {already} of these posts were already shifted into {esc(dst.title)} before: they would be copied again"
151
+ )
152
+ flags = flags or ShiftFlags()
153
+ if p.from_db:
154
+ lines.insert(
155
+ 2,
156
+ f"⚠️ <b>I can't read {esc(src.title)}</b>: {esc(p.unreadable or 'Telegram refuses')}. My posts has the saved "
157
+ "posts of it, so they are copied from there.",
158
+ )
159
+ if flags.links:
160
+ where = f"your {others} other connected channel(s)" if others else "your connected channels"
161
+ lines.append(
162
+ f"β€’ πŸ”— <b>-c</b>: afterwards every link to a post of {esc(src.title)} - a hyperlink, a typed link or a "
163
+ f"button - in {where} is pointed at the copy in {esc(dst.title)} (links to posts that are not shifted stay "
164
+ f"as they are). {esc(src.title)} itself is not changed."
165
+ )
166
+ if flags.profile:
167
+ lines.append(
168
+ f"β€’ πŸ–Ό <b>-all</b>: afterwards {esc(dst.title)} gets the name, description and profile photo of "
169
+ f"{esc(src.title)}. Its own are replaced - undo does not bring them back. A part the source does not have "
170
+ "is left as it is."
171
+ )
172
+ if not info_right:
173
+ lines.append(
174
+ f"β€’ ⚠️ The bot does not have the β€œChange channel info” admin right in {esc(dst.title)} yet - give it "
175
+ "before the copying is finished, or use the β€œcopy again” button afterwards."
176
+ )
177
+ minutes = max(1, round(p.eta_seconds(delay) / 60))
178
+ if p.from_db:
179
+ what = "its text, formatting and buttons" if p.no_media else (
180
+ "its text, formatting, buttons and media (a file that Telegram refuses goes out without it)"
181
+ )
182
+ how = (
183
+ f"<b>How:</b> every post is posted again from what My posts saved of it - {what} - and every button is read "
184
+ "back to make sure it is there. Copies go to the end of the destination silently, in the original order, and "
185
+ "are registered in My posts."
186
+ )
187
+ kept = "<b>Not kept:</b> original dates, view counts, reactions, comments, poll votes, pins, replies and albums (every picture of an album becomes a post of its own)."
188
+ elif p.no_media:
189
+ how = (
190
+ "<b>How:</b> every post is posted again as its text with its formatting and buttons - no file is copied - and "
191
+ "every button is read back to make sure it is there. Copies go to the end of the destination silently, in the "
192
+ "original order, and are registered in My posts."
193
+ )
194
+ kept = "<b>Not kept:</b> the files, albums (a caption becomes a post of its own), original dates, view counts, reactions, comments, poll votes and pins."
195
+ elif p.channel_restricted:
196
+ how = (
197
+ "<b>How:</b> Telegram copies nothing out of a restricted channel, so every post is posted again - from what "
198
+ "My posts saved of it, or as Telegram hands it out when there is no saved copy - with its text, formatting, "
199
+ "media and buttons in one go, and every button is read back to make sure it is there. Copies go to the end of "
200
+ "the destination silently, in the original order, and are registered in My posts."
201
+ )
202
+ kept = "<b>Not kept:</b> original dates, view counts, reactions, comments, poll votes and pins."
203
+ else:
204
+ how = (
205
+ "<b>How:</b> posts are copied by Telegram itself where possible (exactly as they are); posts with buttons or "
206
+ "replies are posted again with their text, formatting, media and buttons in one go, and every button is read "
207
+ "back to make sure it is there. Copies go to the end of the destination silently, in the original order, and "
208
+ "are registered in My posts."
209
+ )
210
+ if p.held_saved or p.live_restricted:
211
+ how += " Posts that Telegram restricts are never copied by Telegram itself: they are posted again."
212
+ kept = "<b>Not kept:</b> original dates, view counts, reactions, comments, poll votes and pins."
213
+ lines += [
214
+ "",
215
+ how,
216
+ "",
217
+ kept,
218
+ f"Time: about {minutes} min. <b>Nothing is changed in {esc(src.title)}.</b>",
219
+ ]
220
+ return "\n".join(lines)
221
+
222
+
223
+ def register(ctx: Ctx) -> None:
224
+ client, db, cfg = ctx.client, ctx.db, ctx.cfg
225
+
226
+ # ---------------------------------------------------------------- views
227
+ async def view_for(sh):
228
+ """Text and buttons describing where a shift stands."""
229
+ dst = await db.get_channel(sh.dst_channel_id)
230
+ c = await db.shift_counts(sh.id)
231
+ src_name = esc(sh.src_title or str(sh.src_channel_id))
232
+ dst_name = esc(dst.title) if dst else str(sh.dst_channel_id)
233
+ route = f"<b>{src_name}</b> β†’ <b>{dst_name}</b>"
234
+ first_copy = ""
235
+ if dst and c["first_new"]:
236
+ first_copy = f'\n<a href="{post_link(dst, c["first_new"])}">First copy</a>'
237
+ undo = [Button.inline("↩️ Undo - remove the copies", f"sfu:{sh.id}")]
238
+ marks = await db.marks_of(sh.id)
239
+ if "nomedia" in marks:
240
+ route += " (without files)"
241
+ extras = []
242
+ if "relink" in marks:
243
+ extras.append([Button.inline("πŸ”— Update links again", f"sfl:{sh.id}")])
244
+ if "profile" in marks and "profile_done" not in marks:
245
+ extras.append([Button.inline("πŸ–Ό Copy name, description, photo again", f"sfp:{sh.id}")])
246
+ if sh.status == "copied":
247
+ text = (
248
+ f"βœ… {route}: <b>{c['copied']} message(s) copied</b> (source ids {sh.first_id}-{sh.last_id}) and "
249
+ f"registered in My posts.{first_copy}\nThe source was not changed. Look at the end of the destination; "
250
+ "if something is wrong, undo removes just these copies."
251
+ )
252
+ kb = extras + [undo]
253
+ elif sh.status == "copies_deleted":
254
+ text = f"↩️ {route}: the copies were removed again."
255
+ kb = []
256
+ elif sh.status == "stopped":
257
+ text = f"⏹ {route}: <b>stopped</b>. {c['copied']} message(s) copied so far.{first_copy}"
258
+ go = "▢️ Continue anyway" if "hiddenok" in marks else "▢️ Continue"
259
+ kb = [[Button.inline(go, f"sfc:{sh.id}")], undo]
260
+ elif sh.status == "copying":
261
+ text = f"⏳ {route}: a shift was running when the bot stopped. {c['copied']} message(s) copied.{first_copy}"
262
+ kb = [[Button.inline("▢️ Continue", f"sfc:{sh.id}")], undo]
263
+ else: # incomplete
264
+ text = (
265
+ f"⚠️ {route}: <b>not everything was copied</b>. {c['copied']} message(s) copied.{first_copy}\n"
266
+ "Nothing was changed in the source."
267
+ )
268
+ kb = [[Button.inline("πŸ” Try the rest again", f"sfc:{sh.id}")], undo]
269
+ return text, kb
270
+
271
+ # --------------------------------------------------------------- /shift
272
+ @client.on(cmd("shift", args=True))
273
+ @guard(ctx, owner=True)
274
+ async def h_shift(event):
275
+ purge_pending(ctx)
276
+ raw = (event.pattern_match.group(1) or "").strip()
277
+ if not raw:
278
+ sh = await db.open_shift()
279
+ if sh is not None:
280
+ text, kb = await view_for(sh)
281
+ await say(event, "Unfinished shift:\n\n" + text, kb)
282
+ return
283
+ await say(event, USAGE)
284
+ # a finished shift keeps its Undo: offer it again, so it can be found without scrolling up to its old message
285
+ last = await db.last_finished_shift()
286
+ if last is not None:
287
+ text, kb = await view_for(last)
288
+ await say(event, "Latest finished shift - you can still undo it:\n\n" + text, kb)
289
+ return
290
+ try:
291
+ src_text, dst_text, first, last, flags = parse_shift_args(raw)
292
+ except ValueError as e:
293
+ raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE).replace("&lt;", "<").replace("&gt;", ">"))
294
+ src = await resolve_channel(ctx, src_text)
295
+ dst = await resolve_channel(ctx, dst_text)
296
+ if src.id == dst.id:
297
+ raise UserError("The source and the destination are the same channel. To rebuild one channel in order, use /repost.")
298
+ sh = await db.open_shift(src.id, dst.id)
299
+ if sh is not None:
300
+ text, kb = await view_for(sh)
301
+ await say(event, "There is an unfinished shift between these two channels. Finish or undo it first.\n\n" + text, kb)
302
+ return
303
+ rights = await get_rights(client, dst)
304
+ if rights is not None and not (rights.admin and rights.post):
305
+ raise UserError(f"The bot needs the β€œPost messages” admin right in {dst.title}.")
306
+ if ctx.lock.locked():
307
+ raise UserError("Another long job (replace / repost / shift) is still running.")
308
+ note = await say(event, f"πŸ” Reading <b>{esc(src.title)}</b>…")
309
+ last_edit = [0.0]
310
+
311
+ async def prog(p):
312
+ if time.monotonic() - last_edit[0] < 3:
313
+ return
314
+ last_edit[0] = time.monotonic()
315
+ try:
316
+ await note.edit(f"πŸ” Reading <b>{esc(src.title)}</b>: post id {p.scanned}…")
317
+ except Exception:
318
+ pass
319
+
320
+ try:
321
+ async with ctx.lock:
322
+ plan = await plan_repost(
323
+ client, src, RepostOptions(), progress=prog, first_id=first, last_id=last,
324
+ saved=saved_lookup(db, src.id), use_saved=True, no_media=flags.no_media,
325
+ )
326
+ except errors.RPCError as e:
327
+ why = explain_rpc(e)
328
+ # a channel that can't be read any more (banned, private ...) may still be in My posts: copy it from there
329
+ plan = await plan_from_my_posts(db, src, first, last, unreadable=why, no_media=flags.no_media)
330
+ if plan is None:
331
+ raise UserError(
332
+ f"I can't read {src.title}: {why}\nThe bot has to be a member of the source channel "
333
+ "(an admin is best; it only reads). My posts has no saved posts of it to copy from instead."
334
+ )
335
+ if plan.error:
336
+ await note.edit(f"⚠️ {esc(plan.error)}")
337
+ return
338
+ already = len(await db.shifted_ids(src.id, dst.id, plan.first, plan.last))
339
+ others = 0
340
+ if flags.links: # the channels the links are looked for in: all connected ones, the source itself excluded
341
+ known = {c.id for c in await db.list_channels()} | {dst.id}
342
+ others = len(known - {src.id})
343
+ info_right = rights is None or bool(getattr(rights, "change_info", True))
344
+ token = secrets.token_hex(4)
345
+ ctx.pending[token] = ShiftJob(user=event.sender_id, src=src, dst=dst, plan=plan, already=already, flags=flags)
346
+ kb = [[Button.inline("▢️ Start copying", f"sfa:{token}"), Button.inline("βœ–οΈ Cancel", f"sfn:{token}")]]
347
+ await note.edit(plan_text(plan, src, dst, already, cfg.edit_delay, flags, others, info_right), buttons=kb)
348
+
349
+ @on_cb(ctx, "sfn")
350
+ async def cb_cancel(event, parts):
351
+ require_owner(ctx, event)
352
+ ctx.pending.pop(parts[0], None)
353
+ await edit_callback_message(event, "Cancelled - nothing was copied.")
354
+
355
+ # ------------------------------------------------------------------ copy
356
+ async def run_copy(event, sid: str, job: Optional[ShiftJob] = None) -> None:
357
+ sh = await db.get_shift(sid)
358
+ dst = await db.get_channel(sh.dst_channel_id)
359
+ if dst is None:
360
+ raise UserError("The destination channel is not registered any more.")
361
+ job = job or ShiftJob(user=event.sender_id, src=None, dst=None, plan=None) # type: ignore[arg-type]
362
+ job.running, job.stop, job.shift_id = True, False, sid
363
+ ctx.pending[f"job:{sid}"] = job
364
+ total = job.plan.units if job.plan else None
365
+ last = [0.0]
366
+ names = f"<b>{esc(sh.src_title)}</b> β†’ <b>{esc(dst.title)}</b>"
367
+
368
+ async def prog(res):
369
+ if res.phase in ("copy", "links") and time.monotonic() - last[0] < 4:
370
+ return
371
+ last[0] = time.monotonic()
372
+ done = res.copied_units + res.skipped_done
373
+ of = f"/{total}" if total else ""
374
+ if res.phase == "links" and res.cross is not None:
375
+ body = f"βœ… Copied {done}{of} posts.\n" + progress_text(res.cross, title="Pointing links of your channels at the copies")
376
+ elif res.phase == "profile":
377
+ body = f"πŸ–Ό Copied {done}{of} posts. Now copying the name, description and photo of {esc(sh.src_title)}…"
378
+ elif res.phase == "finish":
379
+ body = f"πŸ”— Copied {done}{of} posts. Now pointing links at the new copies…"
380
+ else:
381
+ body = f"⏳ Shifting {names}: {done}{of} posts…\nThe source stays untouched."
382
+ body += hidden_progress(res)
383
+ try:
384
+ await edit_callback_message(event, body, [[Button.inline("⏹ Stop", f"sfs:{sid}")]])
385
+ except errors.MessageNotModifiedError:
386
+ pass
387
+ except Exception:
388
+ log.debug("progress update failed", exc_info=True)
389
+
390
+ try:
391
+ async with ctx.lock:
392
+ await db.set_shift_status(sid, "copying")
393
+ res = await run_shift(
394
+ client, db, sh, dst, event.sender_id, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop
395
+ )
396
+ finally:
397
+ job.running = False
398
+ status = "stopped" if res.stopped else ("incomplete" if (res.failed or res.aborted or res.held_back) else "copied")
399
+ await db.set_shift_status(sid, status)
400
+ if res.hidden_stop: # stopped because Telegram hides the copies: pressing Continue means "go on anyway"
401
+ await db.set_mark(sid, "hiddenok")
402
+ sh = await db.get_shift(sid)
403
+ text, kb = await view_for(sh)
404
+ notes = []
405
+ if res.copied_units:
406
+ notes.append(f"{res.forwarded} post(s) were copied by Telegram, {res.rebuilt} were posted again with their buttons.")
407
+ if res.repaired:
408
+ notes.append(f"{res.repaired} post(s) needed their buttons set again after posting - they show them now.")
409
+ if res.failed:
410
+ sample = ", ".join(f"#{i} {esc(n)}" for i, n in res.failed[:6])
411
+ notes.append(f"<b>{len(res.failed)} post(s) failed</b> ({sample}{'…' if len(res.failed) > 6 else ''}).")
412
+ if any(n == "ButtonsNotShown" for _, n in res.failed):
413
+ notes.append(
414
+ "ButtonsNotShown: Telegram did not show the buttons on the new post, so that copy was removed again. "
415
+ "The original is untouched - use β€œTry the rest again”."
416
+ )
417
+ if any(n == "ReplyParentMissing" for _, n in res.failed):
418
+ notes.append("ReplyParentMissing: that post answers a post whose copy failed; it follows when you try again.")
419
+ if res.aborted:
420
+ notes.append(f"Stopped early because of {esc(res.aborted)}.")
421
+ notes += finishing_notes(res, shift=True)
422
+ await edit_callback_message(event, text + ("\n\n" + "\n".join(notes) if notes else ""), kb)
423
+
424
+ @on_cb(ctx, "sfa")
425
+ async def cb_start(event, parts):
426
+ require_owner(ctx, event)
427
+ job = ctx.pending.get(parts[0])
428
+ if not isinstance(job, ShiftJob) or job.user != event.sender_id:
429
+ raise UserError("That plan has expired. Run /shift again.")
430
+ if job.running or ctx.lock.locked():
431
+ raise UserError("A long job is already running.")
432
+ if await db.open_shift(job.src.id, job.dst.id) is not None:
433
+ raise UserError("There is already an unfinished shift between these two channels.")
434
+ rights = await get_rights(client, job.dst)
435
+ if rights is not None and not (rights.admin and rights.post):
436
+ raise UserError(f"The bot needs the β€œPost messages” admin right in {job.dst.title}.")
437
+ # the copies are registered in My posts, so the destination has to be one of the bot's channels
438
+ await db.save_channel(job.dst.id, job.dst.access_hash, job.dst.title, job.dst.username, event.sender_id)
439
+ sid = secrets.token_hex(6)
440
+ p = job.plan
441
+ await db.create_shift(sid, src=job.src, dst_channel_id=job.dst.id, first_id=p.first, last_id=p.last, user_id=event.sender_id)
442
+ if job.flags.links:
443
+ await db.set_mark(sid, "relink")
444
+ if job.flags.profile:
445
+ await db.set_mark(sid, "profile")
446
+ if job.flags.no_media: # continuing the shift later goes on without files as well
447
+ await db.set_mark(sid, "nomedia")
448
+ if p.from_db: # the source can't be read: continuing the shift goes on from My posts as well
449
+ await db.set_mark(sid, "fromdb")
450
+ ctx.pending.pop(parts[0], None)
451
+ await run_copy(event, sid, job)
452
+
453
+ @on_cb(ctx, "sfc")
454
+ async def cb_continue(event, parts):
455
+ require_owner(ctx, event)
456
+ sh = await db.get_shift(parts[0])
457
+ if sh is None or sh.status not in ("stopped", "incomplete", "copying"):
458
+ raise UserError("There is nothing to continue.")
459
+ if ctx.lock.locked():
460
+ raise UserError("A long job is already running.")
461
+ await run_copy(event, sh.id)
462
+
463
+ @on_cb(ctx, "sfs")
464
+ async def cb_stop(event, parts):
465
+ require_owner(ctx, event)
466
+ job = ctx.pending.get(f"job:{parts[0]}")
467
+ if isinstance(job, ShiftJob) and job.running:
468
+ job.stop = True
469
+ await event.respond("⏹ Stopping after the post that is being worked on…")
470
+ else:
471
+ await event.respond("Nothing is running.")
472
+
473
+ # ------------------------------------------------------------ the extras again
474
+ @on_cb(ctx, "sfl")
475
+ async def cb_links(event, parts):
476
+ """-c once more: look through every connected channel for links to the source's posts."""
477
+ require_owner(ctx, event)
478
+ sh, dst = await load(parts)
479
+ if sh.status != "copied":
480
+ raise UserError("Links can be updated once everything is copied.")
481
+ if ctx.lock.locked():
482
+ raise UserError("A long job is already running.")
483
+ job = ShiftJob(user=event.sender_id, src=None, dst=None, plan=None, running=True, shift_id=sh.id) # type: ignore[arg-type]
484
+ ctx.pending[f"job:{sh.id}"] = job
485
+ cross, last = CrossResult(), [0.0]
486
+
487
+ async def prog(c):
488
+ if time.monotonic() - last[0] < 4:
489
+ return
490
+ last[0] = time.monotonic()
491
+ try:
492
+ await edit_callback_message(
493
+ event, progress_text(c, title="Pointing links at the copies"), [[Button.inline("⏹ Stop", f"sfs:{sh.id}")]]
494
+ )
495
+ except errors.MessageNotModifiedError:
496
+ pass
497
+ except Exception:
498
+ log.debug("progress update failed", exc_info=True)
499
+
500
+ error = None
501
+ try:
502
+ async with ctx.lock:
503
+ await edit_callback_message(event, "πŸ”— Looking for links to the source's posts in your channels…")
504
+ await relink_after_shift(
505
+ client, db, sh, source_of(sh), dst, delay=cfg.edit_delay, progress=prog,
506
+ should_stop=lambda: job.stop, result=cross,
507
+ )
508
+ except Exception as e: # the copies are fine; only the links were not (all) updated
509
+ log.exception("pointing the links at the shifted posts failed")
510
+ error = type(e).__name__
511
+ finally:
512
+ job.running = False
513
+ ctx.pending.pop(f"job:{sh.id}", None)
514
+ notes = report_lines(cross, what=f"the copies in {esc(dst.title)}")
515
+ if error:
516
+ notes.append(f"Links could not be updated ({esc(error)}).")
517
+ if not notes:
518
+ notes.append("πŸ”— There is nothing to change.")
519
+ text, kb = await view_for(sh)
520
+ await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb)
521
+
522
+ @on_cb(ctx, "sfp")
523
+ async def cb_profile(event, parts):
524
+ """-all once more: the name, description and photo of the source."""
525
+ require_owner(ctx, event)
526
+ sh, dst = await load(parts)
527
+ if "profile" not in await db.marks_of(sh.id):
528
+ raise UserError("This shift was not started with -all.")
529
+ if sh.status not in ("copied", "stopped", "incomplete"):
530
+ raise UserError("There is nothing to copy it to any more.")
531
+ if ctx.lock.locked():
532
+ raise UserError("A long job is already running.")
533
+ holder = RepostResult()
534
+ async with ctx.lock:
535
+ await edit_callback_message(event, f"πŸ–Ό Copying the name, description and photo of {esc(sh.src_title)}…")
536
+ await shift_profile(client, db, sh, dst, event.sender_id, holder)
537
+ dst = await db.get_channel(sh.dst_channel_id) or dst # it may have a new name now
538
+ notes = profile_lines(holder.profile, dst.title) if holder.profile is not None else []
539
+ if holder.profile_error:
540
+ notes.append(f"The name, description and photo could not be copied ({esc(holder.profile_error)}).")
541
+ text, kb = await view_for(sh)
542
+ await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb)
543
+
544
+ # ------------------------------------------------------------------ undo
545
+ async def load(parts):
546
+ sh = await db.get_shift(parts[0])
547
+ if sh is None:
548
+ raise UserError("I don't know that shift any more.")
549
+ dst = await db.get_channel(sh.dst_channel_id)
550
+ if dst is None:
551
+ raise UserError("The destination channel is not registered any more.")
552
+ return sh, dst
553
+
554
+ @on_cb(ctx, "sfb")
555
+ async def cb_back(event, parts):
556
+ sh, _ = await load(parts)
557
+ text, kb = await view_for(sh)
558
+ await edit_callback_message(event, text, kb)
559
+
560
+ @on_cb(ctx, "sfu")
561
+ async def cb_undo_ask(event, parts):
562
+ require_owner(ctx, event)
563
+ sh, dst = await load(parts)
564
+ c = await db.shift_counts(sh.id)
565
+ if not c["new_left"]:
566
+ raise UserError("There is nothing to remove.")
567
+ await edit_callback_message(
568
+ event,
569
+ f"↩️ <b>Remove the {c['new_left']} copied message(s) from {esc(dst.title)}?</b>\n"
570
+ f"The posts in {esc(sh.src_title)} are not touched.",
571
+ [[Button.inline("↩️ Yes, remove the copies", f"sfuy:{sh.id}"), Button.inline("Back", f"sfb:{sh.id}")]],
572
+ )
573
+
574
+ @on_cb(ctx, "sfuy")
575
+ async def cb_undo(event, parts):
576
+ require_owner(ctx, event)
577
+ sh, dst = await load(parts)
578
+ if ctx.lock.locked():
579
+ raise UserError("A long job is already running.")
580
+ fallback, deleter = await ctx.userbot.fallback_for(dst) if ctx.userbot is not None else (None, None)
581
+ back, last = CrossResult(), [0.0]
582
+
583
+ async def prog(c):
584
+ if time.monotonic() - last[0] < 4:
585
+ return
586
+ last[0] = time.monotonic()
587
+ try:
588
+ await edit_callback_message(event, progress_text(c, title="Pointing links back at the source's posts"))
589
+ except Exception:
590
+ log.debug("progress update failed", exc_info=True)
591
+
592
+ try:
593
+ async with ctx.lock:
594
+ try: # links that were pointed at the copies would be left without a post: point them back first
595
+ await restore_after_shift_undo(client, db, sh, source_of(sh), dst, delay=cfg.edit_delay, progress=prog, result=back)
596
+ except Exception:
597
+ log.exception("pointing the links back at the source's posts failed")
598
+ back.stopped = True
599
+ res = await delete_shift_copies(client, db, dst, sh, delay=0.5, fallback=fallback)
600
+ finally:
601
+ if deleter is not None:
602
+ await deleter.close()
603
+ link_notes = report_lines(back, back=True)
604
+ link_text = ("\n" + "\n".join(link_notes)) if link_notes else ""
605
+ if res.remaining == 0 and not res.error:
606
+ await db.set_shift_status(sh.id, "copies_deleted")
607
+ await edit_callback_message(
608
+ event,
609
+ f"↩️ Done. {res.deleted} copied message(s) removed from {esc(dst.title)}; the source was not touched.{link_text}",
610
+ )
611
+ else:
612
+ why = esc(delete_problem_text(ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot))
613
+ await edit_callback_message(
614
+ event,
615
+ f"⚠️ Removed {res.deleted}, {res.remaining} copy/copies are still there. {why}{link_text}",
616
+ [[Button.inline("πŸ” Try again", f"sfuy:{sh.id}")]],
617
+ )
618
+
app/handlers/sync.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/sync (owner only) and the live watch over the channels.
2
+
3
+ The live part listens to Telegram's updates: a post deleted, edited or added in a connected channel is recorded in My
4
+ posts a few seconds later, and service messages ("pinned a message", "channel photo changed" ...) are deleted at once.
5
+ The same comparison runs on a timer for everything the bot was not there to see (SYNC_INTERVAL_MINUTES).
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import re
11
+ import time
12
+ from typing import Optional
13
+
14
+ from telethon import events, types
15
+
16
+ from ..common import Ctx, UserError, cmd, guard, say
17
+ from ..sync_engine import SyncReport
18
+ from ..syncer import Syncer
19
+ from ..tgutil import esc
20
+ from .replace import pick_channels
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+ USAGE = (
25
+ "Usage: <code>/sync</code>\n"
26
+ "Compares every channel with My posts right now: posts that were deleted or edited in the channel by someone else "
27
+ "are updated here (a post deleted in the channel leaves My posts), new posts that were not made with this bot are "
28
+ "added, and service messages (β€œpinned a message”, β€œchannel photo changed” ...) that appeared meanwhile are deleted. "
29
+ "The posts that were in a channel before the bot was added are read into My posts too (a long channel takes a few "
30
+ "checks; <code>/sync</code> goes on where the last one stopped).\n"
31
+ "Options: <code>--channel @name</code> (only that channel), <code>--history</code> (read the channel's older posts "
32
+ "again and add the ones that are missing; posts you made the bot forget stay forgotten)."
33
+ )
34
+
35
+
36
+ def parse_sync_args(raw: str) -> tuple:
37
+ """(channel reference or None for every channel, read the older posts again) - ValueError for anything else."""
38
+ toks = (raw or "").split()
39
+ ref: Optional[str] = None
40
+ history = False
41
+ i = 0
42
+ while i < len(toks):
43
+ t = toks[i]
44
+ if t == "--channel" and i + 1 < len(toks):
45
+ ref = toks[i + 1]
46
+ i += 2
47
+ elif t == "--history":
48
+ history = True
49
+ i += 1
50
+ else:
51
+ raise ValueError(f"I don't know β€œ{t}”.")
52
+ return ref, history
53
+
54
+
55
+ def ids_text(ids, limit: int = 8) -> str:
56
+ ids = sorted(ids)
57
+ shown = ", ".join(str(i) for i in ids[:limit])
58
+ return shown + (f" and {len(ids) - limit} more" if len(ids) > limit else "")
59
+
60
+
61
+ def channel_block(rep: SyncReport) -> str:
62
+ lines = [f"<b>{esc(rep.channel.title)}</b>"]
63
+ if rep.error:
64
+ return "\n".join(lines + [f"⚠️ {esc(rep.error)}"])
65
+ if rep.restricted_channel:
66
+ return "\n".join(
67
+ lines
68
+ + [
69
+ f"🚫 Telegram has restricted this channel ({esc(rep.restricted_channel)}). Nothing was changed in My posts - "
70
+ "the saved posts stay exactly as they are, whatever the channel shows now."
71
+ ]
72
+ )
73
+ nothing = True
74
+ if rep.first_look:
75
+ lines.append("πŸ‘€ First look at this channel. From now on, posts made, edited or deleted outside this bot are recorded here.")
76
+ if rep.checked:
77
+ lines.append(f"βœ“ {rep.checked} saved post(s) compared with the channel")
78
+ if rep.deleted:
79
+ nothing = False
80
+ lines.append(f"πŸ—‘ {len(rep.deleted)} deleted in the channel β†’ removed from My posts (message {ids_text(rep.deleted)})")
81
+ if rep.edited:
82
+ nothing = False
83
+ lines.append(f"✏️ {len(rep.edited)} edited in the channel β†’ updated in My posts (message {ids_text(rep.edited)})")
84
+ if rep.adopted:
85
+ nothing = False
86
+ lines.append(f"βž• {len(rep.adopted)} new post(s) made outside the bot β†’ added to My posts (message {ids_text(rep.adopted)})")
87
+ if rep.history_top:
88
+ if rep.imported:
89
+ nothing = False
90
+ skipped = f" ({rep.history_unsupported} of a kind My posts can't hold - poll, sticker ... - skipped)" if rep.history_unsupported else ""
91
+ if rep.history_done:
92
+ if rep.imported:
93
+ lines.append(f"πŸ“₯ {rep.imported} older post(s), sent before the bot was added β†’ added to My posts{skipped}")
94
+ else:
95
+ lines.append(f"πŸ“₯ The older posts were looked through: nothing to add{skipped}")
96
+ else:
97
+ lines.append(
98
+ f"πŸ“₯ Older posts: {rep.imported} added so far, read up to message {rep.history_to} of {rep.history_top}{skipped} - "
99
+ "the next check goes on, or send /sync again to go on right away"
100
+ )
101
+ if rep.restricted:
102
+ nothing = False
103
+ lines.append(
104
+ f"🚫 {len(rep.restricted)} post(s) are held back by Telegram ({esc(rep.restricted_why or 'restricted')}) - "
105
+ f"left exactly as saved in My posts (message {ids_text(rep.restricted)})"
106
+ )
107
+ if rep.refreshed:
108
+ lines.append(f"β€’ {rep.refreshed} saved post(s) tidied up (spaces at the ends of the text)")
109
+ if rep.services_deleted:
110
+ nothing = False
111
+ lines.append(f"🧹 {rep.services_deleted} service message(s) deleted")
112
+ if rep.services_failed:
113
+ nothing = False
114
+ lines.append(
115
+ f"⚠️ {rep.services_failed} service message(s) could not be deleted ({esc(rep.services_error or 'refused')}) - "
116
+ "the bot needs the β€œDelete messages” right, and Telegram lets bots delete only recent messages"
117
+ )
118
+ if rep.buttons_missing:
119
+ nothing = False
120
+ lines.append(
121
+ f"⚠️ {len(rep.buttons_missing)} saved post(s) show no buttons in the channel (message {ids_text(rep.buttons_missing)}). "
122
+ "The saved buttons were kept: /posts β†’ the channel β†’ πŸ”§ Check buttons puts them back"
123
+ )
124
+ if rep.unsupported:
125
+ lines.append(f"β€’ {rep.unsupported} new message(s) of a kind My posts can't hold (poll, sticker ...) were left alone")
126
+ fresh = len(rep.young) + len(rep.young_new)
127
+ if fresh:
128
+ lines.append(f"⏳ {fresh} too fresh to judge - the next check will see them")
129
+ if rep.changed_meanwhile:
130
+ lines.append(f"β€’ {rep.changed_meanwhile} saved post(s) were changed through the bot meanwhile - left as they are")
131
+ if rep.anomaly:
132
+ nothing = False
133
+ lines.append(f"⚠️ {esc(rep.anomaly)}")
134
+ if rep.busy:
135
+ lines.append("⏸ A long job started, so this check stopped early.")
136
+ if nothing and not rep.busy and not rep.first_look:
137
+ lines.append("Everything matches.")
138
+ return "\n".join(lines)
139
+
140
+
141
+ def report_text(reports: list) -> str:
142
+ head = "πŸ”„ <b>Sync finished</b>"
143
+ if not reports:
144
+ return head + "\nNothing to look at."
145
+ return head + "\n\n" + "\n\n".join(channel_block(r) for r in reports)
146
+
147
+
148
+ def channel_id_of(msg) -> Optional[int]:
149
+ peer = getattr(msg, "peer_id", None)
150
+ return peer.channel_id if isinstance(peer, types.PeerChannel) else None
151
+
152
+
153
+ def register(ctx: Ctx) -> None:
154
+ client, db = ctx.client, ctx.db
155
+ if ctx.syncer is None:
156
+ ctx.syncer = Syncer(ctx)
157
+ sy = ctx.syncer
158
+
159
+ # ----------------------------------------------------------------------------------------- /sync
160
+ @client.on(cmd("sync", args=True))
161
+ @guard(ctx, owner=True)
162
+ async def h_sync(event):
163
+ raw = (event.pattern_match.group(1) or "").strip()
164
+ try:
165
+ ref, history = parse_sync_args(raw)
166
+ chans = pick_channels(await db.list_channels(), ref)
167
+ except ValueError as e:
168
+ raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE))
169
+ if not chans:
170
+ raise UserError("No channels registered yet. Use /addchannel.")
171
+ if ctx.lock.locked():
172
+ raise UserError("Another long job (replace, repost, shift ...) is still running - try again when it has finished.")
173
+ async with ctx.lock:
174
+ if history:
175
+ for ch in chans:
176
+ await db.reset_history(ch.id)
177
+ status = await say(event, f"πŸ”„ Looking at {len(chans)} channel(s)…")
178
+ last = [0.0]
179
+
180
+ async def prog(ch, rep) -> None:
181
+ now = time.monotonic()
182
+ if now - last[0] < 3:
183
+ return
184
+ last[0] = now
185
+ try:
186
+ await status.edit(f"πŸ”„ <b>{esc(ch.title)}</b>: {rep.phase} (message {rep.scanned_to})…")
187
+ except Exception:
188
+ pass
189
+
190
+ reports = await sy.run_all(chans, explicit=True, history=True if history else None, progress=prog)
191
+ await say(event, report_text(reports))
192
+
193
+ # ------------------------------------------------------------------- what Telegram tells while we run
194
+ @client.on(events.Raw(types.UpdateNewChannelMessage))
195
+ async def on_channel_message(update):
196
+ try:
197
+ m = update.message
198
+ cid = channel_id_of(m)
199
+ if cid is None:
200
+ return
201
+ if isinstance(m, types.MessageService):
202
+ await sy.on_service(cid, m)
203
+ elif not isinstance(m, types.MessageEmpty):
204
+ sy.note_new(cid, m)
205
+ except Exception:
206
+ log.warning("could not handle a new channel message", exc_info=True)
207
+
208
+ @client.on(events.Raw(types.UpdateEditChannelMessage))
209
+ async def on_channel_edit(update):
210
+ try:
211
+ m = update.message
212
+ cid = channel_id_of(m)
213
+ if cid is not None and not isinstance(m, (types.MessageService, types.MessageEmpty)):
214
+ sy.note_edit(cid, m)
215
+ except Exception:
216
+ log.warning("could not handle an edited channel message", exc_info=True)
217
+
218
+ @client.on(events.Raw(types.UpdateDeleteChannelMessages))
219
+ async def on_channel_delete(update):
220
+ try:
221
+ await sy.note_deleted(update.channel_id, list(update.messages))
222
+ except Exception:
223
+ log.warning("could not handle deleted channel messages", exc_info=True)
app/handleswap.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/handleswap: change a username written in a post - "@bro" -> "@sis" - and nothing else.
2
+
3
+ Only usernames are touched: the words "@bro" in the text or caption (and in button names). Links, hyperlinks and the
4
+ links behind buttons are left exactly as they are, and so is "@bro" when it is part of a link or an e-mail address.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import re
10
+ from typing import Optional
11
+
12
+ from telethon import types
13
+ from telethon.helpers import add_surrogate, del_surrogate
14
+
15
+ from .linkswap import MsgChange, apply_span_replacements
16
+ from .richmsg import is_rich_message
17
+ from .tgutil import button_url, is_callback_button, with_text
18
+
19
+ # a "@name" that follows one of these is part of something else: an e-mail (a@bro), a link (t.me/x@bro, ?u=@bro) ...
20
+ _NOT_BEFORE = r"\w@./=?&#%"
21
+ _PROTECTED = tuple(
22
+ getattr(types, n) for n in ("MessageEntityUrl", "MessageEntityTextUrl", "MessageEntityEmail") if hasattr(types, n)
23
+ )
24
+
25
+
26
+ def mention_regex(name: str):
27
+ """'@name' as a whole word (case does not matter): not '@name_bot', not 'x@name'."""
28
+ return re.compile(rf"(?<![{_NOT_BEFORE}])@{re.escape(name)}(?![A-Za-z0-9_])", re.I)
29
+
30
+
31
+ def find_mention_spans(sur: str, entities, name: str) -> tuple:
32
+ """([(start, end)], skipped) - where '@name' stands in `sur` (UTF-16 units). Mentions that sit inside a link or a
33
+ hyperlink are not changed; `skipped` counts them."""
34
+ guarded = [(e.offset, e.offset + e.length) for e in entities or [] if isinstance(e, _PROTECTED)]
35
+ spans, skipped = [], 0
36
+ for m in mention_regex(name).finditer(sur):
37
+ s, e = m.span()
38
+ if any(gs < e and s < ge for gs, ge in guarded):
39
+ skipped += 1
40
+ continue
41
+ spans.append((s, e))
42
+ return spans, skipped
43
+
44
+
45
+ def compute_handle_changes(msg, old: str, new: str) -> tuple:
46
+ """(MsgChange or None, number of mentions skipped because they are part of a link) - same shape as
47
+ linkswap.compute_message_changes, so the /swap engine can apply it."""
48
+ rich = is_rich_message(msg) # the text of a rich message is blocks: only its buttons are changed
49
+ text = "" if rich else (msg.message or "")
50
+ ents = [] if rich else list(msg.entities or [])
51
+ sur = add_surrogate(text)
52
+ spans, skipped = find_mention_spans(sur, ents, old) if text else ([], 0)
53
+ new_sur, new_ents = sur, [copy.copy(e) for e in ents]
54
+ if spans:
55
+ new_sur, new_ents = apply_span_replacements(sur, ents, [(s, e, "@" + new) for s, e in spans])
56
+
57
+ # the names on link buttons (their links stay)
58
+ new_markup: Optional[types.ReplyInlineMarkup] = None
59
+ n_btn, has_cb = 0, False
60
+ mk = msg.reply_markup
61
+ if isinstance(mk, types.ReplyInlineMarkup):
62
+ rx = mention_regex(old)
63
+ rows = []
64
+ for row in mk.rows:
65
+ btns = []
66
+ for b in row.buttons:
67
+ if button_url(b) is not None:
68
+ label, n = rx.subn("@" + new, getattr(b, "text", "") or "")
69
+ if n:
70
+ btns.append(with_text(b, label))
71
+ n_btn += n
72
+ continue
73
+ elif is_callback_button(b):
74
+ has_cb = True
75
+ btns.append(b)
76
+ rows.append(types.KeyboardButtonRow(btns))
77
+ if n_btn:
78
+ new_markup = types.ReplyInlineMarkup(rows)
79
+
80
+ if not (spans or n_btn):
81
+ return None, skipped
82
+ return (
83
+ MsgChange(
84
+ message_id=msg.id,
85
+ new_text=del_surrogate(new_sur),
86
+ new_entities=new_ents,
87
+ new_markup=new_markup,
88
+ text_changed=bool(spans),
89
+ entities_changed=bool(spans),
90
+ n_buttons=n_btn,
91
+ n_links=0,
92
+ n_typed=len(spans),
93
+ mine=bool(getattr(msg, "out", False)),
94
+ callbacks=has_cb,
95
+ ),
96
+ skipped,
97
+ )
app/health.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional tiny HTTP endpoint for hosts that insist on an open port (set PORT)."""
2
+ import asyncio
3
+ import logging
4
+
5
+ log = logging.getLogger(__name__)
6
+
7
+
8
+ async def start_health_server(port: int):
9
+ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
10
+ try:
11
+ await asyncio.wait_for(reader.read(1024), timeout=5)
12
+ except Exception:
13
+ pass
14
+ try:
15
+ writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok")
16
+ await writer.drain()
17
+ finally:
18
+ writer.close()
19
+
20
+ try:
21
+ server = await asyncio.start_server(handle, "0.0.0.0", port)
22
+ except OSError as e: # e.g. something else (python -m http.server) already uses the port
23
+ log.warning("could not open the health endpoint on :%s (%s) - continuing without it", port, e)
24
+ return None
25
+ log.info("health endpoint listening on :%s", port)
26
+ return server
app/linkswap.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Swap a username inside t.me links: button links, hyperlinks and typed links in message text.
2
+
3
+ Only the username part of a link changes; everything after it (?start=...) is left untouched.
4
+ Offsets of message entities are UTF-16 based, so text is handled in Telethon's 'surrogate' form.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ import re
10
+ from dataclasses import dataclass
11
+ from typing import Optional
12
+
13
+ from telethon import types
14
+ from telethon.helpers import add_surrogate, del_surrogate
15
+
16
+ from .richmsg import is_rich_message
17
+ from .tgutil import button_url, is_callback_button, with_url
18
+
19
+ USERNAME_RX = re.compile(r"^[A-Za-z0-9_]{1,32}$")
20
+
21
+
22
+ def normalize_username(s: str) -> Optional[str]:
23
+ s = (s or "").strip()
24
+ m = re.match(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me)/([A-Za-z0-9_]+)/?$", s)
25
+ if m:
26
+ s = m.group(1)
27
+ s = s.lstrip("@")
28
+ return s if USERNAME_RX.match(s) else None
29
+
30
+
31
+ # ------------------------------------------------------------------------------- urls
32
+ _HTTP_RX = re.compile(
33
+ r"^(?P<pre>(?:https?://)?(?:www\.)?(?:t\.me|telegram\.me|telegram\.dog)/)(?P<name>[A-Za-z0-9_]+)(?P<rest>[/?#].*)?$",
34
+ re.I | re.S,
35
+ )
36
+ _TG_RX = re.compile(r"^(?P<pre>tg://resolve\?(?:[^#]*&)?domain=)(?P<name>[A-Za-z0-9_]+)(?P<rest>[&#].*)?$", re.I | re.S)
37
+
38
+
39
+ def _split(url: str):
40
+ for rx in (_HTTP_RX, _TG_RX):
41
+ m = rx.match(url)
42
+ if m:
43
+ return m
44
+ return None
45
+
46
+
47
+ def _is_post_tail(tail: str) -> bool:
48
+ return bool(re.match(r"/\d", tail)) or bool(re.match(r"&post=\d", tail))
49
+
50
+
51
+ def classify_url(url: str, old: str) -> Optional[str]:
52
+ """'link' (t.me/old?start=..), 'post' (t.me/old/123 - a channel post) or None."""
53
+ m = _split(url or "")
54
+ if not m or m.group("name").lower() != old.lower():
55
+ return None
56
+ return "post" if _is_post_tail(m.group("rest") or "") else "link"
57
+
58
+
59
+ def swap_url(url: str, old: str, new: str) -> str:
60
+ m = _split(url or "")
61
+ if not m or m.group("name").lower() != old.lower():
62
+ return url
63
+ return url[: m.start("name")] + new + url[m.end("name"):]
64
+
65
+
66
+ # ------------------------------------------------------------------- typed links in text
67
+ def _typed_regexes(old: str) -> list:
68
+ n = re.escape(old)
69
+ return [
70
+ re.compile(
71
+ r"(?<![\w@./-])(?:https?://)?(?:www\.)?(?:t\.me|telegram\.me|telegram\.dog)/(?P<name>" + n + r")(?![A-Za-z0-9_])",
72
+ re.I,
73
+ ),
74
+ re.compile(r"(?<![\w@./-])tg://resolve\?(?:[^\s&#]*&)?domain=(?P<name>" + n + r")(?![A-Za-z0-9_])", re.I),
75
+ ]
76
+
77
+
78
+ def find_typed_spans(sur: str, old: str, include_posts: bool) -> tuple:
79
+ spans: list = []
80
+ skipped = 0
81
+ for rx in _typed_regexes(old):
82
+ for m in rx.finditer(sur):
83
+ s, e = m.span("name")
84
+ if _is_post_tail(sur[e:e + 8]) and not include_posts:
85
+ skipped += 1
86
+ continue
87
+ spans.append((s, e))
88
+ spans.sort()
89
+ return spans, skipped
90
+
91
+
92
+ def apply_span_replacements(sur: str, entities: list, repls: list) -> tuple:
93
+ """repls: sorted, non-overlapping (start, end, new_text) in UTF-16 units.
94
+ Returns (new_text, new_entities) with every entity offset/length kept consistent."""
95
+ parts: list = []
96
+ last = 0
97
+ for s, e, nt in repls:
98
+ parts.append(sur[last:s])
99
+ parts.append(nt)
100
+ last = e
101
+ parts.append(sur[last:])
102
+ new_text = "".join(parts)
103
+
104
+ def mp(x: int) -> int:
105
+ acc = 0
106
+ for s, e, nt in repls:
107
+ if x >= e:
108
+ acc += len(nt) - (e - s)
109
+ elif x > s:
110
+ return s + acc + min(x - s, len(nt))
111
+ else:
112
+ break
113
+ return x + acc
114
+
115
+ out = []
116
+ for ent in entities:
117
+ cp = copy.copy(ent)
118
+ o = mp(ent.offset)
119
+ end = mp(ent.offset + ent.length)
120
+ cp.offset = o
121
+ cp.length = max(0, end - o)
122
+ out.append(cp)
123
+ return new_text, out
124
+
125
+
126
+ # --------------------------------------------------------------------- whole message
127
+ @dataclass
128
+ class MsgChange:
129
+ message_id: int
130
+ new_text: str
131
+ new_entities: list
132
+ new_markup: Optional[types.ReplyInlineMarkup]
133
+ text_changed: bool
134
+ entities_changed: bool
135
+ n_buttons: int
136
+ n_links: int
137
+ n_typed: int
138
+ mine: bool
139
+ callbacks: bool
140
+
141
+
142
+ def compute_message_changes(msg, old: str, new: str, *, include_typed: bool = True, include_posts: bool = False) -> tuple:
143
+ """Returns (MsgChange or None, number_of_skipped_post_links)."""
144
+ rich = is_rich_message(msg) # the text of a rich message is blocks: only its buttons are changed
145
+ text = "" if rich else (msg.message or "")
146
+ ents = [] if rich else list(msg.entities or [])
147
+ skipped = 0
148
+ n_typed = n_links = n_btn = 0
149
+
150
+ # 1) links typed as plain text (this changes the text itself)
151
+ sur = add_surrogate(text)
152
+ new_sur = sur
153
+ new_ents = [copy.copy(e) for e in ents]
154
+ if include_typed and text:
155
+ spans, sk = find_typed_spans(sur, old, include_posts)
156
+ skipped += sk
157
+ if spans:
158
+ new_sur, new_ents = apply_span_replacements(sur, ents, [(s, e, new) for s, e in spans])
159
+ n_typed = len(spans)
160
+
161
+ # 2) hyperlinks (text with a link behind it)
162
+ for e in new_ents:
163
+ if isinstance(e, types.MessageEntityTextUrl):
164
+ kind = classify_url(e.url, old)
165
+ if kind == "link" or (kind == "post" and include_posts):
166
+ e.url = swap_url(e.url, old, new)
167
+ n_links += 1
168
+ elif kind == "post":
169
+ skipped += 1
170
+
171
+ # 3) buttons
172
+ new_markup = None
173
+ has_cb = False
174
+ mk = msg.reply_markup
175
+ if isinstance(mk, types.ReplyInlineMarkup):
176
+ rows = []
177
+ for row in mk.rows:
178
+ btns = []
179
+ for b in row.buttons:
180
+ url = button_url(b)
181
+ if url is not None:
182
+ kind = classify_url(url, old)
183
+ if kind == "link" or (kind == "post" and include_posts):
184
+ btns.append(with_url(b, swap_url(url, old, new)))
185
+ n_btn += 1
186
+ continue
187
+ if kind == "post":
188
+ skipped += 1
189
+ elif is_callback_button(b):
190
+ has_cb = True
191
+ btns.append(b)
192
+ rows.append(types.KeyboardButtonRow(btns))
193
+ if n_btn:
194
+ new_markup = types.ReplyInlineMarkup(rows)
195
+
196
+ if not (n_typed or n_links or n_btn):
197
+ return None, skipped
198
+ return (
199
+ MsgChange(
200
+ message_id=msg.id,
201
+ new_text=del_surrogate(new_sur),
202
+ new_entities=new_ents,
203
+ new_markup=new_markup,
204
+ text_changed=bool(n_typed),
205
+ entities_changed=bool(n_typed or n_links),
206
+ n_buttons=n_btn,
207
+ n_links=n_links,
208
+ n_typed=n_typed,
209
+ mine=bool(getattr(msg, "out", False)),
210
+ callbacks=has_cb,
211
+ ),
212
+ skipped,
213
+ )
214
+
215
+
216
+ def url_only_markup(markup, old: Optional[str] = None, new: Optional[str] = None, include_posts: bool = False):
217
+ """Buttons for a copy of a post: link buttons only (other bots' buttons would be dead), with the username
218
+ swapped when `old`/`new` are given. Returns (markup or None, number_of_buttons_not_copied)."""
219
+ if not isinstance(markup, types.ReplyInlineMarkup):
220
+ return None, 0
221
+ rows, dropped = [], 0
222
+ for row in markup.rows:
223
+ btns = []
224
+ for b in row.buttons:
225
+ url = button_url(b)
226
+ if url is None:
227
+ dropped += 1
228
+ continue
229
+ if old and new:
230
+ kind = classify_url(url, old)
231
+ if kind == "link" or (kind == "post" and include_posts):
232
+ b = with_url(b, swap_url(url, old, new))
233
+ btns.append(b)
234
+ if btns:
235
+ rows.append(types.KeyboardButtonRow(btns))
236
+ return (types.ReplyInlineMarkup(rows) if rows else None), dropped
app/picker.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The channel chooser used by every command that needs one of the connected channels.
2
+
3
+ The names are written out in the message as a numbered list (A to Z, 20 to a page); the buttons only carry the numbers
4
+ (5 to a row), and β—€ β–Ά underneath move to the previous / next 20. Pressing "3" means the third name of the list.
5
+ Each button carries the channel's id, never its position, so a list that changed meanwhile can't pick the wrong one.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections import Counter
11
+ from typing import Callable, Optional, Sequence
12
+
13
+ from telethon import Button
14
+
15
+ from .tgutil import esc, short
16
+
17
+ PER_PAGE = 20 # channel names in one message
18
+ PER_ROW = 5 # number buttons in one row
19
+ NAME_MAX = 60 # a longer name is cut in the list
20
+ PAGE_CB = "cpg" # callback prefix of the β—€ β–Ά buttons: cpg:<screen>:<argument>:<page>
21
+
22
+ _DIGITS = re.compile(r"(\d+)")
23
+
24
+
25
+ def natural_key(title: Optional[str]) -> tuple:
26
+ """A to Z, numbers by value ("Anime 2" before "Anime 10"), upper and lower case alike."""
27
+ parts = _DIGITS.split(" ".join((title or "").split()).casefold())
28
+ return tuple((0, int(p), "") if p.isdigit() else (1, 0, p) for p in parts if p != "")
29
+
30
+
31
+ def ordered(chans: Sequence) -> list:
32
+ """The channels in the order they are listed: by name, ascending (the id breaks ties)."""
33
+ return sorted(chans, key=lambda c: (natural_key(c.title), c.id))
34
+
35
+
36
+ def page_count(total: int) -> int:
37
+ return max(1, -(-total // PER_PAGE))
38
+
39
+
40
+ def clamp(page: int, total: int) -> int:
41
+ return max(0, min(int(page), page_count(total) - 1))
42
+
43
+
44
+ def names_of(chans: Sequence, *, with_username: bool = False) -> list:
45
+ """Display names (not yet escaped). Two channels with the same name get their @username (or id) added."""
46
+ keys = [" ".join((c.title or "").split()).casefold() for c in chans]
47
+ twins = Counter(keys)
48
+ out = []
49
+ for c, key in zip(chans, keys):
50
+ name = short(c.title or "", NAME_MAX) or "Channel"
51
+ if with_username and c.username:
52
+ name += f" (@{c.username})"
53
+ elif twins[key] > 1:
54
+ name += f" (@{c.username})" if c.username else f" ({c.id})"
55
+ out.append(name)
56
+ return out
57
+
58
+
59
+ def render(
60
+ chans: Sequence,
61
+ page: int,
62
+ *,
63
+ head: str,
64
+ kind: str,
65
+ arg: str = "",
66
+ choose: Optional[Callable] = None,
67
+ extra_rows: Sequence = (),
68
+ with_username: bool = False,
69
+ hint: Optional[str] = "Tap the number of the channel.",
70
+ ) -> tuple:
71
+ """(text, button rows) of one page.
72
+
73
+ head the question, already HTML
74
+ kind, arg which screen this is - the β—€ β–Ά buttons carry them so the same screen can be drawn again
75
+ choose channel -> callback data of its number button (None: a list to read, no number buttons)
76
+ extra_rows buttons under the arrows (Cancel ...)
77
+ hint the line under the list that says what the number buttons do (None: leave it out)
78
+ """
79
+ chans = ordered(chans)
80
+ total = len(chans)
81
+ pages = page_count(total)
82
+ page = clamp(page, total)
83
+ first = page * PER_PAGE
84
+ shown = chans[first : first + PER_PAGE]
85
+ names = names_of(chans, with_username=with_username)[first : first + PER_PAGE]
86
+ lines = [f"{first + i}. {esc(name)}" for i, name in enumerate(names, 1)]
87
+ text = f"{head}\n\n" + "\n".join(lines)
88
+ if pages > 1:
89
+ text += f"\n\nPage {page + 1} of {pages} - channels {first + 1} to {first + len(shown)} of {total}"
90
+ if choose is not None and hint:
91
+ text += f"\n\n{hint}"
92
+ rows: list = []
93
+ if choose is not None:
94
+ nums = [Button.inline(str(first + i), choose(c)) for i, c in enumerate(shown, 1)]
95
+ rows += [nums[i : i + PER_ROW] for i in range(0, len(nums), PER_ROW)]
96
+ if pages > 1: # always both arrows: on the first page β—€ goes to the last page, on the last page β–Ά to the first
97
+ rows.append(
98
+ [
99
+ Button.inline("β—€", f"{PAGE_CB}:{kind}:{arg}:{(page - 1) % pages}"),
100
+ Button.inline("β–Ά", f"{PAGE_CB}:{kind}:{arg}:{(page + 1) % pages}"),
101
+ ]
102
+ )
103
+ rows += [list(r) for r in extra_rows]
104
+ return text, rows
app/postlinks.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Links that point at other posts of the same channel (t.me/name/115, t.me/c/123456/115, tg://...&post=115).
2
+
3
+ When a channel is reposted its posts get new message ids, so a link to post 115 has to point at the copy of post 115.
4
+ Only the digits of the message id change; everything around them (?single, ?comment=3, the visible text) stays.
5
+ Links can sit in three places: a hyperlink behind text, a link typed into the text, and a button.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import re
11
+ from dataclasses import dataclass, field
12
+ from typing import Optional
13
+
14
+ from telethon import types
15
+ from telethon.helpers import add_surrogate, del_surrogate
16
+
17
+ from .linkswap import apply_span_replacements
18
+ from .richmsg import is_rich_message
19
+ from .tgutil import button_url, with_url
20
+
21
+ _HOST = r"(?:t\.me|telegram\.me|telegram\.dog)"
22
+ _NAME = r"[A-Za-z][A-Za-z0-9_]{2,31}"
23
+ # https://t.me/name/115 https://t.me/c/123456/115 (also t.me/s/name/115, the web preview)
24
+ _WEB = re.compile(
25
+ rf"^(?:https?://)?(?:www\.)?{_HOST}/(?:s/)?(?P<seg>c/(?P<cid>\d+)|(?P<name>{_NAME}))/(?P<id>\d+)(?![A-Za-z0-9_])", re.I
26
+ )
27
+ _TYPED = re.compile(
28
+ rf"(?<![\w@./=?&#-])(?:https?://)?(?:www\.)?{_HOST}/(?:s/)?(?:c/\d+|{_NAME})/\d+(?![A-Za-z0-9_])", re.I
29
+ )
30
+ # tg://resolve?domain=name&post=115 tg://privatepost?channel=123456&post=115
31
+ _TG = re.compile(r"^tg://(?P<kind>resolve|privatepost)\?(?P<query>[^#]*)", re.I)
32
+ _POST_PARAM = re.compile(r"(?<=[?&])post=(\d+)")
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class Ref:
37
+ """A link to a post: which channel (username in lower case, or the numeric id) and where the id's digits sit."""
38
+
39
+ name: Optional[str]
40
+ cid: Optional[int]
41
+ msg_id: int
42
+ start: int # the digits of the message id ...
43
+ end: int
44
+ seg_start: Optional[int] = None # ... and the channel part in front of them ("name" or "c/123"); web links only
45
+
46
+
47
+ def parse_ref(url: str) -> Optional[Ref]:
48
+ """What `url` points at, if it is a link to a post of some channel; None for every other link."""
49
+ url = url or ""
50
+ m = _WEB.match(url)
51
+ if m:
52
+ return Ref(
53
+ name=m.group("name").lower() if m.group("name") else None,
54
+ cid=int(m.group("cid")) if m.group("cid") else None,
55
+ msg_id=int(m.group("id")),
56
+ start=m.start("id"),
57
+ end=m.end("id"),
58
+ seg_start=m.start("seg"),
59
+ )
60
+ m = _TG.match(url)
61
+ if m:
62
+ params = dict(p.split("=", 1) for p in m.group("query").split("&") if "=" in p)
63
+ post = _POST_PARAM.search(url)
64
+ if post is None:
65
+ return None
66
+ if m.group("kind").lower() == "resolve" and re.fullmatch(r"[A-Za-z0-9_]+", params.get("domain", "")):
67
+ return Ref(params["domain"].lower(), None, int(post.group(1)), post.start(1), post.end(1))
68
+ if m.group("kind").lower() == "privatepost" and params.get("channel", "").isdigit():
69
+ return Ref(None, int(params["channel"]), int(post.group(1)), post.start(1), post.end(1))
70
+ return None
71
+
72
+
73
+ @dataclass
74
+ class PostLinks:
75
+ """The links that point into one channel, and where its posts went: `ids` maps old message id -> new one.
76
+
77
+ By default the copies are in the same channel (/repost): only the message id changes. With `target_id` the
78
+ copies are in another channel (/shift): the channel part of the link changes too."""
79
+
80
+ username: Optional[str]
81
+ channel_id: int
82
+ ids: dict = field(default_factory=dict)
83
+ target_username: Optional[str] = None
84
+ target_id: Optional[int] = None
85
+
86
+ @classmethod
87
+ def for_channel(cls, ch, ids: Optional[dict] = None) -> "PostLinks":
88
+ return cls(username=(ch.username or None), channel_id=int(ch.id), ids=ids if ids is not None else {})
89
+
90
+ # -------------------------------------------------------------------------------------- one url
91
+ def ref_of(self, url: str) -> Optional[Ref]:
92
+ """The reference in `url` if it points at a post of THIS channel."""
93
+ r = parse_ref(url)
94
+ if r is None:
95
+ return None
96
+ if r.name is not None and self.username and r.name == self.username.lower():
97
+ return r
98
+ if r.cid is not None and r.cid == self.channel_id:
99
+ return r
100
+ return None
101
+
102
+ def edit_of(self, url: str) -> Optional[tuple]:
103
+ """(start, end, new text) to apply to `url` so it points at the copy of its post; None if it stays as it is."""
104
+ r = self.ref_of(url)
105
+ if r is None or r.msg_id not in self.ids:
106
+ return None
107
+ new_id = str(self.ids[r.msg_id])
108
+ if self.target_id is None:
109
+ return r.start, r.end, new_id
110
+ if r.seg_start is None: # tg:// links are not moved to another channel
111
+ return None
112
+ channel = self.target_username or f"c/{self.target_id}"
113
+ return r.seg_start, r.end, f"{channel}/{new_id}"
114
+
115
+ def remap_url(self, url: str) -> str:
116
+ e = self.edit_of(url)
117
+ return url if e is None else url[: e[0]] + e[2] + url[e[1] :]
118
+
119
+ # --------------------------------------------------------------------------------- whole message
120
+ def count(self, text: str, entities, markup) -> int:
121
+ """How many links in a message point at a post of this channel (whether or not the post has a new id)."""
122
+ n = 0
123
+ sur = add_surrogate(text or "")
124
+ for m in _TYPED.finditer(sur):
125
+ if self.ref_of(m.group(0)):
126
+ n += 1
127
+ for e in entities or []:
128
+ if isinstance(e, types.MessageEntityTextUrl) and self.ref_of(e.url):
129
+ n += 1
130
+ if isinstance(markup, types.ReplyInlineMarkup):
131
+ for row in markup.rows:
132
+ for b in row.buttons:
133
+ u = button_url(b)
134
+ if u is not None and self.ref_of(u):
135
+ n += 1
136
+ return n
137
+
138
+ def remap_text(self, text: str, entities) -> tuple:
139
+ """-> (text, entities, typed_links_changed, hyperlinks_changed). Offsets of all entities stay right."""
140
+ ents = list(entities or [])
141
+ sur = add_surrogate(text or "")
142
+ repls = []
143
+ for m in _TYPED.finditer(sur):
144
+ e = self.edit_of(m.group(0))
145
+ if e is not None:
146
+ repls.append((m.start() + e[0], m.start() + e[1], e[2]))
147
+ if repls:
148
+ new_sur, new_ents = apply_span_replacements(sur, ents, repls)
149
+ else:
150
+ new_sur, new_ents = sur, [copy.copy(e) for e in ents]
151
+ hyper = 0
152
+ for e in new_ents:
153
+ if isinstance(e, types.MessageEntityTextUrl):
154
+ new_url = self.remap_url(e.url)
155
+ if new_url != e.url:
156
+ e.url = new_url
157
+ hyper += 1
158
+ return del_surrogate(new_sur), new_ents, len(repls), hyper
159
+
160
+ def remap_markup(self, markup) -> tuple:
161
+ """-> (markup, buttons_changed); the keyboard object is only rebuilt when a button changes."""
162
+ if not isinstance(markup, types.ReplyInlineMarkup):
163
+ return markup, 0
164
+ rows, changed = [], 0
165
+ for row in markup.rows:
166
+ btns = []
167
+ for b in row.buttons:
168
+ u = button_url(b)
169
+ new = self.remap_url(u) if u is not None else None
170
+ if new is not None and new != u:
171
+ btns.append(with_url(b, new))
172
+ changed += 1
173
+ else:
174
+ btns.append(b)
175
+ rows.append(types.KeyboardButtonRow(btns))
176
+ return (types.ReplyInlineMarkup(rows) if changed else markup), changed
177
+
178
+
179
+ @dataclass
180
+ class Relinked:
181
+ """A message whose links to other posts of the channel were pointed at the copies."""
182
+
183
+ text: str
184
+ entities: list
185
+ markup: Optional[types.ReplyInlineMarkup]
186
+ text_changed: bool # the text or its entities differ
187
+ markup_changed: bool
188
+ n_typed: int
189
+ n_hyper: int
190
+ n_buttons: int
191
+
192
+ @property
193
+ def links(self) -> int:
194
+ return self.n_typed + self.n_hyper + self.n_buttons
195
+
196
+
197
+ def relink_message(msg, links: PostLinks) -> Optional[Relinked]:
198
+ """The new text / entities / buttons of `msg` once its links are remapped; None when nothing changes."""
199
+ if is_rich_message(msg): # the text of a rich message is blocks: only its buttons are changed
200
+ text, entities, n_typed, n_hyper = "", [], 0, 0
201
+ else:
202
+ text, entities, n_typed, n_hyper = links.remap_text(msg.message or "", msg.entities)
203
+ markup, n_buttons = links.remap_markup(msg.reply_markup)
204
+ if not (n_typed or n_hyper or n_buttons):
205
+ return None
206
+ return Relinked(
207
+ text=text,
208
+ entities=entities,
209
+ markup=markup,
210
+ text_changed=bool(n_typed or n_hyper),
211
+ markup_changed=bool(n_buttons),
212
+ n_typed=n_typed,
213
+ n_hyper=n_hyper,
214
+ n_buttons=n_buttons,
215
+ )
216
+
217
+
218
+ def resolve_chain(step: dict) -> dict:
219
+ """Several reposts in a row: {1: 5, 5: 9} -> {1: 9, 5: 9} (a post that moved twice points at its latest copy)."""
220
+ out = {}
221
+ for old in step:
222
+ cur, seen = old, 0
223
+ while cur in step and seen < 100:
224
+ cur, seen = step[cur], seen + 1
225
+ out[old] = cur
226
+ return out
app/profile_copy.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/shift -all: the destination channel gets the name, description and profile photo of the source channel.
2
+
3
+ Each part is done on its own, so one that fails (a missing admin right, a photo Telegram refuses) does not stop the
4
+ others. A part the source does not have (no description, no photo) is left as it is in the destination: nothing is ever
5
+ wiped. The notices Telegram adds to a channel when its name or photo changes are deleted again right away.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ from dataclasses import dataclass, field
11
+ from types import SimpleNamespace
12
+ from typing import Optional
13
+
14
+ from telethon import errors, functions, types
15
+
16
+ from .repost_engine import delete_ids, new_messages_from
17
+ from .tgutil import esc, flood_retry, peer_of
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+ PARTS = ("name", "description", "photo")
22
+ LABELS = {"name": "Name", "description": "Description", "photo": "Profile photo"}
23
+ NEEDS_RIGHT = "the bot needs the β€œChange channel info” admin right in the destination"
24
+
25
+
26
+ @dataclass
27
+ class ProfileResult:
28
+ """What happened to each part: part -> (status, detail). Status: done | same | none | failed."""
29
+
30
+ outcome: dict = field(default_factory=dict)
31
+ title: Optional[str] = None # the destination's name after the run (None: it did not change)
32
+
33
+ @property
34
+ def ok(self) -> bool:
35
+ return all(s != "failed" for s, _ in self.outcome.values())
36
+
37
+ @property
38
+ def done(self) -> list:
39
+ return [p for p in PARTS if self.outcome.get(p, ("", ""))[0] == "done"]
40
+
41
+ @property
42
+ def failed(self) -> list:
43
+ return [(p, d) for p in PARTS for s, d in [self.outcome.get(p, ("", ""))] if s == "failed"]
44
+
45
+
46
+ def _real(photo):
47
+ return None if photo is None or isinstance(photo, types.PhotoEmpty) else photo
48
+
49
+
50
+ async def read_profile(client, ch) -> SimpleNamespace:
51
+ """The name, the description and the profile photo a channel shows right now."""
52
+ full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer_of(ch))))
53
+ chat = next((c for c in getattr(full, "chats", None) or [] if getattr(c, "id", None) == ch.id), None)
54
+ fc = full.full_chat
55
+ return SimpleNamespace(
56
+ title=getattr(chat, "title", None), about=getattr(fc, "about", None) or "", photo=_real(getattr(fc, "chat_photo", None))
57
+ )
58
+
59
+
60
+ def _failure(e: BaseException) -> str:
61
+ name = type(e).__name__
62
+ if name == "ChatAdminRequiredError":
63
+ return NEEDS_RIGHT
64
+ return name
65
+
66
+
67
+ async def _set_name(client, dst, title: str) -> tuple:
68
+ try:
69
+ out = await flood_retry(lambda: client(functions.channels.EditTitleRequest(channel=peer_of(dst), title=title)))
70
+ except errors.ChatNotModifiedError:
71
+ return "same", ""
72
+ except errors.RPCError as e:
73
+ return "failed", _failure(e)
74
+ await _drop_notices(client, dst, out)
75
+ return "done", title
76
+
77
+
78
+ async def _set_description(client, dst, about: str) -> tuple:
79
+ try:
80
+ await flood_retry(lambda: client(functions.messages.EditChatAboutRequest(peer=peer_of(dst), about=about)))
81
+ except (errors.ChatAboutNotModifiedError, errors.ChatNotModifiedError):
82
+ return "same", ""
83
+ except errors.RPCError as e:
84
+ return "failed", _failure(e)
85
+ return "done", ""
86
+
87
+
88
+ async def _set_photo(client, dst, photo) -> tuple:
89
+ try:
90
+ data = await client.download_media(photo, file=bytes)
91
+ if not data:
92
+ return "failed", "the photo could not be downloaded"
93
+ uploaded = await client.upload_file(data, file_name="channel_photo.jpg")
94
+ out = await flood_retry(
95
+ lambda: client(
96
+ functions.channels.EditPhotoRequest(channel=peer_of(dst), photo=types.InputChatUploadedPhoto(file=uploaded))
97
+ )
98
+ )
99
+ except errors.ChatNotModifiedError:
100
+ return "same", ""
101
+ except errors.RPCError as e:
102
+ return "failed", _failure(e)
103
+ except Exception as e: # a download or upload problem is not a reason to stop the shift
104
+ log.warning("copying the profile photo failed: %s %s", type(e).__name__, e)
105
+ return "failed", type(e).__name__
106
+ await _drop_notices(client, dst, out)
107
+ return "done", ""
108
+
109
+
110
+ async def _drop_notices(client, ch, result) -> None:
111
+ """Remove the "channel name / photo changed" notices Telegram put into the channel."""
112
+ ids = [m.id for m in new_messages_from(result) if isinstance(m, types.MessageService)]
113
+ if ids:
114
+ await delete_ids(client, peer_of(ch), ids)
115
+
116
+
117
+ async def copy_profile(client, src, dst) -> ProfileResult:
118
+ """Give `dst` the name, the description and the profile photo of `src`. Nothing is wiped: a part that the source
119
+ does not have stays as the destination has it. Both arguments need `id` and `access_hash`."""
120
+ res = ProfileResult()
121
+ try:
122
+ s = await read_profile(client, src)
123
+ except errors.RPCError as e:
124
+ for p in PARTS:
125
+ res.outcome[p] = ("failed", f"the source can't be read ({type(e).__name__})")
126
+ return res
127
+ try:
128
+ d = await read_profile(client, dst)
129
+ except errors.RPCError:
130
+ d = SimpleNamespace(title=None, about=None, photo=None) # unknown: every part is simply tried
131
+
132
+ if not s.title:
133
+ res.outcome["name"] = ("none", "")
134
+ elif s.title == d.title:
135
+ res.outcome["name"] = ("same", "")
136
+ else:
137
+ res.outcome["name"] = await _set_name(client, dst, s.title)
138
+ if res.outcome["name"][0] == "done":
139
+ res.title = s.title
140
+
141
+ if not s.about:
142
+ res.outcome["description"] = ("none", "")
143
+ elif s.about == d.about:
144
+ res.outcome["description"] = ("same", "")
145
+ else:
146
+ res.outcome["description"] = await _set_description(client, dst, s.about)
147
+
148
+ if s.photo is None:
149
+ res.outcome["photo"] = ("none", "")
150
+ else:
151
+ res.outcome["photo"] = await _set_photo(client, dst, s.photo)
152
+ return res
153
+
154
+
155
+ def profile_lines(res: ProfileResult, dst_title: str = "") -> list:
156
+ """Lines (HTML) about what was copied, for the end of a shift."""
157
+ shown = {"done": "copied", "same": "already the same", "none": "the source has none - left as it is"}
158
+ parts, bad = [], []
159
+ for p in PARTS:
160
+ status, detail = res.outcome.get(p, ("", ""))
161
+ if status == "failed":
162
+ bad.append(f"{LABELS[p]}: {esc(detail)}")
163
+ elif status:
164
+ parts.append(f"{LABELS[p].lower()} {shown[status]}")
165
+ out = []
166
+ if parts:
167
+ out.append("πŸ–Ό " + ("<b>" + esc(dst_title) + "</b>: " if dst_title else "") + ", ".join(parts) + ".")
168
+ if bad:
169
+ out.append("⚠️ Not copied - " + "; ".join(bad) + ".")
170
+ return out
app/replace_engine.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/swap engine: scan channels message by message, rewrite links, log every change, undo."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import logging
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Awaitable, Callable, Optional
8
+
9
+ from telethon import errors, functions, types
10
+
11
+ from .handleswap import compute_handle_changes
12
+ from .linkswap import compute_message_changes
13
+ from .richmsg import entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of
14
+ from .tgutil import (
15
+ build_markup,
16
+ de_entities,
17
+ edit_raw,
18
+ flood_retry,
19
+ media_info,
20
+ peer_of,
21
+ ser_entities,
22
+ ser_markup,
23
+ state_of,
24
+ )
25
+
26
+ log = logging.getLogger(__name__)
27
+
28
+ CHUNK = 100 # Telegram returns at most 100 messages per request
29
+ FALLBACK_EMPTY_BATCHES = 15 # used only when the newest message id can't be determined
30
+ ABORT_AFTER = 5 # stop a channel after this many identical Telegram refusals in a row
31
+
32
+
33
+ @dataclass
34
+ class ScanOptions:
35
+ old: str
36
+ new: str
37
+ include_typed: bool = True
38
+ include_posts: bool = False
39
+ last: Optional[int] = None
40
+ mode: str = "links" # "links": the username inside t.me links (/swap); "handles": '@name' written in a post (/handleswap)
41
+
42
+
43
+ def compute_changes(m, opts: ScanOptions) -> tuple:
44
+ """What this run would change in message `m`: (MsgChange or None, skipped)."""
45
+ if opts.mode == "handles":
46
+ return compute_handle_changes(m, opts.old, opts.new)
47
+ return compute_message_changes(
48
+ m, opts.old, opts.new, include_typed=opts.include_typed, include_posts=opts.include_posts
49
+ )
50
+
51
+
52
+ @dataclass
53
+ class ChangeInfo:
54
+ message_id: int
55
+ buttons: int = 0
56
+ links: int = 0
57
+ typed: int = 0
58
+ mine: bool = False
59
+ callbacks: bool = False
60
+
61
+
62
+ @dataclass
63
+ class ChannelScan:
64
+ channel: Any
65
+ can_edit_others: bool = True
66
+ top: int = 0
67
+ first: int = 1
68
+ scanned: int = 0
69
+ infos: dict = field(default_factory=dict)
70
+ skipped_post_links: int = 0
71
+ not_editable: int = 0
72
+ error: Optional[str] = None
73
+ rights: Any = None
74
+
75
+ @property
76
+ def total(self) -> int:
77
+ return len(self.infos)
78
+
79
+ @property
80
+ def foreign(self) -> int:
81
+ return sum(1 for i in self.infos.values() if not i.mine)
82
+
83
+
84
+ @dataclass
85
+ class ApplyResult:
86
+ edited: int = 0
87
+ unchanged: int = 0
88
+ missing: int = 0
89
+ no_perm: int = 0
90
+ failed: list = field(default_factory=list)
91
+ aborted: Optional[str] = None # error name that made us stop early
92
+
93
+
94
+ @dataclass
95
+ class UndoResult:
96
+ restored: int = 0
97
+ failed: list = field(default_factory=list)
98
+
99
+
100
+ async def fetch_messages(client, peer, ids: list) -> list:
101
+ res = await flood_retry(lambda: client.get_messages(peer, ids=ids))
102
+ return list(res)
103
+
104
+
105
+ async def get_top_id(client, peer) -> Optional[int]:
106
+ """Upper bound for the newest message id: the channel's event counter (pts) is never lower."""
107
+ try:
108
+ full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer)))
109
+ pts = getattr(full.full_chat, "pts", None)
110
+ if pts:
111
+ return int(pts)
112
+ except Exception as e:
113
+ log.info("could not read channel counter: %s", e)
114
+ return None
115
+
116
+
117
+ def is_skippable(m) -> bool:
118
+ return m is None or isinstance(m, (types.MessageEmpty, types.MessageService))
119
+
120
+
121
+ async def scan_channel(
122
+ client,
123
+ ch,
124
+ opts: ScanOptions,
125
+ *,
126
+ can_edit_others: bool = True,
127
+ mine_ids: Optional[set] = None,
128
+ progress: Optional[Callable[[ChannelScan], Awaitable[None]]] = None,
129
+ ) -> ChannelScan:
130
+ scan = ChannelScan(channel=ch, can_edit_others=can_edit_others)
131
+ peer = peer_of(ch)
132
+ mine_ids = mine_ids or set()
133
+ top = await get_top_id(client, peer)
134
+ first = 1
135
+ if opts.last and top:
136
+ first = max(1, top - opts.last + 1)
137
+ scan.first, scan.top = first, top or 0
138
+ a, empty_run = first, 0
139
+ while True:
140
+ if top is not None and a > top:
141
+ break
142
+ hi = a + CHUNK - 1 if top is None else min(a + CHUNK - 1, top)
143
+ msgs = await fetch_messages(client, peer, list(range(a, hi + 1)))
144
+ found = False
145
+ for m in msgs:
146
+ if m is None or isinstance(m, types.MessageEmpty):
147
+ continue
148
+ found = True
149
+ if isinstance(m, types.MessageService):
150
+ continue
151
+ change, skipped = compute_changes(m, opts)
152
+ scan.skipped_post_links += skipped
153
+ if not change:
154
+ continue
155
+ mine = change.mine or m.id in mine_ids
156
+ if not mine and not can_edit_others:
157
+ scan.not_editable += 1
158
+ continue
159
+ scan.infos[m.id] = ChangeInfo(
160
+ m.id, change.n_buttons, change.n_links, change.n_typed, mine, change.callbacks
161
+ )
162
+ scan.scanned = hi
163
+ if top is None:
164
+ empty_run = 0 if found else empty_run + 1
165
+ if empty_run >= FALLBACK_EMPTY_BATCHES:
166
+ break
167
+ if progress:
168
+ await progress(scan)
169
+ a = hi + 1
170
+ if top is None:
171
+ scan.top = scan.scanned
172
+ return scan
173
+
174
+
175
+ def preview_flag(m):
176
+ if isinstance(m.media, types.MessageMediaWebPage):
177
+ return True
178
+ return False if m.media is None else None
179
+
180
+
181
+ async def _do_edit(client, peer, m, change, markup, preview) -> None:
182
+ if change.text_changed or change.entities_changed:
183
+ await edit_raw(
184
+ client, peer, m.id, text=change.new_text, entities=change.new_entities, markup=markup, preview=preview
185
+ )
186
+ else: # only button links changed: leave the text untouched
187
+ await edit_raw(client, peer, m.id, markup=markup)
188
+
189
+
190
+ async def apply_channel(
191
+ client,
192
+ db,
193
+ scan: ChannelScan,
194
+ opts: ScanOptions,
195
+ batch_id: str,
196
+ user_id: int,
197
+ *,
198
+ edit_delay: float = 1.2,
199
+ progress: Optional[Callable[[ApplyResult], Awaitable[None]]] = None,
200
+ ) -> ApplyResult:
201
+ ch = scan.channel
202
+ peer = peer_of(ch)
203
+ mine_ids = await db.mine_message_ids(ch.id)
204
+ res = ApplyResult()
205
+ ids = sorted(scan.infos)
206
+ buf: list = []
207
+ streak, last_name = 0, None
208
+
209
+ async def flush() -> None:
210
+ nonlocal buf
211
+ if buf:
212
+ batch, buf = buf, []
213
+ await db.record_changes(batch_id, ch.id, batch, user_id)
214
+
215
+ try:
216
+ for i in range(0, len(ids), CHUNK):
217
+ chunk = ids[i:i + CHUNK]
218
+ msgs = await fetch_messages(client, peer, chunk)
219
+ for mid, m in zip(chunk, msgs):
220
+ if is_skippable(m):
221
+ res.missing += 1
222
+ continue
223
+ # re-check against the live message: it may have been edited since the scan
224
+ change, _ = compute_changes(m, opts)
225
+ if not change:
226
+ res.unchanged += 1
227
+ continue
228
+ if not (change.mine or m.id in mine_ids) and not scan.can_edit_others:
229
+ res.no_perm += 1
230
+ continue
231
+ preview = preview_flag(m)
232
+ markup = change.new_markup if change.new_markup is not None else m.reply_markup
233
+ old_state = state_of(m.message, m.entities, m.reply_markup, preview)
234
+ rich = is_rich_message(m)
235
+ if rich: # its text is blocks this run never touches: undo puts the buttons back and nothing else
236
+ old_state["rich"] = True
237
+ try:
238
+ await flood_retry(lambda: _do_edit(client, peer, m, change, markup, preview))
239
+ except errors.MessageNotModifiedError:
240
+ res.unchanged += 1
241
+ continue
242
+ except errors.RPCError as e:
243
+ name = type(e).__name__
244
+ log.warning("edit of %s/%s failed: %s", ch.id, m.id, name)
245
+ res.failed.append((m.id, name))
246
+ streak = streak + 1 if name == last_name else 1
247
+ last_name = name
248
+ if streak >= ABORT_AFTER:
249
+ res.aborted = name
250
+ break
251
+ continue
252
+ streak, last_name = 0, None
253
+ res.edited += 1
254
+ kind, fid = media_info(m)
255
+ adopt = {
256
+ "text": change.new_text,
257
+ "entities": ser_entities(change.new_entities),
258
+ "buttons": ser_markup(markup),
259
+ "link_preview": bool(preview),
260
+ }
261
+ if kind:
262
+ adopt["media_kind"], adopt["media_file_id"] = kind, fid
263
+ new_state = state_of(change.new_text, change.new_entities, markup, preview)
264
+ if rich:
265
+ new_state["rich"] = True
266
+ saved = await db.find_by_message(ch.id, m.id)
267
+ if saved is not None and rich_of(saved) is not None:
268
+ del adopt["text"], adopt["entities"] # the saved copy keeps what it was sent from
269
+ else: # a rich message nobody saved yet: it is taken over as its blocks
270
+ adopt["text"] = plain_of_message(m)
271
+ adopt["entities"] = [rich_entry(rich_from_received(m.rich_message))]
272
+ buf.append(
273
+ {
274
+ "message_id": m.id,
275
+ "old_state": old_state,
276
+ "new_state": new_state,
277
+ "adopt": adopt,
278
+ }
279
+ )
280
+ if len(buf) >= 10:
281
+ await flush()
282
+ if progress:
283
+ await progress(res)
284
+ await asyncio.sleep(edit_delay)
285
+ if res.aborted:
286
+ break
287
+ finally:
288
+ await flush()
289
+ return res
290
+
291
+
292
+ async def undo_batch(
293
+ client,
294
+ db,
295
+ batch_id: str,
296
+ *,
297
+ edit_delay: float = 1.2,
298
+ progress: Optional[Callable[[UndoResult], Awaitable[None]]] = None,
299
+ ) -> UndoResult:
300
+ """Put every post touched by a /swap run back exactly as it was."""
301
+ res = UndoResult()
302
+ channels: dict = {}
303
+ done_ids: list = []
304
+ restored: list = []
305
+ for c in await db.batch_changes(batch_id):
306
+ if c.channel_id not in channels:
307
+ channels[c.channel_id] = await db.get_channel(c.channel_id)
308
+ ch = channels[c.channel_id]
309
+ if ch is None:
310
+ res.failed.append((c.message_id, "ChannelRemoved"))
311
+ continue
312
+ old = c.old_state or {}
313
+ try:
314
+ if old.get("rich"): # a rich message: only its buttons were changed, so only they are put back
315
+ markup = build_markup(old.get("buttons"))
316
+ if markup is not None:
317
+ await flood_retry(lambda: edit_raw(client, peer_of(ch), c.message_id, markup=markup))
318
+ else:
319
+ await flood_retry(
320
+ lambda: edit_raw(
321
+ client,
322
+ peer_of(ch),
323
+ c.message_id,
324
+ text=old.get("text", ""),
325
+ entities=de_entities(old.get("entities")),
326
+ markup=build_markup(old.get("buttons")),
327
+ preview=old.get("preview"),
328
+ )
329
+ )
330
+ except errors.MessageNotModifiedError:
331
+ pass
332
+ except errors.RPCError as e:
333
+ log.warning("undo of %s/%s failed: %s", c.channel_id, c.message_id, e)
334
+ res.failed.append((c.message_id, type(e).__name__))
335
+ continue
336
+ res.restored += 1
337
+ done_ids.append(c.id)
338
+ restored.append((c.channel_id, c.message_id, old))
339
+ if progress:
340
+ await progress(res)
341
+ await asyncio.sleep(edit_delay)
342
+ await db.finish_undo(batch_id, done_ids, restored, all_done=not res.failed)
343
+ return res
app/repost_engine.py ADDED
@@ -0,0 +1,1372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Repost a whole channel in order.
2
+
3
+ Every post is copied to the end of the channel (silently), in the same order as the original:
4
+ 1. a post that needs no change (no buttons, no link to swap) is copied by Telegram itself
5
+ (messages.forwardMessages with drop_author): text, formatting, quotes, media and albums stay exact;
6
+ 2. a post with buttons, or with links to swap, is created again in ONE request that carries its final
7
+ text, formatting and buttons - exactly how the bot publishes a post of its own - and is then read back
8
+ to make sure the buttons really are there (a copy that is edited afterwards can end up without them);
9
+ 3. if the channel forbids forwarding, every post is created like in 2.
10
+ Links can be swapped on the way, the new posts are registered in the database, and the old posts are removed
11
+ later in a separate step. Nothing here deletes anything unless asked to (delete_copies).
12
+
13
+ What a plain copy would lose is put back as well:
14
+ * a post that answers another post is posted as an answer to the COPY of that post (a reply can only be set
15
+ when a post is created, so such a post is always created again instead of copied);
16
+ * a link to another post of the channel (t.me/name/115) is pointed at the copy of that post - at once when the
17
+ copy already exists, afterwards (finalize_repost) for posts that are copied later;
18
+ * a post that was pinned has its copy pinned at the end.
19
+
20
+ A post that TELEGRAM restricts (a copyright strike: the whole channel is "unavailable due to copyright infringement",
21
+ or the post carries a restriction mark, or Telegram's apps show "This message couldn't be displayed on your device due
22
+ to copyright infringement" instead of the post) is not copied as Telegram hands it out now. /shift rebuilds such a post
23
+ from what My posts saved of it (text, formatting, buttons, media) - for a restricted CHANNEL every post that has a saved
24
+ copy, however intact Telegram's version looks. A post without a saved copy is copied as Telegram hands it out when that
25
+ is the post itself, and skipped (and reported) when it is only Telegram's notice. Telegram's notice is never posted, from
26
+ whichever source. /repost leaves a post whose content Telegram holds back alone.
27
+ Every copy of a restricted source is read back: if Telegram itself hides the new post, that is reported (copy_loop).
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import asyncio
32
+ import copy
33
+ import logging
34
+ from dataclasses import dataclass, field
35
+ from typing import Any, AsyncIterator, Awaitable, Callable, Optional
36
+
37
+ from telethon import errors, functions, types, utils
38
+
39
+ from .buttons_sync import ButtonsNotShown, ensure_markup, link_urls
40
+ from .crosslinks import CrossResult, relink_after_repost
41
+ from .linkswap import compute_message_changes, url_only_markup
42
+ from .postlinks import PostLinks, relink_message
43
+ from .replace_engine import CHUNK, FALLBACK_EMPTY_BATCHES, fetch_messages, is_skippable, preview_flag
44
+ from .restrictions import PLACEHOLDER_NOTE, is_placeholder_text, message_restriction, probe_channel
45
+ from .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of, rich_from_received, rich_of, with_rich
46
+ from .tgutil import (
47
+ FATAL,
48
+ build_markup,
49
+ classify_media,
50
+ de_entities,
51
+ edit_raw,
52
+ flood_retry,
53
+ media_from_ref,
54
+ media_ref,
55
+ peer_of,
56
+ ser_entities,
57
+ ser_markup,
58
+ )
59
+
60
+ log = logging.getLogger(__name__)
61
+
62
+ ABORT_AFTER = 8 # consecutive posts that could not be copied -> stop
63
+
64
+
65
+ @dataclass
66
+ class RepostOptions:
67
+ old: Optional[str] = None
68
+ new: Optional[str] = None
69
+ include_typed: bool = True
70
+ include_posts: bool = False
71
+ last: Optional[int] = None # trial run: only the newest N post ids
72
+
73
+ @property
74
+ def swaps(self) -> bool:
75
+ return bool(self.old and self.new)
76
+
77
+
78
+ @dataclass
79
+ class Final:
80
+ """What a copy of a post should look like."""
81
+
82
+ text: str
83
+ entities: list
84
+ markup: Optional[types.ReplyInlineMarkup]
85
+ preview: Optional[bool]
86
+ text_changed: bool
87
+ n_buttons: int = 0
88
+ n_links: int = 0
89
+ n_typed: int = 0
90
+ dropped: int = 0 # other bots' buttons that are not copied
91
+ n_post_links: int = 0 # links to other posts of the same channel (whatever their new id will be)
92
+ n_relinked: int = 0 # of those, how many were already pointed at a copy
93
+ rich: Optional[Rich] = None # the post is a rich message: this is what the copy is made from (text / entities are empty)
94
+
95
+
96
+ def rich_for(src) -> Optional[Rich]:
97
+ """The rich message that `src` is - a live post, or a stand-in made from a saved post - or None for an ordinary post."""
98
+ saved = getattr(src, "rich_saved", None)
99
+ if saved is not None:
100
+ return saved
101
+ rm = getattr(src, "rich_message", None)
102
+ return rich_from_received(rm) if rm is not None else None
103
+
104
+
105
+ def final_state(src, opts: RepostOptions, links: Optional[PostLinks] = None) -> Final:
106
+ """What the copy of `src` should look like. `links` (optional) points links to other posts of the channel at
107
+ the copies that exist so far (links.ids: old message id -> new one)."""
108
+ change = None
109
+ if opts.swaps:
110
+ change, _ = compute_message_changes(
111
+ src, opts.old, opts.new, include_typed=opts.include_typed, include_posts=opts.include_posts
112
+ )
113
+ rich = rich_for(src)
114
+ text = change.new_text if change else (src.message or "")
115
+ entities = list(change.new_entities) if change else list(src.entities or [])
116
+ if rich is not None: # a rich message's text is blocks: nothing of it is changed here, only its buttons
117
+ text, entities = "", []
118
+ # text mentions need an access hash to be re-sent; they are rare in channel posts
119
+ entities = [e for e in entities if not isinstance(e, types.MessageEntityMentionName)]
120
+ markup, dropped = url_only_markup(
121
+ src.reply_markup, opts.old if opts.swaps else None, opts.new if opts.swaps else None, opts.include_posts
122
+ )
123
+ n_post_links = n_relinked = 0
124
+ text_changed = bool(change and change.entities_changed)
125
+ if links is not None:
126
+ n_post_links = links.count(text, entities, markup)
127
+ if n_post_links and links.ids:
128
+ text, entities, n_typed, n_hyper = links.remap_text(text, entities)
129
+ markup, n_buttons = links.remap_markup(markup)
130
+ n_relinked = n_typed + n_hyper + n_buttons
131
+ text_changed = text_changed or bool(n_typed or n_hyper)
132
+ # Send exactly what is saved: go through the stored form that "My posts" also uses to build its edits.
133
+ markup = build_markup(ser_markup(markup)) if markup is not None else None
134
+ entities = de_entities(ser_entities(entities))
135
+ return Final(
136
+ text=text,
137
+ entities=entities,
138
+ markup=markup,
139
+ preview=preview_flag(src),
140
+ text_changed=text_changed,
141
+ n_buttons=change.n_buttons if change else 0,
142
+ n_links=change.n_links if change else 0,
143
+ n_typed=change.n_typed if change else 0,
144
+ dropped=dropped,
145
+ n_post_links=n_post_links,
146
+ n_relinked=n_relinked,
147
+ rich=rich,
148
+ )
149
+
150
+
151
+ # ---------------------------------------------------------------------------- replies and pins
152
+ class ReplyParentMissing(RuntimeError):
153
+ """A post answers another post whose copy does not exist (yet): copying it now would lose the answer."""
154
+
155
+
156
+ def reply_parent(msg) -> Optional[int]:
157
+ """The message id a post answers (in the same channel), or None."""
158
+ h = getattr(msg, "reply_to", None)
159
+ if h is None or getattr(h, "reply_to_peer_id", None) is not None or getattr(h, "forum_topic", None):
160
+ return None
161
+ return getattr(h, "reply_to_msg_id", None) or None
162
+
163
+
164
+ def new_parent(msg, idmap: dict, seen: set) -> Optional[int]:
165
+ """The copy of the post `msg` answers. None when it answers nothing, or the post it answered is gone / outside
166
+ the range being copied. Raises ReplyParentMissing when that post was read in this run but has no copy."""
167
+ pid = reply_parent(msg)
168
+ if pid is None:
169
+ return None
170
+ if pid in idmap:
171
+ return idmap[pid]
172
+ if pid in seen:
173
+ raise ReplyParentMissing(f"post {msg.id} answers post {pid}, which has not been copied")
174
+ return None
175
+
176
+
177
+ def new_messages_from(result) -> list:
178
+ """The messages created by a send / forward request, oldest first."""
179
+ out = []
180
+ for u in getattr(result, "updates", None) or []:
181
+ if isinstance(u, (types.UpdateNewChannelMessage, types.UpdateNewMessage)):
182
+ out.append(u.message)
183
+ out.sort(key=lambda m: m.id)
184
+ return out
185
+
186
+
187
+ # ------------------------------------------------------ posts Telegram holds back (copyright strike ...)
188
+ SavedLookup = Callable[[list], Awaitable[dict]] # message ids -> {message id: the saved post of My posts}
189
+
190
+
191
+ def saved_lookup(db, channel_id: int) -> SavedLookup:
192
+ """How the copy loop and the plan look up what My posts saved of the posts of one channel."""
193
+
194
+ async def lookup(ids: list) -> dict:
195
+ return {p.message_id: p for p in await db.posts_at(channel_id, ids)}
196
+
197
+ return lookup
198
+
199
+
200
+ def usable_row(row) -> bool:
201
+ """A saved post that can take the place of a restricted post: it has something to post, and what it says is not
202
+ Telegram's notice (a saved copy that an older version made from a restricted post can hold the notice)."""
203
+ if row is None:
204
+ return False
205
+ text = row.text or ""
206
+ if is_placeholder_text(text):
207
+ return False
208
+ return bool(text.strip() or row.media_file_id)
209
+
210
+
211
+ def copy_source(unit: list, rows: dict, *, restricted: Optional[str] = None, use_saved: bool = False) -> tuple:
212
+ """Where the copy of this post (or album) comes from -> (source, why).
213
+
214
+ "live" - as Telegram hands the post out: nothing restricts it, or Telegram restricts it but still hands out the
215
+ post itself and there is no saved copy to use instead;
216
+ "saved" - from what My posts saved of it: Telegram restricts the channel (`restricted`) or the post (a copyright
217
+ strike) and My posts has every part of it. Only when `use_saved` (/shift) - the saved copy wins even when
218
+ Telegram's version still looks intact, because that is the owner's rule for a struck channel;
219
+ "skip" - not copied: what Telegram hands out is its notice - or nothing - and My posts can't take over.
220
+
221
+ `why` is Telegram's own wording about the restriction, None when nothing restricts the post."""
222
+ marked = next((w for w in (message_restriction(m) for m in unit) if w), None)
223
+ why = marked or restricted
224
+ if why is None:
225
+ return "live", None
226
+ if use_saved and all(usable_row(rows.get(m.id)) for m in unit):
227
+ return "saved", why
228
+ for m in unit:
229
+ live = m.message or ""
230
+ if is_placeholder_text(live) or (
231
+ not live.strip() and getattr(m, "media", None) is None and rich_for(m) is None
232
+ ):
233
+ return "skip", why
234
+ return "live", why
235
+
236
+
237
+ def stand_in(m, row):
238
+ """A copy of the live message `m` that shows what My posts saved for it - text, formatting, buttons, media. It takes
239
+ the place of a post Telegram holds back (the live message keeps what Telegram still tells: id, album, reply)."""
240
+ s = copy.copy(m)
241
+ s.message = row.text or ""
242
+ s.entities = de_entities(row.entities)
243
+ s.rich_message = None # what it shows is what My posts saved ...
244
+ s.rich_saved = rich_of(row) # ... which is a rich message when the saved post is one
245
+ s.reply_markup = build_markup(row.buttons)
246
+ s.media = None
247
+ s.saved_ref = None # the saved media reference (resend_saved may need it again without its file reference)
248
+ if row.media_file_id:
249
+ try:
250
+ s.media = media_from_ref(row.media_file_id)
251
+ s.saved_ref = row.media_file_id
252
+ except ValueError: # a reference that can't be read: the post goes out without media
253
+ log.warning("the saved media of post %s can't be read", m.id)
254
+ if s.media is None and row.link_preview:
255
+ s.media = types.MessageMediaWebPage(webpage=types.WebPageEmpty(id=0))
256
+ return s
257
+
258
+
259
+ def stand_ins(unit: list, rows: dict) -> Optional[list]:
260
+ """The saved copies that stand in for a restricted post, or None when My posts does not have all of them (or one of
261
+ them has nothing to post, or holds only Telegram's notice)."""
262
+ out = []
263
+ for m in unit:
264
+ row = rows.get(m.id)
265
+ if not usable_row(row):
266
+ return None
267
+ out.append(stand_in(m, row))
268
+ return out
269
+
270
+
271
+ FILE_MEDIA = (types.MessageMediaPhoto, types.MessageMediaDocument) # a photo, video, document, voice, sticker ...
272
+
273
+
274
+ def has_file(m) -> bool:
275
+ """The post carries a file. A link preview, a poll, a location or a contact is not a file."""
276
+ return isinstance(getattr(m, "media", None), FILE_MEDIA)
277
+
278
+
279
+ def without_files(unit: list) -> tuple:
280
+ """/shift --no-media: the posts of `unit` as they look without their files -> (those that still have a text, the
281
+ number of files left out). A post that was only a file has nothing left to post and is dropped."""
282
+ out, lost = [], 0
283
+ for m in unit:
284
+ c = m
285
+ if has_file(m):
286
+ c = copy.copy(m)
287
+ c.media, c.saved_ref, c.invert_media = None, None, None
288
+ lost += 1
289
+ if (c.message or "").strip() or rich_for(c) is not None:
290
+ out.append(c)
291
+ return out, lost
292
+
293
+
294
+ async def single_posts(units: AsyncIterator[list]) -> AsyncIterator[list]:
295
+ """/shift --no-media: an album can't be rebuilt without its pictures, so every message of it is a post of its own."""
296
+ async for unit in units:
297
+ for m in unit:
298
+ yield [m]
299
+
300
+
301
+ def saved_message(row, channel_id: int):
302
+ """A post built from its saved copy alone, for a channel that can't be read at all. Only the saved parts exist: no
303
+ album, no reply, no pin."""
304
+ base = types.Message(
305
+ id=row.message_id, peer_id=types.PeerChannel(channel_id), date=row.sent_at or row.created_at, message=""
306
+ )
307
+ return stand_in(base, row)
308
+
309
+
310
+ def saved_rows_between(rows: list, first: Optional[int], last: Optional[int]) -> list:
311
+ """The saved posts (oldest first, one per message id) that can be posted - they have something to post that is not
312
+ Telegram's notice - between two message ids."""
313
+ out, seen = [], set()
314
+ for row in sorted(rows, key=lambda r: (r.message_id or 0, r.id)):
315
+ mid = row.message_id
316
+ if mid is None or mid in seen or (first and mid < first) or (last and mid > last):
317
+ continue
318
+ if usable_row(row):
319
+ seen.add(mid)
320
+ out.append(row)
321
+ return out
322
+
323
+
324
+ async def saved_units(db, channel_id: int, first: int, last: int) -> AsyncIterator[list]:
325
+ """The saved posts of a channel between two message ids, oldest first - each one a unit of its own."""
326
+ for row in saved_rows_between(await db.sent_posts_from(channel_id, first), first, last):
327
+ yield [saved_message(row, channel_id)]
328
+
329
+
330
+ # ------------------------------------------------------------------------------- planning
331
+ @dataclass
332
+ class RepostPlan:
333
+ channel: Any
334
+ first: int = 1
335
+ last: int = 0 # newest existing message id when the plan was made
336
+ scanned: int = 0
337
+ units: int = 0 # posts (an album counts once)
338
+ messages: int = 0
339
+ albums: int = 0
340
+ text: int = 0
341
+ media: int = 0
342
+ polls: int = 0
343
+ other: int = 0
344
+ service: int = 0
345
+ link_posts: int = 0
346
+ n_buttons: int = 0
347
+ n_links: int = 0
348
+ n_typed: int = 0
349
+ dropped_posts: int = 0
350
+ post_link_posts: int = 0 # posts with a link to another post of this channel
351
+ post_links: int = 0
352
+ pinned: int = 0 # pinned posts (their copies get pinned)
353
+ replies: int = 0 # posts that answer another post
354
+ held_saved: int = 0 # restricted posts that are copied from what My posts saved of them (counted in units)
355
+ held_skipped: int = 0 # restricted posts that can't be copied: only Telegram's notice is left (not counted in units)
356
+ live_restricted: int = 0 # restricted posts without a saved copy that are copied as Telegram hands them out
357
+ no_media: bool = False # /shift --no-media: the files are left out
358
+ files_left_out: int = 0 # ... posts that are copied as text without their file (counted in units)
359
+ file_only: int = 0 # ... posts that are only a file: nothing to copy (not counted in units)
360
+ held_why: Optional[str] = None # what Telegram says about them
361
+ channel_restricted: Optional[str] = None # what Telegram says when it restricts the whole channel
362
+ from_db: bool = False # the channel can't be read: the plan (and the copy) is made from My posts alone
363
+ unreadable: Optional[str] = None # ... because of this
364
+ partial: bool = False
365
+ error: Optional[str] = None
366
+
367
+ def eta_seconds(self, delay: float) -> int:
368
+ return int(self.units * (delay + 1.0))
369
+
370
+
371
+ def tally(plan: RepostPlan, m, opts: RepostOptions, links: PostLinks) -> None:
372
+ """Count one message (as it will be copied) into the plan."""
373
+ plan.messages += 1
374
+ media = m.media
375
+ if media is None or isinstance(media, types.MessageMediaWebPage):
376
+ plan.text += 1
377
+ elif isinstance(media, (types.MessageMediaPhoto, types.MessageMediaDocument)):
378
+ plan.media += 1
379
+ elif isinstance(media, types.MessageMediaPoll):
380
+ plan.polls += 1
381
+ else:
382
+ plan.other += 1
383
+ f = final_state(m, opts, links)
384
+ if f.n_buttons or f.n_links or f.n_typed:
385
+ plan.link_posts += 1
386
+ plan.n_buttons += f.n_buttons
387
+ plan.n_links += f.n_links
388
+ plan.n_typed += f.n_typed
389
+ if f.dropped:
390
+ plan.dropped_posts += 1
391
+ if f.n_post_links:
392
+ plan.post_link_posts += 1
393
+ plan.post_links += f.n_post_links
394
+ if getattr(m, "pinned", False):
395
+ plan.pinned += 1
396
+ if reply_parent(m) is not None:
397
+ plan.replies += 1
398
+
399
+
400
+ def plan_from_saved(
401
+ ch, rows: list, opts: RepostOptions, *, first_id=None, last_id=None, unreadable=None, no_media: bool = False
402
+ ) -> RepostPlan:
403
+ """The plan of a copy made from My posts alone (the channel can't be read): one post per saved message."""
404
+ plan = RepostPlan(
405
+ channel=ch, partial=bool(first_id or last_id), from_db=True, unreadable=unreadable, no_media=no_media
406
+ )
407
+ links = PostLinks.for_channel(ch)
408
+ chosen = saved_rows_between(rows, first_id, last_id)
409
+ for row in chosen:
410
+ m = saved_message(row, ch.id)
411
+ if no_media:
412
+ kept, lost = without_files([m])
413
+ if not kept:
414
+ plan.file_only += 1
415
+ continue
416
+ m, plan.files_left_out = kept[0], plan.files_left_out + lost
417
+ plan.units += 1
418
+ tally(plan, m, opts, links)
419
+ if chosen:
420
+ plan.first, plan.last = chosen[0].message_id, chosen[-1].message_id
421
+ plan.scanned = plan.last
422
+ else:
423
+ plan.first, plan.last = first_id or 1, last_id or 0
424
+ if not plan.units:
425
+ plan.error = "There is nothing to copy."
426
+ if plan.file_only:
427
+ plan.error = "Every saved post in this range is only a file, so without files there is nothing to copy."
428
+ return plan
429
+
430
+
431
+ async def find_last_id(client, peer, top: int) -> Optional[int]:
432
+ """Newest existing message id, searching backwards from the channel counter."""
433
+ a = top
434
+ for _ in range(300):
435
+ lo = max(1, a - CHUNK + 1)
436
+ msgs = await fetch_messages(client, peer, list(range(lo, a + 1)))
437
+ ids = [m.id for m in msgs if m is not None and not isinstance(m, types.MessageEmpty)]
438
+ if ids:
439
+ return max(ids)
440
+ if lo == 1:
441
+ return None
442
+ a = lo - 1
443
+ return None
444
+
445
+
446
+ async def plan_repost(
447
+ client,
448
+ ch,
449
+ opts: RepostOptions,
450
+ *,
451
+ progress: Optional[Callable[[RepostPlan], Awaitable[None]]] = None,
452
+ first_id: Optional[int] = None,
453
+ last_id: Optional[int] = None,
454
+ saved: Optional[SavedLookup] = None,
455
+ use_saved: bool = False,
456
+ no_media: bool = False,
457
+ ) -> RepostPlan:
458
+ """Read the channel and count what a copy would do. first_id / last_id limit the range (used by /shift).
459
+ `saved` looks up My posts' copies of the channel's posts; with `use_saved` a post Telegram holds back is counted as
460
+ the saved post it will be copied from (/shift), without it such a post is left out (/repost). With `no_media` the
461
+ files are left out of the copies (/shift --no-media): a post that is only a file has nothing left to copy."""
462
+ peer = peer_of(ch)
463
+ plan = RepostPlan(channel=ch, partial=bool(opts.last), no_media=no_media)
464
+ try:
465
+ top, plan.channel_restricted, _ = await probe_channel(client, peer)
466
+ except Exception as e: # the counter is only a help: without it the ids are read until nothing more turns up
467
+ log.info("could not read channel counter: %s", e)
468
+ top = None
469
+ first = 1
470
+ if opts.last:
471
+ if top is None:
472
+ plan.error = "I can't tell which post is the newest, so --last can't be used here."
473
+ return plan
474
+ newest = await find_last_id(client, peer, top)
475
+ if newest is None:
476
+ plan.error = "The channel has no posts."
477
+ return plan
478
+ first, top = max(1, newest - opts.last + 1), newest
479
+ if first_id:
480
+ first = max(first, first_id)
481
+ plan.partial = True
482
+ if last_id:
483
+ top = last_id if top is None else min(top, last_id)
484
+ plan.partial = True
485
+ plan.first = first
486
+ links = PostLinks.for_channel(ch)
487
+ a, empty_run, prev_gid, max_seen = first, 0, None, 0
488
+ while True:
489
+ if top is not None and a > top:
490
+ break
491
+ hi = a + CHUNK - 1 if top is None else min(a + CHUNK - 1, top)
492
+ found = False
493
+ rows = await saved(list(range(a, hi + 1))) if saved else {}
494
+ for m in await fetch_messages(client, peer, list(range(a, hi + 1))):
495
+ if m is None or isinstance(m, types.MessageEmpty):
496
+ continue
497
+ found = True
498
+ max_seen = max(max_seen, m.id)
499
+ if isinstance(m, types.MessageService):
500
+ plan.service += 1
501
+ continue
502
+ gid = getattr(m, "grouped_id", None)
503
+ new_unit = no_media or gid is None or gid != prev_gid # without files an album is a post per message
504
+ row = rows.get(m.id)
505
+ # a struck channel changes how /shift copies (My posts first); /repost copies as before, post by post
506
+ source, why = copy_source(
507
+ [m], rows, restricted=plan.channel_restricted if use_saved else None, use_saved=use_saved
508
+ )
509
+ if why:
510
+ plan.held_why = plan.held_why or why
511
+ if source == "skip":
512
+ plan.held_skipped += 1 if new_unit else 0 # nothing to copy it from
513
+ prev_gid = gid
514
+ continue
515
+ if source == "saved":
516
+ m = stand_in(m, row) # counted as the saved post it will be copied from
517
+ if no_media:
518
+ kept, lost = without_files([m])
519
+ if not kept: # nothing but a file: nothing to copy without it
520
+ plan.file_only += 1
521
+ prev_gid = gid
522
+ continue
523
+ m, plan.files_left_out = kept[0], plan.files_left_out + lost
524
+ if source == "saved":
525
+ plan.held_saved += 1 if new_unit else 0
526
+ elif why:
527
+ plan.live_restricted += 1 if new_unit else 0
528
+ if new_unit:
529
+ plan.units += 1
530
+ if gid is not None and not no_media:
531
+ plan.albums += 1
532
+ prev_gid = gid
533
+ tally(plan, m, opts, links)
534
+ plan.scanned = hi
535
+ if top is None:
536
+ empty_run = 0 if found else empty_run + 1
537
+ if empty_run >= FALLBACK_EMPTY_BATCHES:
538
+ break
539
+ if progress:
540
+ await progress(plan)
541
+ a = hi + 1
542
+ plan.last = max_seen
543
+ if not plan.units:
544
+ plan.error = "There is nothing to copy."
545
+ if plan.held_skipped:
546
+ plan.error = (
547
+ "Telegram holds back every post in this range (it shows a notice instead of the post) and My posts has "
548
+ "no saved copy of them, so there is nothing to copy."
549
+ )
550
+ elif plan.file_only:
551
+ plan.error = "Every post in this range is only a file, so without files there is nothing to copy."
552
+ return plan
553
+
554
+
555
+ # ---------------------------------------------------------------------------------- copying
556
+ async def iter_units(client, peer, first: int, last: int) -> AsyncIterator[list]:
557
+ """The posts between two ids, oldest first. An album is one unit (a list of messages)."""
558
+ group: list = []
559
+ a = first
560
+ while a <= last:
561
+ hi = min(a + CHUNK - 1, last)
562
+ for m in await fetch_messages(client, peer, list(range(a, hi + 1))):
563
+ if is_skippable(m):
564
+ continue
565
+ gid = getattr(m, "grouped_id", None)
566
+ if group and gid != group[0].grouped_id:
567
+ yield group
568
+ group = []
569
+ group.append(m)
570
+ if gid is None:
571
+ yield group
572
+ group = []
573
+ a = hi + 1
574
+ if group:
575
+ yield group
576
+
577
+
578
+ async def delete_ids(client, peer, ids: list) -> None:
579
+ if not ids:
580
+ return
581
+ try:
582
+ await flood_retry(lambda: client(functions.channels.DeleteMessagesRequest(channel=peer, id=list(ids))))
583
+ except errors.RPCError as e:
584
+ log.warning("could not remove messages %s: %s", ids, type(e).__name__)
585
+
586
+
587
+ async def forward_unit(client, src_peer, unit: list, dst_peer=None) -> list:
588
+ """Let Telegram copy the posts (no "forwarded from" header). `dst_peer` defaults to the same channel."""
589
+ ids = [m.id for m in unit]
590
+ to_peer = dst_peer if dst_peer is not None else src_peer
591
+ result = await flood_retry(
592
+ lambda: client(
593
+ functions.messages.ForwardMessagesRequest(
594
+ from_peer=src_peer, id=ids, to_peer=to_peer, silent=True, drop_author=True
595
+ )
596
+ )
597
+ )
598
+ return new_messages_from(result)
599
+
600
+
601
+ def _inverted(m) -> Optional[bool]:
602
+ return True if getattr(m, "invert_media", False) else None
603
+
604
+
605
+ def reply_header(reply_to: Optional[int]):
606
+ """The `reply_to` argument of the send requests: answer message `reply_to` of the same channel."""
607
+ return types.InputReplyToMessage(reply_to_msg_id=reply_to) if reply_to else None
608
+
609
+
610
+ async def resend_unit(client, peer, unit: list, finals: list, reply_to: Optional[int] = None) -> list:
611
+ """Rebuild a post from its parts (used when copying is not allowed, or the copy must differ from the original).
612
+ `reply_to`: message id (in the channel `peer`) the new post answers."""
613
+ reply = reply_header(reply_to)
614
+ sender = None
615
+ if len(unit) == 1 and getattr(finals[0], "rich", None) is not None:
616
+ rich_final = finals[0] # a rich message: Telegram builds it again from its blocks (or its HTML / Markdown)
617
+
618
+ async def send_rich_final():
619
+ return await with_rich(
620
+ rich_final.rich,
621
+ lambda inp: client(
622
+ functions.messages.SendMessageRequest(
623
+ peer=peer, message="", rich_message=inp, reply_markup=rich_final.markup, silent=True, reply_to=reply
624
+ )
625
+ ),
626
+ )
627
+
628
+ sender = send_rich_final
629
+ elif len(unit) > 1:
630
+ singles = [
631
+ types.InputSingleMedia(media=utils.get_input_media(m.media), message=f.text, entities=f.entities or None)
632
+ for m, f in zip(unit, finals)
633
+ ]
634
+
635
+ def make():
636
+ return functions.messages.SendMultiMediaRequest(
637
+ peer=peer, multi_media=singles, silent=True, invert_media=_inverted(unit[0]), reply_to=reply
638
+ )
639
+
640
+ else:
641
+ m, f = unit[0], finals[0]
642
+ if m.media is None or isinstance(m.media, types.MessageMediaWebPage):
643
+
644
+ def make():
645
+ return functions.messages.SendMessageRequest(
646
+ peer=peer,
647
+ message=f.text,
648
+ entities=f.entities or None,
649
+ reply_markup=f.markup,
650
+ no_webpage=True if f.preview is False else None,
651
+ invert_media=_inverted(m),
652
+ silent=True,
653
+ reply_to=reply,
654
+ )
655
+
656
+ else:
657
+ media = utils.get_input_media(m.media)
658
+
659
+ def make():
660
+ return functions.messages.SendMediaRequest(
661
+ peer=peer,
662
+ media=media,
663
+ message=f.text,
664
+ entities=f.entities or None,
665
+ reply_markup=f.markup,
666
+ invert_media=_inverted(m),
667
+ silent=True,
668
+ reply_to=reply,
669
+ )
670
+
671
+ result = await flood_retry(sender if sender is not None else (lambda: client(make())))
672
+ news = new_messages_from(result)
673
+ if len(news) != len(unit):
674
+ await delete_ids(client, peer, [n.id for n in news])
675
+ raise RuntimeError(f"Telegram created {len(news)} messages instead of {len(unit)}")
676
+ return news
677
+
678
+
679
+ @dataclass
680
+ class _State:
681
+ mode: str = "forward" # becomes "resend" when the channel forbids forwarding
682
+ forwarded: int = 0
683
+ rebuilt: int = 0
684
+ repaired: int = 0 # new posts whose buttons had to be set again after posting
685
+ replies: int = 0 # new posts created as an answer to the copy of the post the original answered
686
+ reply_lost: int = 0 # answers that could only be copied without the reply
687
+ from_saved: int = 0 # posts Telegram holds back that were rebuilt from their saved copy in My posts
688
+ media_lost: list = field(default_factory=list) # old ids of those that had to go out without their media
689
+
690
+
691
+ def is_pure(src, f: Final, reply_to: Optional[int] = None) -> bool:
692
+ """True when a server-side copy is already the final post: nothing to swap, no keyboard to rebuild and no
693
+ reply to set (a reply can only be given when a post is created)."""
694
+ return not f.text_changed and src.reply_markup is None and not reply_to
695
+
696
+
697
+ def _has_media(unit: list) -> bool:
698
+ return any(m.media is not None and not isinstance(m.media, types.MessageMediaWebPage) for m in unit)
699
+
700
+
701
+ def _without_reference(unit: list) -> list:
702
+ """The same saved posts with the file reference of their media left out (it may have expired)."""
703
+ out = []
704
+ for m in unit:
705
+ b = copy.copy(m)
706
+ if getattr(m, "saved_ref", None):
707
+ b.media = media_from_ref(m.saved_ref, blank_reference=True)
708
+ out.append(b)
709
+ return out
710
+
711
+
712
+ async def resend_saved(client, dst_peer, unit: list, finals: list, st: _State, reply_to: Optional[int] = None) -> list:
713
+ """Create the copies of posts that Telegram holds back, from the saved posts that stand in for them (stand_in).
714
+ Their media is sent from the saved reference: when Telegram says the reference is out of date it is tried without
715
+ it, and a single post whose text is saved goes out without its media when Telegram still refuses the file
716
+ (a file taken down for copyright is refused) - counted in st.media_lost."""
717
+ failure: Optional[BaseException] = None
718
+ for attempt in (unit, None):
719
+ if attempt is None:
720
+ if failure is None or not _has_media(unit):
721
+ break
722
+ attempt = _without_reference(unit)
723
+ try:
724
+ return await resend_unit(client, dst_peer, attempt, finals, reply_to)
725
+ except (TypeError, ValueError, errors.RPCError) as e:
726
+ if isinstance(e, errors.RPCError) and type(e).__name__ in FATAL:
727
+ raise
728
+ failure = failure or e
729
+ if not _has_media(unit):
730
+ raise
731
+ if len(unit) == 1 and (finals[0].text or "").strip():
732
+ unit[0].media = None # what goes out now has no media, and neither has its entry in My posts
733
+ news = await resend_unit(client, dst_peer, unit, finals, reply_to)
734
+ st.media_lost.append(unit[0].id)
735
+ return news
736
+ raise failure # type: ignore[misc]
737
+
738
+
739
+ async def copy_unit(
740
+ client,
741
+ peer,
742
+ unit: list,
743
+ finals: list,
744
+ st: _State,
745
+ reply_to: Optional[int] = None,
746
+ dst_peer=None,
747
+ *,
748
+ from_saved: bool = False,
749
+ no_forward: bool = False,
750
+ ) -> list:
751
+ """Create the copy of one post (or album) at the end of `dst_peer` (default: the same channel `peer`).
752
+ `from_saved`: the posts in `unit` are saved copies standing in for posts Telegram restricts - never forwarded.
753
+ `no_forward`: Telegram restricts these posts and refuses to copy them itself: they are rebuilt from their parts."""
754
+ dst = dst_peer if dst_peer is not None else peer
755
+ if from_saved:
756
+ news = await resend_saved(client, dst, unit, finals, st, reply_to)
757
+ st.rebuilt += 1
758
+ st.from_saved += 1
759
+ if reply_to:
760
+ st.replies += 1
761
+ return news
762
+ pure = all(is_pure(m, f, reply_to) for m, f in zip(unit, finals))
763
+ if st.mode == "forward" and pure and not no_forward:
764
+ try:
765
+ news = await forward_unit(client, peer, unit, dst)
766
+ if len(news) == len(unit):
767
+ st.forwarded += 1
768
+ return news
769
+ await delete_ids(client, dst, [n.id for n in news])
770
+ except errors.ChatForwardsRestrictedError:
771
+ st.mode = "resend"
772
+ log.info("this channel restricts forwarding - rebuilding posts from their parts instead")
773
+ except errors.RPCError as e:
774
+ if type(e).__name__ in FATAL:
775
+ raise
776
+ log.info("copy failed (%s) - rebuilding the post", type(e).__name__)
777
+ try:
778
+ news = await resend_unit(client, dst, unit, finals, reply_to)
779
+ except (TypeError, ValueError, errors.RPCError) as e:
780
+ # A kind of media a post cannot be rebuilt from (or a reply Telegram refuses). If only the reply made a
781
+ # rebuild necessary, a plain copy by Telegram still works - without the reply.
782
+ if isinstance(e, errors.RPCError) and type(e).__name__ in FATAL:
783
+ raise
784
+ if reply_to and st.mode == "forward" and not no_forward and all(is_pure(m, f) for m, f in zip(unit, finals)):
785
+ news = await forward_unit(client, peer, unit, dst)
786
+ if len(news) != len(unit):
787
+ await delete_ids(client, dst, [n.id for n in news])
788
+ raise
789
+ st.reply_lost += 1
790
+ st.forwarded += 1
791
+ return news
792
+ raise
793
+ st.rebuilt += 1
794
+ if reply_to:
795
+ st.replies += 1
796
+ return news
797
+
798
+
799
+ async def settle_buttons(client, peer, finals: list, news: list, st: _State, *, pause: float) -> None:
800
+ """Read the new posts back: each must show the link buttons it should. Repairs it, or removes the copies."""
801
+ for f, new in zip(finals, news):
802
+ if not link_urls(f.markup):
803
+ continue
804
+ try:
805
+ how = await ensure_markup(client, peer, new.id, f.markup, pause=pause)
806
+ except errors.RPCError as e:
807
+ await delete_ids(client, peer, [n.id for n in news])
808
+ if type(e).__name__ in FATAL:
809
+ raise
810
+ raise ButtonsNotShown(f"could not set the buttons ({type(e).__name__})") from e
811
+ except (ButtonsNotShown, LookupError) as e:
812
+ await delete_ids(client, peer, [n.id for n in news])
813
+ raise ButtonsNotShown(str(e)) from e
814
+ if how != "fine":
815
+ st.repaired += 1
816
+
817
+
818
+ @dataclass
819
+ class FinalizeResult:
820
+ """The finishing touches after the copies exist: links to other posts, pins."""
821
+
822
+ checked: int = 0 # copies read back
823
+ relinked: int = 0 # copies whose links to other posts now point at the new copies
824
+ links: int = 0 # links changed in total
825
+ missing: int = 0 # copies that do not exist any more
826
+ failed: list = field(default_factory=list) # [(message id, error name)]
827
+ pin_wanted: int = 0 # copies of pinned posts that still had to be pinned
828
+ pinned: int = 0
829
+ pin_error: Optional[str] = None
830
+ aborted: Optional[str] = None
831
+ stopped: bool = False
832
+
833
+
834
+ @dataclass
835
+ class RepostResult:
836
+ copied_units: int = 0
837
+ copied_messages: int = 0
838
+ skipped_done: int = 0
839
+ failed: list = field(default_factory=list) # [(first old id, error name)]
840
+ forwarded: int = 0
841
+ rebuilt: int = 0
842
+ repaired: int = 0
843
+ replies: int = 0 # copies created as an answer to the copy of the post the original answered
844
+ reply_lost: int = 0 # answers that could only be copied without the reply
845
+ reply_dropped: int = 0 # answers to a post that no longer exists (nothing to answer)
846
+ from_saved: int = 0 # restricted posts that were copied from their saved copy in My posts
847
+ media_lost: list = field(default_factory=list) # ... of which these (old ids) went out without their media
848
+ held_back: list = field(default_factory=list) # posts that were not copied: only Telegram's notice was left (old id)
849
+ held_why: Optional[str] = None # what Telegram says about the restricted posts
850
+ live_restricted: int = 0 # restricted posts without a saved copy, copied as Telegram hands them out
851
+ no_media: bool = False # /shift --no-media: no file was copied
852
+ files_left_out: int = 0 # ... posts that were copied as text, without their file
853
+ file_only: list = field(default_factory=list) # ... posts that are only a file: nothing to copy (old id)
854
+ used_saved: bool = False # the run could take restricted posts from My posts (/shift)
855
+ from_db: bool = False # the channel can't be read: every post was copied from My posts alone
856
+ checked: int = 0 # new posts that were read back to see whether Telegram itself hides them
857
+ hidden: list = field(default_factory=list) # [(old id, had media)] new posts Telegram itself hides (restriction mark)
858
+ hidden_why: Optional[str] = None # what Telegram says about them
859
+ dst_restricted: Optional[str] = None # what Telegram says about the destination channel (when copies were hidden)
860
+ hidden_stop: bool = False # the run stopped by itself: Telegram hides every copy it read back
861
+ aborted: Optional[str] = None
862
+ stopped: bool = False
863
+ first_new: Optional[int] = None
864
+ last_new: Optional[int] = None
865
+ phase: str = "copy" # copy | finish | profile | links
866
+ final: Optional[FinalizeResult] = None
867
+ final_error: Optional[str] = None
868
+ cross: Optional[CrossResult] = None # links to the old posts in ALL connected channels, pointed at the copies
869
+ cross_error: Optional[str] = None
870
+ profile: Any = None # /shift -all: what happened to the name, description and photo (profile_copy.ProfileResult)
871
+ profile_error: Optional[str] = None
872
+
873
+
874
+ def _rows(unit: list, finals: list, news: list) -> list:
875
+ rows = []
876
+ for src, f, new in zip(unit, finals, news):
877
+ kind = classify_media(src)
878
+ ref = (media_ref(new) or media_ref(src)) if kind else None
879
+ rows.append(
880
+ {
881
+ "old_id": src.id,
882
+ "new_id": new.id,
883
+ "post": {
884
+ "text": plain_of(f.rich) if f.rich is not None else f.text,
885
+ "entities": [rich_entry(f.rich)] if f.rich is not None else ser_entities(f.entities),
886
+ "buttons": ser_markup(f.markup),
887
+ "media_kind": kind,
888
+ "media_file_id": ref,
889
+ "link_preview": bool(f.preview),
890
+ },
891
+ }
892
+ )
893
+ return rows
894
+
895
+
896
+ CHECK_FIRST = 3 # the first copies of any run are read back ...
897
+ CHECK_EVERY = 10 # ... then every tenth (all of them when Telegram restricts the source)
898
+ STOP_IF_HIDDEN = 3 # /shift stops when Telegram hides this many new copies and not one of those read back is shown
899
+
900
+
901
+ async def check_copies(client, dst_peer, unit: list, news: list, res: RepostResult) -> None:
902
+ """Read the new posts back: does TELEGRAM itself hide them (a restriction mark, or its notice as the text)? That
903
+ is not the bot copying a notice - Telegram restricts the new post as well, usually because of a file or a link in
904
+ it. What is found goes into `res` (checked, hidden, hidden_why). Never fails the copy: it is only a look."""
905
+ try:
906
+ got = await fetch_messages(client, dst_peer, [n.id for n in news])
907
+ except Exception as e: # a look that fails is not a failed copy (the post exists and is registered already)
908
+ log.info("could not read the new posts back: %s", type(e).__name__)
909
+ return
910
+ for old, new in zip(unit, got):
911
+ if is_skippable(new):
912
+ continue
913
+ res.checked += 1
914
+ why = message_restriction(new)
915
+ if why:
916
+ res.hidden.append((old.id, _has_media([old])))
917
+ res.hidden_why = res.hidden_why or why
918
+
919
+
920
+ @dataclass
921
+ class CopyJob:
922
+ """Everything the copy loop needs to know; /repost and /shift each fill it in their own way."""
923
+
924
+ src_peer: Any
925
+ dst_peer: Any # the same as src_peer for /repost
926
+ opts: RepostOptions
927
+ links: PostLinks # links.ids is `idmap`: old message id -> id of its copy, grows as we go
928
+ first_id: int
929
+ last_id: int
930
+ done: set # old ids that already have a copy
931
+ idmap: dict
932
+ record: Callable[[list], Awaitable[None]] # saves [{old_id, new_id, post}] (and registers the posts)
933
+ saved: Optional[SavedLookup] = None # what My posts saved of the source's posts
934
+ use_saved: bool = False # a post Telegram holds back is rebuilt from its saved copy (otherwise it is left out)
935
+ units: Optional[Callable[[], AsyncIterator[list]]] = None # where the posts come from (default: read the channel)
936
+ from_db: bool = False # `units` are saved posts: they are all rebuilt, none is read from Telegram
937
+ restricted: Optional[str] = None # what Telegram says about the source channel itself (a copyright strike), if anything
938
+ no_media: bool = False # the copies get no files: text, formatting and buttons only (/shift --no-media)
939
+ stop_if_hidden: int = 0 # stop when this many copies were read back and Telegram hides every one (0: never)
940
+
941
+
942
+ async def copy_loop(
943
+ client,
944
+ job: CopyJob,
945
+ *,
946
+ delay: float = 1.2,
947
+ progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None,
948
+ should_stop: Optional[Callable[[], bool]] = None,
949
+ settle_pause: float = 0.7,
950
+ ) -> RepostResult:
951
+ """Copy the posts first_id..last_id of `job.src_peer` to the end of `job.dst_peer`, in order.
952
+ Safe to run again to continue: posts in `job.done` are skipped."""
953
+ src, dst = job.src_peer, job.dst_peer
954
+ seen: set = set() # old ids read in this run (a reply to one of them needs its copy)
955
+ res, st, streak = RepostResult(used_saved=job.use_saved or job.from_db, from_db=job.from_db), _State(), 0
956
+ res.no_media = job.no_media
957
+ units = job.units() if job.units is not None else iter_units(client, src, job.first_id, job.last_id)
958
+ if job.no_media:
959
+ units = single_posts(units)
960
+ async for unit in units:
961
+ if should_stop and should_stop():
962
+ res.stopped = True
963
+ break
964
+ ids = [m.id for m in unit]
965
+ seen.update(ids)
966
+ if all(i in job.done for i in ids):
967
+ res.skipped_done += 1
968
+ continue
969
+ rows = await job.saved(ids) if (job.saved and not job.from_db) else {}
970
+ if job.from_db:
971
+ source, why = "saved", None
972
+ else:
973
+ source, why = copy_source(unit, rows, restricted=job.restricted, use_saved=job.use_saved)
974
+ if why: # Telegram restricts this post (or the whole channel): what it hands out now is not trusted
975
+ res.held_why = res.held_why or why
976
+ from_saved = job.from_db # saved posts already
977
+ standing = None
978
+ if source == "saved" and not job.from_db:
979
+ standing = stand_ins(unit, rows)
980
+ if standing is None:
981
+ source = "skip"
982
+ if source == "skip":
983
+ log.info("post %s: Telegram shows only its notice (%s) and My posts has no saved copy to use", ids[0], why)
984
+ res.held_back.append(ids[0])
985
+ continue
986
+ if standing is not None:
987
+ unit, from_saved = standing, True
988
+ no_forward, left_out = bool(why), 0
989
+ if job.no_media: # the copy is the text with its formatting and buttons; its file stays where it is
990
+ unit, left_out = without_files(unit)
991
+ if not unit: # nothing but a file: there is nothing to post without it, and nothing waits for it
992
+ res.file_only.append(ids[0])
993
+ seen.difference_update(ids)
994
+ continue
995
+ no_forward = no_forward or bool(left_out) # a copy by Telegram would carry the file
996
+ finals = [final_state(m, job.opts, job.links) for m in unit]
997
+ if any(is_placeholder_text(f.text) for f in finals): # Telegram's notice is never posted, whatever it came from
998
+ log.info("post %s: its text is Telegram's notice - not copied", ids[0])
999
+ res.held_back.append(ids[0])
1000
+ res.held_why = res.held_why or PLACEHOLDER_NOTE
1001
+ continue
1002
+ try:
1003
+ reply_to = new_parent(unit[0], job.idmap, seen)
1004
+ news = await copy_unit(
1005
+ client, src, unit, finals, st, reply_to, dst, from_saved=from_saved, no_forward=no_forward
1006
+ )
1007
+ await settle_buttons(client, dst, finals, news, st, pause=settle_pause)
1008
+ except Exception as e: # one bad post must not stop the others
1009
+ name = type(e).__name__
1010
+ log.warning("copying %s failed: %s %s", ids, name, e)
1011
+ res.failed.append((ids[0], name))
1012
+ streak += 1
1013
+ if name in FATAL or streak >= ABORT_AFTER:
1014
+ res.aborted = name
1015
+ break
1016
+ await asyncio.sleep(delay)
1017
+ continue
1018
+ try:
1019
+ await job.record(_rows(unit, finals, news))
1020
+ except Exception as e: # keep the channel and the database consistent
1021
+ log.exception("could not save the copy of %s", ids)
1022
+ await delete_ids(client, dst, [n.id for n in news])
1023
+ res.failed.append((ids[0], type(e).__name__))
1024
+ res.aborted = type(e).__name__
1025
+ break
1026
+ streak = 0
1027
+ job.done.update(ids)
1028
+ for old, new in zip(unit, news):
1029
+ job.idmap[old.id] = new.id
1030
+ if reply_parent(unit[0]) is not None and reply_to is None:
1031
+ res.reply_dropped += 1
1032
+ if why and not from_saved:
1033
+ res.live_restricted += 1
1034
+ res.files_left_out += left_out
1035
+ if why or res.copied_units < CHECK_FIRST or res.copied_units % CHECK_EVERY == 0:
1036
+ await check_copies(client, dst, unit, news, res)
1037
+ res.copied_units += 1
1038
+ res.copied_messages += len(unit)
1039
+ res.first_new = res.first_new or news[0].id
1040
+ res.last_new = news[-1].id
1041
+ if progress:
1042
+ await progress(res)
1043
+ if job.stop_if_hidden and res.checked >= job.stop_if_hidden and len(res.hidden) == res.checked:
1044
+ log.info("Telegram hides every copy read back (%s): stopping", res.checked)
1045
+ res.stopped = res.hidden_stop = True # more copies would only be more posts that nobody can see
1046
+ break
1047
+ await asyncio.sleep(delay)
1048
+ if res.hidden: # Telegram hides copies: is the destination itself restricted too?
1049
+ try:
1050
+ _top, res.dst_restricted, _err = await probe_channel(client, dst)
1051
+ except Exception: # only an extra for the report
1052
+ log.debug("could not ask Telegram about the destination channel", exc_info=True)
1053
+ res.forwarded, res.rebuilt, res.repaired = st.forwarded, st.rebuilt, st.repaired
1054
+ res.replies, res.reply_lost = st.replies, st.reply_lost
1055
+ res.from_saved, res.media_lost = st.from_saved, st.media_lost
1056
+ return res
1057
+
1058
+
1059
+ async def run_repost(
1060
+ client,
1061
+ db,
1062
+ ch,
1063
+ mig,
1064
+ user_id: int,
1065
+ *,
1066
+ delay: float = 1.2,
1067
+ progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None,
1068
+ should_stop: Optional[Callable[[], bool]] = None,
1069
+ settle_pause: float = 0.7,
1070
+ ) -> RepostResult:
1071
+ """Copy the posts of migration `mig` (ids first_id..last_id) in order; safe to run again to continue.
1072
+
1073
+ When every post is copied (not stopped, no fatal error) the finishing touches follow: links to posts that were
1074
+ copied later are pointed at their copies, the copies of pinned posts are pinned, and then every connected channel
1075
+ is searched for links to the old posts (crosslinks.relink_after_repost)."""
1076
+ opts = RepostOptions(
1077
+ old=mig.old_username, new=mig.new_username, include_typed=mig.include_typed, include_posts=mig.include_posts
1078
+ )
1079
+ peer = peer_of(ch)
1080
+ idmap = dict(await db.migration_pairs(mid=mig.id, alive_only=False))
1081
+ job = CopyJob(
1082
+ src_peer=peer,
1083
+ dst_peer=peer,
1084
+ opts=opts,
1085
+ links=PostLinks.for_channel(ch, idmap),
1086
+ first_id=mig.first_id,
1087
+ last_id=mig.last_id,
1088
+ done=await db.migration_done_old_ids(mig.id),
1089
+ idmap=idmap,
1090
+ record=lambda rows: db.record_repost(mig.id, ch.id, rows, user_id),
1091
+ saved=saved_lookup(db, ch.id), # a post Telegram holds back is left alone (and so is not deleted)
1092
+ )
1093
+ res = await copy_loop(client, job, delay=delay, progress=progress, should_stop=should_stop, settle_pause=settle_pause)
1094
+ if not res.stopped and not res.aborted:
1095
+ res.phase = "finish"
1096
+ if progress:
1097
+ await progress(res)
1098
+ try:
1099
+ res.final = await finalize_repost(
1100
+ client, db, ch, mig, delay=delay, settle_pause=settle_pause, should_stop=should_stop
1101
+ )
1102
+ except Exception as e: # the copies are fine; only the finishing touches failed
1103
+ log.exception("finishing the repost (links, pins) failed")
1104
+ res.final_error = type(e).__name__
1105
+ if not (res.final is not None and res.final.stopped):
1106
+ res.phase = "links"
1107
+ res.cross = CrossResult()
1108
+
1109
+ async def watch(_cross) -> None:
1110
+ if progress:
1111
+ await progress(res)
1112
+
1113
+ if progress:
1114
+ await progress(res)
1115
+ try:
1116
+ await relink_after_repost(
1117
+ client, db, ch, mig, delay=delay, settle_pause=settle_pause, progress=watch,
1118
+ should_stop=should_stop, result=res.cross,
1119
+ )
1120
+ except Exception as e: # the copies are fine; only the links in the other channels were not updated
1121
+ log.exception("pointing the links of the other channels at the copies failed")
1122
+ res.cross_error = type(e).__name__
1123
+ return res
1124
+
1125
+
1126
+ # --------------------------------------------------------------------- links to copies, pins
1127
+ async def relink_copies(
1128
+ client,
1129
+ db,
1130
+ ch,
1131
+ ids: dict,
1132
+ targets: list,
1133
+ *,
1134
+ delay: float = 1.2,
1135
+ settle_pause: float = 0.7,
1136
+ dry_run: bool = False,
1137
+ progress: Optional[Callable[[FinalizeResult], Awaitable[None]]] = None,
1138
+ should_stop: Optional[Callable[[], bool]] = None,
1139
+ links: Optional[PostLinks] = None,
1140
+ ) -> FinalizeResult:
1141
+ """Point every link to a post of this channel at the copy of that post (`ids`: old message id -> new one).
1142
+
1143
+ `targets` are the message ids of `ch` to look at (the copies). Idempotent: a link that already points at a copy
1144
+ is left alone, because only OLD ids are replaced. With dry_run nothing is edited, the result only counts.
1145
+ `links` (optional) says which links to follow; the default is "links to posts of `ch` itself" (/repost)."""
1146
+ res = FinalizeResult()
1147
+ peer = peer_of(ch)
1148
+ links = links if links is not None else PostLinks.for_channel(ch, ids)
1149
+ targets = sorted(set(targets))
1150
+ streak, last_name = 0, None
1151
+ for i in range(0, len(targets), CHUNK):
1152
+ chunk = targets[i : i + CHUNK]
1153
+ for mid, m in zip(chunk, await fetch_messages(client, peer, chunk)):
1154
+ if is_skippable(m):
1155
+ res.missing += 1
1156
+ continue
1157
+ res.checked += 1
1158
+ rl = relink_message(m, links)
1159
+ if rl is None:
1160
+ continue
1161
+ if dry_run:
1162
+ res.relinked += 1
1163
+ res.links += rl.links
1164
+ continue
1165
+ if should_stop and should_stop():
1166
+ res.stopped = True
1167
+ return res
1168
+ rich = is_rich_message(m) # a rich message's text is blocks: only its buttons change, the text is not sent again
1169
+ try:
1170
+ if rich:
1171
+ await flood_retry(lambda: edit_raw(client, peer, m.id, markup=rl.markup))
1172
+ else:
1173
+ await flood_retry(
1174
+ lambda: edit_raw(
1175
+ client, peer, m.id, text=rl.text, entities=rl.entities, markup=rl.markup, preview=preview_flag(m)
1176
+ )
1177
+ )
1178
+ if link_urls(rl.markup):
1179
+ await ensure_markup(client, peer, m.id, rl.markup, pause=settle_pause)
1180
+ except errors.MessageNotModifiedError:
1181
+ continue
1182
+ except Exception as e: # one bad post must not stop the others
1183
+ name = type(e).__name__
1184
+ log.warning("could not update the links of %s: %s %s", m.id, name, e)
1185
+ res.failed.append((m.id, name))
1186
+ streak = streak + 1 if name == last_name else 1
1187
+ last_name = name
1188
+ if name in FATAL or streak >= ABORT_AFTER:
1189
+ res.aborted = name
1190
+ return res
1191
+ continue
1192
+ streak, last_name = 0, None
1193
+ res.relinked += 1
1194
+ res.links += rl.links
1195
+ try:
1196
+ saved = dict(buttons=ser_markup(rl.markup))
1197
+ if not rich:
1198
+ saved.update(text=rl.text, entities=ser_entities(rl.entities))
1199
+ await db.update_post_by_message(ch.id, m.id, **saved)
1200
+ except Exception: # the channel is right; the saved copy will be corrected by the next sync
1201
+ log.warning("could not save the new links of %s", m.id, exc_info=True)
1202
+ if progress:
1203
+ await progress(res)
1204
+ await asyncio.sleep(delay)
1205
+ return res
1206
+
1207
+
1208
+ async def pin_copies(client, ch, pairs: list, res: FinalizeResult, *, delay: float = 1.2) -> None:
1209
+ """Pin the copy of every post that is pinned among the originals (oldest first, so the newest pin is on top).
1210
+
1211
+ The "pinned a message" notices Telegram adds to the channel are deleted again right away."""
1212
+ peer = peer_of(ch)
1213
+ pairs = sorted(pairs)
1214
+ todo: list = []
1215
+ for i in range(0, len(pairs), CHUNK):
1216
+ chunk = pairs[i : i + CHUNK]
1217
+ olds = await fetch_messages(client, peer, [o for o, _ in chunk])
1218
+ news = await fetch_messages(client, peer, [n for _, n in chunk])
1219
+ for (_, new_id), src, cur in zip(chunk, olds, news):
1220
+ if is_skippable(src) or is_skippable(cur):
1221
+ continue
1222
+ if getattr(src, "pinned", False) and not getattr(cur, "pinned", False):
1223
+ todo.append(new_id)
1224
+ res.pin_wanted = len(todo)
1225
+ for new_id in todo:
1226
+ try:
1227
+ out = await flood_retry(
1228
+ lambda: client(functions.messages.UpdatePinnedMessageRequest(peer=peer, id=new_id, silent=True))
1229
+ )
1230
+ except errors.MessageNotModifiedError:
1231
+ continue # already pinned
1232
+ except errors.RPCError as e:
1233
+ res.pin_error = type(e).__name__
1234
+ return
1235
+ res.pinned += 1
1236
+ await delete_ids(client, peer, [m.id for m in new_messages_from(out) if isinstance(m, types.MessageService)])
1237
+ await asyncio.sleep(delay)
1238
+
1239
+
1240
+ async def finalize_repost(
1241
+ client,
1242
+ db,
1243
+ ch,
1244
+ mig,
1245
+ *,
1246
+ delay: float = 1.2,
1247
+ settle_pause: float = 0.7,
1248
+ progress: Optional[Callable[[FinalizeResult], Awaitable[None]]] = None,
1249
+ should_stop: Optional[Callable[[], bool]] = None,
1250
+ ) -> FinalizeResult:
1251
+ """After the copies exist: links that point at old posts get the copies' ids, copies of pinned posts get pinned."""
1252
+ pairs = sorted(await db.migration_pairs(mid=mig.id))
1253
+ res = await relink_copies(
1254
+ client, db, ch, dict(pairs), [n for _, n in pairs], delay=delay, settle_pause=settle_pause,
1255
+ progress=progress, should_stop=should_stop,
1256
+ )
1257
+ if not res.stopped and not res.aborted:
1258
+ await pin_copies(client, ch, pairs, res, delay=delay)
1259
+ return res
1260
+
1261
+
1262
+ # ----------------------------------------------------------------------------- deleting
1263
+ @dataclass
1264
+ class DeleteResult:
1265
+ deleted: int = 0
1266
+ by_userbot: int = 0 # of those, how many only the userbot could delete
1267
+ remaining: int = 0
1268
+ blocked: bool = False # some messages are still there although Telegram did not report an error
1269
+ error: Optional[str] = None # the bot's Telegram error that stopped the run
1270
+ fallback_error: Optional[str] = None # why the userbot could not help
1271
+ tried_userbot: bool = False
1272
+
1273
+
1274
+ async def gone_ids(client, peer, ids: list) -> set:
1275
+ """Which of `ids` no longer exist in the channel."""
1276
+ msgs = await fetch_messages(client, peer, ids)
1277
+ return {i for i, m in zip(ids, msgs) if m is None or isinstance(m, types.MessageEmpty)}
1278
+
1279
+
1280
+ @dataclass
1281
+ class BatchOutcome:
1282
+ gone: set = field(default_factory=set) # message ids that no longer exist afterwards
1283
+ bot_error: Optional[str] = None
1284
+ by_userbot: int = 0
1285
+ fallback_error: Optional[str] = None
1286
+ tried_userbot: bool = False
1287
+
1288
+
1289
+ async def delete_batch(client, peer, ids: list, fallback: Optional[Callable[[list], Awaitable[Any]]] = None) -> BatchOutcome:
1290
+ """Delete up to 100 messages: the bot tries first, the result is checked by reading the messages back, and
1291
+ whatever is still there goes to `fallback(ids)` (the userbot), followed by a second check."""
1292
+ out = BatchOutcome()
1293
+ try:
1294
+ await flood_retry(lambda: client(functions.channels.DeleteMessagesRequest(channel=peer, id=list(ids))))
1295
+ except errors.RPCError as e:
1296
+ out.bot_error = type(e).__name__
1297
+ out.gone = await gone_ids(client, peer, ids)
1298
+ left = [x for x in ids if x not in out.gone]
1299
+ if left and fallback is not None:
1300
+ out.tried_userbot = True
1301
+ try:
1302
+ await fallback(left)
1303
+ except Exception as e: # a userbot problem must not hide what the bot already did
1304
+ log.warning("the userbot could not delete %s message(s): %s", len(left), e)
1305
+ out.fallback_error = str(e) or type(e).__name__
1306
+ again = await gone_ids(client, peer, left)
1307
+ out.by_userbot = len(again)
1308
+ out.gone |= again
1309
+ return out
1310
+
1311
+
1312
+ async def delete_pending(
1313
+ client,
1314
+ peer,
1315
+ todo: list,
1316
+ mark: Callable[[list], Awaitable[None]],
1317
+ *,
1318
+ delay: float = 0.5,
1319
+ progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None,
1320
+ fallback: Optional[Callable[[list], Awaitable[Any]]] = None,
1321
+ ) -> DeleteResult:
1322
+ """Delete the messages `todo` (oldest first, 100 per request). `mark(ids)` records the ones that are gone.
1323
+
1324
+ The bot tries first and the result is always checked by reading the messages back. Whatever the bot could not
1325
+ delete (Telegram may refuse old posts) goes to `fallback(ids)` - the userbot - if there is one, and is checked
1326
+ again. A batch the bot cannot delete does not stop the run: newer posts may still be deletable."""
1327
+ res = DeleteResult()
1328
+ use_fallback = fallback
1329
+ for i in range(0, len(todo), 100):
1330
+ ids = todo[i : i + 100]
1331
+ out = await delete_batch(client, peer, ids, use_fallback)
1332
+ res.tried_userbot = res.tried_userbot or out.tried_userbot
1333
+ res.by_userbot += out.by_userbot
1334
+ if out.fallback_error:
1335
+ res.fallback_error = out.fallback_error
1336
+ use_fallback = None # it will not work for the next batches either
1337
+ left = [x for x in ids if x not in out.gone]
1338
+ if out.gone:
1339
+ await mark(sorted(out.gone))
1340
+ res.deleted += len(out.gone)
1341
+ if left and out.bot_error:
1342
+ res.error = res.error or out.bot_error # remembered for the report
1343
+ if out.bot_error in FATAL and use_fallback is None:
1344
+ break # e.g. no "Delete messages" right: the next batch would fail the same way
1345
+ if progress:
1346
+ await progress(res)
1347
+ await asyncio.sleep(delay)
1348
+ return res
1349
+
1350
+
1351
+ async def delete_copies(
1352
+ client,
1353
+ db,
1354
+ ch,
1355
+ mig,
1356
+ which: str,
1357
+ *,
1358
+ delay: float = 0.5,
1359
+ progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None,
1360
+ fallback: Optional[Callable[[list], Awaitable[Any]]] = None,
1361
+ ) -> DeleteResult:
1362
+ """which='old': remove the original posts; which='new': remove the copies (undo). Oldest first, 100 per request."""
1363
+ todo = await db.migration_pending_ids(mig.id, which, 1_000_000)
1364
+
1365
+ async def mark(ids: list) -> None:
1366
+ await db.mark_migration_deleted(mig.id, ch.id, which, ids)
1367
+
1368
+ res = await delete_pending(client, peer_of(ch), todo, mark, delay=delay, progress=progress, fallback=fallback)
1369
+ counts = await db.migration_counts(mig.id)
1370
+ res.remaining = counts["old_left"] if which == "old" else counts["new_left"]
1371
+ res.blocked = res.remaining > 0 and not res.error
1372
+ return res
app/restrictions.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What TELEGRAM does to a channel (not what an admin does): the copyright notice and its relatives.
2
+
3
+ A channel that gets a copyright strike shows "This message couldn't be displayed on your device due to copyright
4
+ infringement." in place of its posts. That is not an edit by an admin, so nothing here ever treats it as one: the sync
5
+ leaves My posts as saved, and the link fixer does not edit such posts.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from typing import Optional
11
+
12
+ from telethon import errors, functions
13
+
14
+ from .tgutil import explain_rpc, flood_retry
15
+
16
+ PLACEHOLDER_NOTE = "Telegram shows a notice instead of the post"
17
+
18
+ # "This message couldn't be displayed on your device due to copyright infringement." and its relatives
19
+ _NOTICE = re.compile(
20
+ r"^this (?:message|post|channel|media|content|file|video)\b.{0,80}?"
21
+ r"\b(?:can.?t|cannot|can not|couldn.?t|could not|isn.?t|is not|won.?t|will not)\b.{0,40}?"
22
+ r"\b(?:displayed|shown|viewed|available|accessible)\b.{0,160}$",
23
+ re.I,
24
+ )
25
+ _NOTICE_WHY = re.compile(r"copyright|infring|device|country|region|terms of service|violat|restrict|\blaw\b", re.I)
26
+
27
+
28
+ def norm_text(text: Optional[str]) -> str:
29
+ return " ".join((text or "").split())
30
+
31
+
32
+ def is_placeholder_text(text: Optional[str]) -> bool:
33
+ """The notice Telegram's apps show in place of a post it holds back (copyright, terms of service, region ...)."""
34
+ t = norm_text(text)
35
+ return 0 < len(t) <= 260 and bool(_NOTICE.match(t)) and bool(_NOTICE_WHY.search(t))
36
+
37
+
38
+ def restriction_of(obj) -> Optional[str]:
39
+ """What Telegram says about a restricted channel or message (its own words), or None when nothing is restricted."""
40
+ reasons = getattr(obj, "restriction_reason", None)
41
+ if reasons:
42
+ texts = [norm_text(str(getattr(r, "text", "") or getattr(r, "reason", "") or "")) for r in reasons]
43
+ return "; ".join(dict.fromkeys(t for t in texts if t))[:240] or "restricted by Telegram"
44
+ if getattr(obj, "restricted", None):
45
+ return "restricted by Telegram"
46
+ return None
47
+
48
+
49
+ def message_restriction(m, saved_text: Optional[str] = None) -> Optional[str]:
50
+ """Why this message must not be taken over as it looks now, or None. Telegram marks a message it holds back
51
+ (restriction_reason); some places hand out its notice as the text instead. `saved_text` is the saved copy's text: a
52
+ text that the saved copy already has is the owner's own wording, not a notice."""
53
+ why = restriction_of(m)
54
+ if why:
55
+ return why
56
+ live = m.message or ""
57
+ if is_placeholder_text(live) and (saved_text is None or norm_text(live) != norm_text(saved_text)):
58
+ return PLACEHOLDER_NOTE
59
+ return None
60
+
61
+
62
+ async def probe_channel(client, peer) -> tuple:
63
+ """(the channel's event counter, why Telegram restricts the channel or None, None) - or (None, None, why not).
64
+ The counter is never lower than the newest message id."""
65
+ try:
66
+ full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer)))
67
+ except errors.RPCError as e:
68
+ return None, None, explain_rpc(e)
69
+ pts = getattr(getattr(full, "full_chat", None), "pts", None)
70
+ if pts is None:
71
+ return None, None, "Telegram did not say how far the channel has come."
72
+ cid = getattr(peer, "channel_id", None)
73
+ why = None
74
+ for chat in getattr(full, "chats", None) or []:
75
+ if getattr(chat, "id", None) == cid:
76
+ why = restriction_of(chat)
77
+ return int(pts), why, None
app/richmsg.py ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Telegram rich messages: headings, lists, tables, details, math, maps, media blocks, buttons ...
2
+
3
+ A rich message is not text plus entities: it is a tree of blocks. Telegram builds that tree itself from HTML or Markdown
4
+ (InputRichMessageHTML / InputRichMessageMarkdown), so text typed in those languages is handed over unchanged - every block
5
+ and every formatting Telegram knows is supported without this bot having to know it. A rich message that is sent to the
6
+ bot natively (or forwarded to it) is kept block for block (InputRichMessage).
7
+
8
+ How the bot keeps one: as a single entry in the post's `entities` list - ``{"k": "rich", "f": "html" | "markdown" |
9
+ "blocks", "s": source, ...}`` - next to a plain-text version in `text` (for lists, panels and the like). Whatever sends or
10
+ edits a post looks for that entry with `rich_of`. No database change is needed, and exports, backups and the undo log carry
11
+ it like any other formatting.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import copy
17
+ import hashlib
18
+ import logging
19
+ import re
20
+ from dataclasses import dataclass, replace
21
+ from html.parser import HTMLParser
22
+ from types import SimpleNamespace
23
+ from typing import List, Optional
24
+
25
+ from telethon import errors, functions, types, utils
26
+ from telethon.tl.tlobject import TLObject
27
+
28
+ from .tgutil import _b64, _unb64, flood_retry
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+ KIND = "rich" # the "k" of the entry in a post's entities
33
+ MAX_SOURCE = 32768 # characters Telegram allows in a rich message (500 blocks, 16 levels and 50 media as well)
34
+
35
+
36
+ class RichError(ValueError):
37
+ """A rich message that can't be used; the text is safe to show to the owner."""
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Rich:
42
+ """A rich message as the bot keeps it."""
43
+
44
+ fmt: str # "html" | "markdown" (typed: Telegram reads it) | "blocks" (received: base64 of an InputRichMessage)
45
+ source: str
46
+ rtl: bool = False
47
+ noautolink: bool = False # links, @mentions, #tags ... in the text are not made clickable by Telegram
48
+ fp: Optional[str] = None # fingerprint of the blocks Telegram showed last time (what the sync compares)
49
+
50
+
51
+ def entry(r: Rich) -> dict:
52
+ """The entry that stands for `r` in a post's entities."""
53
+ e: dict = {"k": KIND, "f": r.fmt, "s": r.source}
54
+ if r.rtl:
55
+ e["r"] = 1
56
+ if r.noautolink:
57
+ e["n"] = 1
58
+ if r.fp:
59
+ e["p"] = r.fp
60
+ return e
61
+
62
+
63
+ def rich_of(obj) -> Optional[Rich]:
64
+ """The rich message a post (or anything with a post's `entities`) holds, or None."""
65
+ for d in getattr(obj, "entities", None) or []:
66
+ if isinstance(d, dict) and d.get("k") == KIND and d.get("f") in ("html", "markdown", "blocks") and d.get("s"):
67
+ return Rich(d["f"], d["s"], bool(d.get("r")), bool(d.get("n")), d.get("p") or None)
68
+ return None
69
+
70
+
71
+ def is_rich(obj) -> bool:
72
+ return rich_of(obj) is not None
73
+
74
+
75
+ def real_entities(entities) -> list:
76
+ """The formatting entries of a stored entities list, without the rich message's."""
77
+ return [d for d in entities or [] if not (isinstance(d, dict) and d.get("k") == KIND)]
78
+
79
+
80
+ # ------------------------------------------------------------------------------------ what Telegram takes
81
+ def to_input(r: Rich):
82
+ """The InputRichMessage* object to send for `r`."""
83
+ flags = dict(rtl=True if r.rtl else None, noautolink=True if r.noautolink else None)
84
+ if r.fmt == "html":
85
+ return types.InputRichMessageHTML(html=r.source, **flags)
86
+ if r.fmt == "markdown":
87
+ return types.InputRichMessageMarkdown(markdown=r.source, **flags)
88
+ inp = copy.copy(_unb64(r.source))
89
+ # (a message saved by an older version may still hold blocks in Telegram's own form)
90
+ inp.blocks = inputify(inp.blocks, _user_ids(inp.users))
91
+ return inp
92
+
93
+
94
+ def _input_geo(geo):
95
+ if isinstance(geo, types.GeoPoint):
96
+ return types.InputGeoPoint(lat=geo.lat, long=geo.long, accuracy_radius=geo.accuracy_radius)
97
+ if isinstance(geo, types.InputGeoPoint):
98
+ return geo
99
+ return types.InputGeoPointEmpty()
100
+
101
+
102
+ def _user_ids(users) -> set:
103
+ return {u.user_id for u in users or [] if isinstance(getattr(u, "user_id", None), int)}
104
+
105
+
106
+ def inputify(o, users: Optional[set] = None):
107
+ """Blocks the way Telegram wants them SENT. What it hands out and what it takes are the same blocks except where a
108
+ block holds something only Telegram can make: a map holds a stored point (with an access hash) when it comes in, and
109
+ must hold an input point (latitude and longitude) when it goes out.
110
+
111
+ `users`: the ids of the accounts that the message may mention (it carries their access data). A text mention of
112
+ anybody else would be refused, so it stays as the plain name; None leaves all mentions alone.
113
+
114
+ A thinking block (the "thinking ..." part of a message that is being streamed) is for drafts only - the Bot API says so
115
+ of <tg-thinking> - and a message that is sent can't hold one: it goes out as an expandable section called "Thinking"."""
116
+ if isinstance(o, types.PageBlockMap):
117
+ return types.InputPageBlockMap(
118
+ geo=_input_geo(o.geo), zoom=o.zoom, w=o.w, h=o.h, caption=inputify(o.caption, users)
119
+ )
120
+ if isinstance(o, types.PageBlockThinking):
121
+ return types.PageBlockDetails(
122
+ blocks=[types.PageBlockParagraph(inputify(o.text, users))], title=types.TextPlain("Thinking")
123
+ )
124
+ if users is not None and isinstance(o, types.TextMentionName) and o.user_id not in users:
125
+ return inputify(o.text, users)
126
+ if isinstance(o, list):
127
+ return [inputify(x, users) for x in o]
128
+ if isinstance(o, TLObject):
129
+ new = copy.copy(o)
130
+ for key, value in vars(o).items():
131
+ if isinstance(value, (list, TLObject)):
132
+ setattr(new, key, inputify(value, users))
133
+ return new
134
+ return o
135
+
136
+
137
+ def blank_references(inp):
138
+ """The same InputRichMessage with the file references of its photos and files left out (they may have expired)."""
139
+ if not isinstance(inp, types.InputRichMessage):
140
+ return inp
141
+ out = copy.copy(inp)
142
+ out.photos = [types.InputPhoto(p.id, p.access_hash, b"") for p in inp.photos or []] or None
143
+ out.documents = [types.InputDocument(d.id, d.access_hash, b"") for d in inp.documents or []] or None
144
+ return out
145
+
146
+
147
+ async def with_rich(r: Rich, call):
148
+ """call(InputRichMessage*): first as saved, then (if Telegram says a saved file reference expired) without them."""
149
+ try:
150
+ return await call(to_input(r))
151
+ except errors.RPCError as e:
152
+ if r.fmt != "blocks" or "FileReference" not in type(e).__name__:
153
+ raise
154
+ log.info("stored file reference of a rich message rejected (%s) - retrying without it", type(e).__name__)
155
+ return await call(blank_references(to_input(r)))
156
+
157
+
158
+ def sent_message(result):
159
+ """The message a send request created (something with an `id`)."""
160
+ for u in getattr(result, "updates", None) or []:
161
+ if isinstance(u, (types.UpdateNewChannelMessage, types.UpdateNewMessage)):
162
+ return u.message
163
+ if getattr(result, "id", None) is not None and not isinstance(result, (list, tuple)):
164
+ return SimpleNamespace(id=result.id) # UpdateShortSentMessage
165
+ raise RuntimeError("Telegram did not say which message it created")
166
+
167
+
168
+ async def send_rich(client, peer, r: Rich, *, markup=None, silent=None):
169
+ """Send `r` as a new message to `peer`; the message that was created comes back."""
170
+ result = await with_rich(
171
+ r,
172
+ lambda inp: client(
173
+ functions.messages.SendMessageRequest(
174
+ peer=peer, message="", rich_message=inp, reply_markup=markup, silent=True if silent else None
175
+ )
176
+ ),
177
+ )
178
+ return sent_message(result)
179
+
180
+
181
+ # --------------------------------------------------------------------------------- rich messages that are received
182
+ def is_rich_message(m) -> bool:
183
+ """The message carries a rich message (blocks) instead of plain text."""
184
+ return getattr(m, "rich_message", None) is not None
185
+
186
+
187
+ def fingerprint(rm) -> str:
188
+ """Identifies what a rich message shows (its blocks; the file references of its pictures change from fetch to fetch)."""
189
+ h = hashlib.sha1()
190
+ for b in getattr(rm, "blocks", None) or []:
191
+ h.update(bytes(inputify(b))) # (a map's access hash is not part of what it shows)
192
+ h.update(b"r" if getattr(rm, "rtl", None) else b"-")
193
+ return h.hexdigest()[:20]
194
+
195
+
196
+ def _input_files(items, getter, empty) -> list:
197
+ out = []
198
+ for item in items or []:
199
+ try:
200
+ inp = getter(item)
201
+ except (TypeError, ValueError):
202
+ continue
203
+ if not isinstance(inp, empty):
204
+ out.append(inp)
205
+ return out
206
+
207
+
208
+ def input_of(rm, users: Optional[list] = None):
209
+ """The InputRichMessage that sends a received RichMessage again: same blocks, same pictures and files."""
210
+ photos = _input_files(getattr(rm, "photos", None), utils.get_input_photo, types.InputPhotoEmpty)
211
+ docs = _input_files(getattr(rm, "documents", None), utils.get_input_document, types.InputDocumentEmpty)
212
+ return types.InputRichMessage(
213
+ blocks=inputify(list(rm.blocks), _user_ids(users)),
214
+ rtl=True if getattr(rm, "rtl", None) else None,
215
+ photos=photos or None,
216
+ documents=docs or None,
217
+ users=users or None,
218
+ )
219
+
220
+
221
+ def rich_from_received(rm, users: Optional[list] = None) -> Rich:
222
+ return Rich("blocks", _b64(input_of(rm, users)), bool(getattr(rm, "rtl", None)), False, fingerprint(rm))
223
+
224
+
225
+ def mention_ids(blocks) -> list:
226
+ """User ids that the blocks mention by link (a text mention needs the account's access data to be sent again)."""
227
+ found: list = []
228
+
229
+ def walk(o) -> None:
230
+ if isinstance(o, dict):
231
+ if o.get("_") == "TextMentionName" and isinstance(o.get("user_id"), int):
232
+ found.append(o["user_id"])
233
+ for v in o.values():
234
+ walk(v)
235
+ elif isinstance(o, list):
236
+ for v in o:
237
+ walk(v)
238
+
239
+ for b in blocks or []:
240
+ walk(b.to_dict())
241
+ return list(dict.fromkeys(found))
242
+
243
+
244
+ async def input_users(client, ids: list) -> list:
245
+ out = []
246
+ for uid in ids:
247
+ try:
248
+ peer = await client.get_input_entity(uid)
249
+ except Exception as e: # noqa: BLE001 - a mention that can't be resolved is sent as the plain name
250
+ log.info("could not resolve the mentioned user %s: %s", uid, type(e).__name__)
251
+ continue
252
+ if isinstance(peer, types.InputPeerUser):
253
+ out.append(types.InputUser(peer.user_id, peer.access_hash))
254
+ return out
255
+
256
+
257
+ async def received(client, event) -> Optional[Rich]:
258
+ """The rich message that `event`'s message is (sent natively or forwarded to the bot), or None for an ordinary message."""
259
+ m = event.message
260
+ rm = getattr(m, "rich_message", None)
261
+ if rm is None:
262
+ return None
263
+ if getattr(rm, "part", None): # Telegram sent a part of it; the rest has to be asked for
264
+ full = None
265
+ try:
266
+ got = await client(functions.messages.GetRichMessageRequest(peer=await event.get_input_chat(), id=m.id))
267
+ full = got if isinstance(got, types.RichMessage) else getattr(got, "rich_message", None)
268
+ except errors.RPCError as e:
269
+ log.info("could not read the whole rich message: %s", type(e).__name__)
270
+ if full is None or getattr(full, "part", None):
271
+ raise RichError("Telegram only handed me a part of that rich message. Send it again, or type it as HTML / Markdown.")
272
+ rm = full
273
+ if not getattr(rm, "blocks", None):
274
+ raise RichError("That rich message has no content.")
275
+ return rich_from_received(rm, await input_users(client, mention_ids(rm.blocks)))
276
+
277
+
278
+ # --------------------------------------------------------------- when Telegram refuses a block of a received message
279
+ _BLOCK_NAMES = {
280
+ "Heading1": "heading", "Heading2": "heading", "Heading3": "heading", "Heading4": "heading", "Heading5": "heading",
281
+ "Heading6": "heading", "Title": "heading", "Subtitle": "heading", "Header": "heading", "Subheader": "heading",
282
+ "Paragraph": "paragraph", "Preformatted": "code", "Blockquote": "quote", "BlockquoteBlocks": "quote",
283
+ "Pullquote": "pull quote", "List": "list", "OrderedList": "numbered list", "Details": "expandable section",
284
+ "Math": "math", "Map": "map", "ButtonRow": "buttons", "Photo": "picture", "Video": "video", "Audio": "audio",
285
+ "Document": "file", "Collage": "collage", "Slideshow": "slideshow", "Table": "table", "Divider": "rule",
286
+ "Anchor": "anchor", "Footer": "footer", "Unsupported": "a block this version does not know",
287
+ "Thinking": "thinking block", "Embed": "embedded page", "EmbedPost": "embedded post", "Channel": "channel card",
288
+ "RelatedArticles": "related articles", "AuthorDate": "author line", "Kicker": "kicker", "Cover": "cover",
289
+ }
290
+ MAX_PROBES = 60 # blocks that are looked through one by one (at most) when Telegram refuses a message
291
+
292
+
293
+ def block_name(b) -> str:
294
+ """What a block is called to the owner: "map", "table" ..."""
295
+ raw = re.sub(r"^(?:Input)?PageBlock", "", type(b).__name__)
296
+ return _BLOCK_NAMES.get(raw, raw.lower() or "block")
297
+
298
+
299
+ def is_block_invalid(e: BaseException) -> bool:
300
+ """Telegram says one of the blocks it was given is not acceptable (RICH_MESSAGE_BLOCK_INVALID)."""
301
+ return "RICH_MESSAGE_BLOCK_INVALID" in (getattr(e, "message", None) or str(e))
302
+
303
+
304
+ async def refused_blocks(client, peer, r: Rich, *, pause: float = 0.4) -> Optional[List[int]]:
305
+ """The numbers (0, 1, 2 ...) of the top-level blocks of a received rich message that Telegram will not take back.
306
+
307
+ Called once the whole message has been refused. Found by sending groups of the blocks to `peer` - a chat with the
308
+ owner - quietly, and deleting them again straight away. None when it can't be told: the message is typed (Telegram
309
+ reads that itself), it has too many blocks to look through, no single block is at fault (every part is taken), or
310
+ something else than a refused block went wrong."""
311
+ if r.fmt != "blocks":
312
+ return None
313
+ whole = to_input(r)
314
+ blocks = list(whole.blocks)
315
+ if not blocks or len(blocks) > MAX_PROBES:
316
+ return None
317
+
318
+ async def accepted(idx: List[int]) -> bool:
319
+ part = copy.copy(whole)
320
+ part.blocks = [blocks[i] for i in idx]
321
+ try:
322
+ made = await flood_retry(
323
+ lambda: client(
324
+ functions.messages.SendMessageRequest(peer=peer, message="", rich_message=part, silent=True)
325
+ )
326
+ )
327
+ except errors.RPCError as e:
328
+ if is_block_invalid(e):
329
+ return False
330
+ raise
331
+ try:
332
+ await client(functions.messages.DeleteMessagesRequest(id=[sent_message(made).id], revoke=True))
333
+ except Exception: # noqa: BLE001 - a test message that stays is only clutter
334
+ log.info("could not delete a test message of the rich-message check")
335
+ await asyncio.sleep(pause)
336
+ return True
337
+
338
+ async def find(idx: List[int], known: bool = False) -> List[int]:
339
+ if not known and await accepted(idx):
340
+ return []
341
+ if len(idx) == 1:
342
+ return list(idx)
343
+ mid = len(idx) // 2
344
+ return await find(idx[:mid]) + await find(idx[mid:])
345
+
346
+ try:
347
+ bad = await find(list(range(len(blocks))), known=True) # (the whole message was refused: no need to ask again)
348
+ except Exception as e: # noqa: BLE001 - this is only a help for the owner
349
+ log.info("could not find the refused blocks: %s", type(e).__name__)
350
+ return None
351
+ return bad or None
352
+
353
+
354
+ def block_labels(r: Rich, idx: List[int]) -> str:
355
+ """"4 (map), 9 (table)": the blocks numbered `idx` (from 0), counted from 1 and named."""
356
+ blocks = to_input(r).blocks
357
+ return ", ".join(f"{i + 1} ({block_name(blocks[i])})" for i in sorted(set(idx)) if 0 <= i < len(blocks))
358
+
359
+
360
+ def block_count(r: Rich) -> int:
361
+ return len(to_input(r).blocks) if r.fmt == "blocks" else 0
362
+
363
+
364
+ def digest(r: Rich) -> str:
365
+ """Short mark of what `r` holds (so a button made for one message is not used on another)."""
366
+ return hashlib.sha1(f"{r.fmt}:{r.source}".encode()).hexdigest()[:6]
367
+
368
+
369
+ def pack_blocks(idx: List[int]) -> str:
370
+ """Block numbers as one short word (the bits of a number, in base 36) - small enough for a button."""
371
+ n, out = sum(1 << i for i in set(idx)), ""
372
+ while n:
373
+ n, d = divmod(n, 36)
374
+ out = "0123456789abcdefghijklmnopqrstuvwxyz"[d] + out
375
+ return out or "0"
376
+
377
+
378
+ def unpack_blocks(word: str) -> List[int]:
379
+ n = int(word, 36)
380
+ return [i for i in range(n.bit_length()) if n >> i & 1]
381
+
382
+
383
+ def without_blocks(r: Rich, drop: List[int]) -> Rich:
384
+ """The received rich message `r` without the top-level blocks numbered `drop` (what Telegram saw of it changes, so the
385
+ fingerprint is forgotten)."""
386
+ inp = to_input(r)
387
+ inp.blocks = [b for i, b in enumerate(inp.blocks) if i not in set(drop)]
388
+ return Rich("blocks", _b64(inp), r.rtl, r.noautolink, None)
389
+
390
+
391
+ # ------------------------------------------------------------------------- plain text (lists, panels, previews)
392
+ _BLOCKY = ("h1", "h2", "h3", "h4", "h5", "h6", "p", "ul", "ol", "li", "table", "tr", "details", "summary", "figure",
393
+ "figcaption", "aside", "blockquote", "pre", "footer", "hr", "br", "tg-math-block", "tg-button-row", "tg-collage",
394
+ "tg-slideshow", "tg-map", "img", "video", "audio", "tg-document", "caption", "cite")
395
+
396
+
397
+ class _Plain(HTMLParser):
398
+ def __init__(self) -> None:
399
+ super().__init__(convert_charrefs=True)
400
+ self.out: List[str] = []
401
+ self.skip = 0
402
+
403
+ def _break(self, tag: str) -> None:
404
+ """A line break for a block; two blocks in a row are only one line apart (a <br> is always a break)."""
405
+ if tag == "br" or (self.out and not self.out[-1].endswith("\n")):
406
+ self.out.append("\n")
407
+
408
+ def handle_starttag(self, tag, attrs):
409
+ if tag in ("script", "style"):
410
+ self.skip += 1
411
+ if tag in _BLOCKY:
412
+ self._break(tag)
413
+ if tag == "li":
414
+ self.out.append("β€’ ")
415
+ elif tag in ("td", "th"):
416
+ self.out.append(" | " if self.out and not self.out[-1].endswith(("\n", " | ")) else "")
417
+ elif tag == "input" and any(k == "type" and v == "checkbox" for k, v in attrs):
418
+ self.out.append("β˜‘ " if any(k == "checked" for k, _ in attrs) else "☐ ")
419
+
420
+ def handle_startendtag(self, tag, attrs):
421
+ self.handle_starttag(tag, attrs)
422
+
423
+ def handle_endtag(self, tag):
424
+ if tag in ("script", "style") and self.skip:
425
+ self.skip -= 1
426
+ if tag in _BLOCKY:
427
+ self._break(tag)
428
+
429
+ def handle_data(self, data):
430
+ if not self.skip:
431
+ self.out.append(data)
432
+
433
+
434
+ def _tidy(text: str) -> str:
435
+ lines = [" ".join(line.split()) for line in text.replace("\r", "").split("\n")]
436
+ return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
437
+
438
+
439
+ def _plain_html(source: str) -> str:
440
+ p = _Plain()
441
+ try:
442
+ p.feed(source)
443
+ p.close()
444
+ except Exception: # noqa: BLE001 - a snippet is not worth failing for
445
+ return _tidy(re.sub(r"<[^>]*>", " ", source))
446
+ return _tidy("".join(p.out))
447
+
448
+
449
+ _MD_EMPHASIS = re.compile(r"(\*\*|__|~~|\|\||==)(?=\S)(.+?)(?<=\S)\1")
450
+ _MD_SINGLE = re.compile(r"(?<![\w*])([*_])(?=\S)([^*_\n]+?)(?<=\S)\1(?![\w*])")
451
+
452
+
453
+ def _plain_markdown(source: str) -> str:
454
+ out: List[str] = []
455
+ fenced = False
456
+ for line in source.replace("\r", "").split("\n"):
457
+ if re.match(r"^\s*(```|~~~)", line):
458
+ fenced = not fenced
459
+ continue
460
+ if fenced:
461
+ out.append(line)
462
+ continue
463
+ if re.match(r"^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$", line): # a table's delimiter row
464
+ continue
465
+ if re.match(r"^\s*(-{3,}|\*{3,}|_{3,})\s*$", line):
466
+ out.append("")
467
+ continue
468
+ line = re.sub(r"^\s{0,3}#{1,6}\s+", "", line)
469
+ line = re.sub(r"^(\s*)(?:>\s?)+", r"\1", line)
470
+ line = re.sub(r"^(\s*)[-*+]\s+\[[xX]\]\s+", r"\1β˜‘ ", line)
471
+ line = re.sub(r"^(\s*)[-*+]\s+\[ \]\s+", r"\1☐ ", line)
472
+ line = re.sub(r"^(\s*)[-*+]\s+", r"\1β€’ ", line)
473
+ if "|" in line and line.count("|") >= 2:
474
+ line = " | ".join(c.strip() for c in line.strip().strip("|").split("|"))
475
+ line = re.sub(r"!\[([^\]]*)\]\([^)]*?(?:\s+\"([^\"]*)\")?\)", lambda m: m.group(2) or m.group(1), line)
476
+ line = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", line)
477
+ line = re.sub(r"^\[\^([^\]\s]+)\]:[ \t]*", r"\1: ", line) # a footnote's text, led by its mark
478
+ line = re.sub(r"\[\^[^\]]+\]", "", line)
479
+ line = _MD_EMPHASIS.sub(r"\2", line)
480
+ line = _MD_SINGLE.sub(r"\2", line)
481
+ line = line.replace("`", "")
482
+ line = re.sub(r"\\([\\`*_{}\[\]()#+\-.!|~>$=])", r"\1", line)
483
+ out.append(line)
484
+ return _tidy("\n".join(out))
485
+
486
+
487
+ def _plain_blocks(blocks) -> str:
488
+ out: List[str] = []
489
+
490
+ def brk() -> None:
491
+ if out and not out[-1].endswith("\n"):
492
+ out.append("\n")
493
+
494
+ def walk(o) -> None:
495
+ if isinstance(o, dict):
496
+ name = str(o.get("_", ""))
497
+ if name == "PageTableRow":
498
+ brk()
499
+ for n, cell in enumerate(o.get("cells") or []):
500
+ if n:
501
+ out.append(" | ")
502
+ walk(cell)
503
+ brk()
504
+ return
505
+ item = name.startswith(("PageListItem", "PageListOrderedItem"))
506
+ if name.startswith("PageBlock") or item:
507
+ brk()
508
+ if item:
509
+ out.append(("β˜‘ " if o.get("checked") else "☐ ") if o.get("checkbox") else "β€’ ")
510
+ for key in sorted(o, key=lambda k: k != "title"): # a title (of a <details>, a table) is read first
511
+ v = o[key]
512
+ if key in ("text", "source") and isinstance(v, str):
513
+ out.append(v)
514
+ elif isinstance(v, (dict, list)):
515
+ walk(v)
516
+ if name.startswith("PageBlock") or item:
517
+ brk()
518
+ elif isinstance(o, list):
519
+ for v in o:
520
+ walk(v)
521
+
522
+ for b in blocks or []:
523
+ try:
524
+ walk(b.to_dict())
525
+ except Exception: # noqa: BLE001
526
+ continue
527
+ return _tidy("".join(out))
528
+
529
+
530
+ def plain_of(r: Rich) -> str:
531
+ """What the rich message says, as plain text (what My posts shows and searches)."""
532
+ if r.fmt == "html":
533
+ return _plain_html(r.source)
534
+ if r.fmt == "markdown":
535
+ return _plain_markdown(r.source)
536
+ try:
537
+ inp = _unb64(r.source)
538
+ return _plain_blocks(getattr(inp, "blocks", None))
539
+ except Exception: # noqa: BLE001
540
+ return ""
541
+
542
+
543
+ def plain_of_message(m) -> str:
544
+ return _plain_blocks(getattr(getattr(m, "rich_message", None), "blocks", None))
545
+
546
+
547
+ # ---------------------------------------------------------------------------- reading what the owner typed
548
+ _FORCE = re.compile(r"\A[ \t]*<rich((?:[ \t]+(?:rtl|noautolink))*)[ \t]*>[ \t]*(?:\r?\n|\Z)", re.I)
549
+
550
+ # HTML only rich messages have: headings, paragraphs, lists, tables, details, figures, media, maps, math, buttons, marks ...
551
+ _RICH_TAGS = (
552
+ r"h[1-6]", "p", "ul", "ol", "li", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "caption", "details", "summary",
553
+ "figure", "figcaption", "aside", "hr", "img", "video", "audio", "footer", "cite", "input", "mark", "sub", "sup",
554
+ "tg-document", "tg-map", "tg-collage", "tg-slideshow", "tg-math", "tg-math-block", "tg-button", "tg-button-row",
555
+ "tg-time", "tg-reference",
556
+ )
557
+ _RICH_HTML = re.compile(
558
+ r"<(?:" + "|".join(t if t.startswith("h[") else re.escape(t) for t in _RICH_TAGS) + r")(?=[\s/>])[^<>]*>"
559
+ r"|<a\s[^<>]*?\b(?:name\s*=|href\s*=\s*[\"']?#)",
560
+ re.I,
561
+ )
562
+ _BASIC_HTML = re.compile(r"<(?:b|strong|i|em|u|ins|s|strike|del|a|code|pre|blockquote|tg-spoiler|tg-emoji)(?=[\s/>])[^<>]*>", re.I)
563
+
564
+ # Markdown only rich messages have (a bullet list or a rule alone does not count: plain posts use those as decoration)
565
+ _MD_RICH = (
566
+ re.compile(r"^ {0,3}#{1,6}[ \t]+\S", re.M), # # heading
567
+ re.compile(r"^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+\[[ xX]\](?:[ \t]+\S|[ \t]*$)", re.M), # - [x] task
568
+ re.compile(r"^[^\n]*\|[^\n]*\n[ \t]*\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)+\|?[ \t]*$", re.M), # | table |
569
+ re.compile(r"\$\$.+?\$\$", re.S), # $$ block math $$
570
+ re.compile(r"^\[\^[^\]\s]+\]:[ \t]+\S", re.M), # [^1]: footnote
571
+ re.compile(r"(?<![=\w])==(?=\S)[^=\n]+?(?<=\S)==(?![=\w])"), # ==marked==
572
+ re.compile(r"^[ \t]*!\[[^\]\n]*\]\((?!tg://(?:emoji|time)\b)[^)\s]+(?:[ \t]+\"[^\"\n]*\")?\)[ \t]*$", re.M), # ![](picture)
573
+ re.compile(r"!\[[^\]\n]*\]\(tg://time\?[^)\s]+\)"), # a formatted date
574
+ )
575
+ _CODE = re.compile(r"```.*?```|~~~.*?~~~|<pre\b.*?</pre\s*>|<code\b.*?</code\s*>|`[^`\n]+`", re.S | re.I)
576
+
577
+
578
+ def _blank(m: "re.Match") -> str:
579
+ return re.sub(r"[^\n]", " ", m.group())
580
+
581
+
582
+ def detect(text: str, forced: bool = False) -> Optional[str]:
583
+ """"html" or "markdown" when `text` needs a rich message (or `forced` says it is one), else None."""
584
+ bare = _CODE.sub(_blank, text) # what stands in code is not markup
585
+ html_hit = bool(_RICH_HTML.search(bare))
586
+ if html_hit and bare.lstrip().startswith("<"):
587
+ return "html"
588
+ if any(rx.search(bare) for rx in _MD_RICH):
589
+ return "markdown"
590
+ if html_hit:
591
+ return "html"
592
+ if forced:
593
+ return "html" if _BASIC_HTML.search(bare) else "markdown"
594
+ return None
595
+
596
+
597
+ def read_typed(text: str) -> Optional[Rich]:
598
+ """The rich message that text typed as HTML or Markdown stands for, or None when it is an ordinary text.
599
+
600
+ It is a rich message when it has something only rich messages have (a heading, a table, a task list, math, a picture,
601
+ <details> ...), or when its first line is ``<rich>`` (``<rich rtl>``, ``<rich noautolink>``). Telegram reads the
602
+ language itself; what is passed on is exactly what was typed (without that first line)."""
603
+ text = text or ""
604
+ force = _FORCE.match(text)
605
+ body = text[force.end():] if force else text
606
+ fmt = detect(body, forced=bool(force))
607
+ if fmt is None or not body.strip():
608
+ return None
609
+ words = (force.group(1) or "").lower().split() if force else []
610
+ return Rich(fmt, body.strip(), rtl="rtl" in words, noautolink="noautolink" in words)
611
+
612
+
613
+ def check(r: Rich) -> None:
614
+ """RichError when Telegram would not take it (only the limit that is cheap to check here)."""
615
+ if r.fmt != "blocks" and len(r.source) > MAX_SOURCE:
616
+ raise RichError(f"A rich message can have at most {MAX_SOURCE} characters (yours has {len(r.source)}).")
617
+
618
+
619
+ def with_fingerprint(r: Rich, fp: Optional[str]) -> Rich:
620
+ return replace(r, fp=fp)
621
+
622
+
623
+ # --------------------------------------------------------------------------------------- the /rich help pages
624
+ RICH_HELP = (
625
+ "🧩 <b>Rich messages</b>\n\n"
626
+ "Telegram's newer message type: headings, lists, tables, expandable sections, math, maps, pictures and buttons in one "
627
+ "message (up to 32768 characters, 500 blocks, 16 nesting levels, 50 pictures/files, 20 table columns). The bot "
628
+ "publishes your text as one when\n"
629
+ "β€’ you send it a rich message made in Telegram, or forward one: it is kept block for block, or\n"
630
+ "β€’ you type HTML or Markdown that has something only rich messages have: a heading, a table, a task list, math, a "
631
+ "picture, <code>&lt;details&gt;</code>, <code>&lt;h1&gt;</code>, <code>&lt;table&gt;</code> ... or\n"
632
+ "β€’ the first line is just <code>&lt;rich&gt;</code> (<code>&lt;rich rtl&gt;</code> for right-to-left text, "
633
+ "<code>&lt;rich noautolink&gt;</code> so links, @names and #tags are not made clickable).\n\n"
634
+ "Telegram reads the text itself, so everything it supports works. πŸ‘ Preview shows what it made of your text before "
635
+ "you publish. Rich messages are for text posts - a photo's caption can't be rich. The post's own link buttons "
636
+ "(βž• Button) work with them.\n\n"
637
+ "<b>Markdown</b>\n"
638
+ "<code>**bold** *italic* ~~strike~~ ||spoiler|| ==marked== `code`</code> (underline, subscript and superscript: HTML "
639
+ "<code>&lt;u&gt; &lt;sub&gt; &lt;sup&gt;</code>)\n"
640
+ "<code># Heading</code> … <code>###### Heading</code>\n"
641
+ "<code>- item</code> <code>1. item</code> lists, <code>- [ ] task</code> <code>- [x] done</code>, <code>---</code> a rule\n"
642
+ "<code>&gt; quote</code> (a bare <code>&gt;</code> line is a new paragraph inside it)\n"
643
+ "<code>```python</code> … <code>```</code> a code block with a language\n"
644
+ "<code>$x^2$</code> inline math, <code>$$E = mc^2$$</code> or a <code>```math</code> block: a formula block\n"
645
+ "<code>| a | b |</code> then <code>|:--|--:|</code> then rows: a table (colons set the alignment; cells hold inline "
646
+ "formatting only)\n"
647
+ "<code>text[^1]</code> and a line <code>[^1]: the note</code>: a footnote\n"
648
+ "<code>![](https://…/pic.jpg \"caption\")</code> alone on a line: a picture, video, audio, GIF or file (https links "
649
+ "only); put several such lines inside <code>&lt;tg-collage&gt;</code> or <code>&lt;tg-slideshow&gt;</code>\n"
650
+ "<code>![22:45 tomorrow](tg://time?unix=1647531900&amp;format=wDT)</code> a date shown in the reader's time\n"
651
+ "<code>![](tg://emoji?id=5368324170671202286)</code> a custom emoji\n"
652
+ "<code>[name](tg://user?id=123)</code> <code>[mail](mailto:a@b.c)</code> <code>[call](tel:+123)</code>\n"
653
+ "Raw HTML works inside Markdown, but Markdown is not read inside block tags (only inside <code>&lt;details&gt;</code>, "
654
+ "<code>&lt;tg-collage&gt;</code> and <code>&lt;tg-slideshow&gt;</code>)."
655
+ )
656
+
657
+ RICH_HELP_HTML = (
658
+ "🧩 <b>Rich HTML</b>\n\n"
659
+ "<code>&lt;h1&gt;</code> … <code>&lt;h6&gt;</code> <code>&lt;p&gt;</code> <code>&lt;hr&gt;</code> "
660
+ "<code>&lt;footer&gt;</code> <code>&lt;b&gt; &lt;i&gt; &lt;u&gt; &lt;s&gt; &lt;mark&gt; &lt;sub&gt; &lt;sup&gt; "
661
+ "&lt;code&gt; &lt;tg-spoiler&gt;</code> <code>&lt;br&gt;</code>\n"
662
+ "<code>&lt;pre&gt;&lt;code class=\"language-python\"&gt;</code> a code block\n"
663
+ "<code>&lt;ul&gt;</code> <code>&lt;ol start=\"3\" type=\"a\" reversed&gt;</code> "
664
+ "<code>&lt;li value=\"7\" type=\"i\"&gt;</code> (type: a, A, i, I, 1) "
665
+ "<code>&lt;input type=\"checkbox\" checked&gt;</code>\n"
666
+ "<code>&lt;blockquote expandable&gt;text&lt;cite&gt;who&lt;/cite&gt;&lt;/blockquote&gt;</code> and "
667
+ "<code>&lt;aside&gt;pull quote&lt;cite&gt;who&lt;/cite&gt;&lt;/aside&gt;</code>\n"
668
+ "<code>&lt;details open&gt;&lt;summary&gt;Title&lt;/summary&gt;…&lt;/details&gt;</code> an expandable section\n"
669
+ "<code>&lt;table bordered striped compact&gt;&lt;caption&gt;…&lt;/caption&gt;&lt;tr&gt;&lt;th colspan=\"2\" "
670
+ "align=\"center\" valign=\"middle\"&gt;…</code> (td and th: colspan, rowspan, align left/center/right, valign "
671
+ "top/middle/bottom)\n"
672
+ "<code>&lt;tg-math&gt;x^2&lt;/tg-math&gt;</code> <code>&lt;tg-math-block&gt;E = mc^2&lt;/tg-math-block&gt;</code> "
673
+ "(raw LaTeX)\n"
674
+ "<code>&lt;tg-time unix=\"1647531900\" format=\"wDT\"&gt;22:45 tomorrow&lt;/tg-time&gt;</code>\n"
675
+ "<code>&lt;tg-emoji emoji-id=\"5368324170671202286\"&gt;πŸ™‚&lt;/tg-emoji&gt;</code>\n"
676
+ "<code>&lt;a name=\"top\"&gt;&lt;/a&gt;</code> and <code>&lt;a href=\"#top\"&gt;</code> anchors; "
677
+ "<code>&lt;tg-reference name=\"n1\"&gt;text&lt;/tg-reference&gt;</code> with <code>&lt;a href=\"#n1\"&gt;</code> "
678
+ "a footnote\n"
679
+ "<code>&lt;img src=\"https://…\"&gt;</code> <code>&lt;video src=…&gt;</code> <code>&lt;audio src=…&gt;</code> "
680
+ "<code>&lt;tg-document src=…&gt;</code>, each on its own or in "
681
+ "<code>&lt;figure&gt;…&lt;figcaption&gt;caption&lt;cite&gt;credit&lt;/cite&gt;&lt;/figcaption&gt;&lt;/figure&gt;</code> "
682
+ "(https links only; <code>tg-spoiler</code> on img/video hides it); several inside "
683
+ "<code>&lt;tg-collage&gt;</code> or <code>&lt;tg-slideshow&gt;</code>\n"
684
+ "<code>&lt;tg-map lat=\"41.9\" long=\"12.5\" zoom=\"14\"/&gt;</code> a map\n"
685
+ "<code>&lt;tg-button-row align=\"center\"&gt;&lt;tg-button type=\"url\" url=\"https://t.me\" "
686
+ "style=\"success\"&gt;Open&lt;/tg-button&gt;&lt;/tg-button-row&gt;</code> buttons in the text. Types: url, "
687
+ "web_app and login_url (url=), callback_data (data=), copy_text (text=), switch_inline_query, "
688
+ "switch_inline_query_current_chat, switch_inline_query_chosen_chat (query=), disabled. Styles: primary, success, "
689
+ "danger, link.\n"
690
+ "<code>&amp;lt; &amp;gt; &amp;amp;</code> stand for &lt; &gt; &amp; when they must stay as they are.\n\n"
691
+ "<b>Good to know</b>\n"
692
+ "β€’ A picture or video typed into a rich message must be a public https link. To use a file that exists only on "
693
+ "Telegram, send the bot a rich message that already contains it.\n"
694
+ "β€’ A button inside the text that needs the bot (callback_data) only works for the bot that made it - for a forwarded "
695
+ "rich message that is another bot.\n"
696
+ "β€’ /swap, /handleswap and the post-link changes of /repost change a rich post's buttons, not the links inside its text.\n"
697
+ "β€’ Older Telegram apps may not show rich messages."
698
+ )
app/richtext.py ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Telegram formatting from text typed as HTML or Markdown - for when Telegram's own editor is not at hand.
2
+
3
+ A message the owner sends can carry Telegram's own formatting: that is used exactly as it is. When it carries none, the
4
+ text is read as HTML (when it holds a supported tag together with its closing tag) or else as Markdown, and what is
5
+ recognised becomes real formatting. Whatever is not recognised stays as it was typed, so ordinary text (``5 * 3``,
6
+ ``snake_case_names``, ``<3``, ``[Group] Title``, ``Sub | Dub``) is left alone.
7
+
8
+ HTML, like Telegram's own HTML mode:
9
+ <b> <strong>, <i> <em>, <u> <ins>, <s> <strike> <del>, <tg-spoiler> or <span class="tg-spoiler">, <code>,
10
+ <pre> (<pre><code class="language-python">..</code></pre> names a language), <a href="..">, <blockquote> and
11
+ <blockquote expandable>, <tg-emoji emoji-id="123">πŸ™‚</tg-emoji>, <br> for a line break.
12
+ ``&lt;`` ``&gt;`` ``&amp;`` stand for those characters. Any other tag is left as typed.
13
+
14
+ Markdown:
15
+ **bold** *italic* _italic_ __underline__ ~~strikethrough~~ ||spoiler|| `code` ```code block```
16
+ [text](https://link) ![πŸ™‚](tg://emoji?id=123) a line that starts with ``>`` is quoted (``**>`` starts an
17
+ expandable quote that ends with ``||``) and a backslash before a punctuation mark keeps it as it is.
18
+ As in CommonMark, a mark must touch the text it formats (``**bold**``, not ``** bold **``), and a lone ``*`` or
19
+ ``_`` inside a word does nothing. A link typed as it is (https://...) is never cut up by marks inside it.
20
+
21
+ Entities come out in the form the bot stores them (see ``tgutil.ser_entities``), with UTF-16 offsets like Telegram's.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+ import re
27
+ import unicodedata
28
+ from html.parser import HTMLParser
29
+ from typing import List, Optional, Tuple
30
+
31
+ from .tgutil import ser_entities, utf16_len
32
+
33
+ log = logging.getLogger(__name__)
34
+
35
+ Span = Tuple[str, int, int, object] # (kind, offset, length, arg) - offsets in UTF-16 units, like Telegram's own
36
+
37
+
38
+ def _entity(kind: str, offset: int, length: int, arg=None) -> dict:
39
+ """One entity as the bot stores it; `arg` is the pre block's language, the link, the emoji id or "expandable"."""
40
+ e = {"k": kind, "o": offset, "l": length}
41
+ if kind == "pre":
42
+ e["g"] = arg or ""
43
+ elif kind == "url":
44
+ e["u"] = arg
45
+ elif kind == "quote":
46
+ e["c"] = bool(arg)
47
+ elif kind == "emoji":
48
+ e["d"] = arg
49
+ return e
50
+
51
+
52
+ _NO_NEST = {"bold", "italic", "underline", "strike", "spoiler", "code", "quote", "url"} # a second one inside the first adds nothing
53
+
54
+
55
+ def _entities(spans: List[Span]) -> list:
56
+ """Entities for the spans, outer ones first (same start: the longer one).
57
+
58
+ A span of a kind that lies wholly inside another of the same kind (``<b>a <b>b</b></b>``, a quote in a quote) is left
59
+ out: it changes nothing on screen, and Telegram does not want such entities nested."""
60
+ out: list = []
61
+ kept: List[Tuple[str, int, int]] = []
62
+ for kind, offset, length, arg in sorted((s for s in spans if s[2] > 0), key=lambda s: (s[1], -s[2])):
63
+ if kind in _NO_NEST and any(k == kind and offset >= a and offset + length <= b for k, a, b in kept):
64
+ continue
65
+ kept.append((kind, offset, offset + length))
66
+ out.append(_entity(kind, offset, length, arg))
67
+ return out
68
+
69
+
70
+ # ------------------------------------------------------------------------------------------------------ links
71
+ _SCHEMES = ("http://", "https://", "tg://", "ton://")
72
+ _DOMAIN = re.compile(r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}(?::\d{1,5})?(?:[/?#]\S*)?")
73
+
74
+
75
+ def clean_url(raw: Optional[str]) -> Optional[str]:
76
+ """The link as Telegram wants it, or None when it is no link (``t.me/x`` gets its https://)."""
77
+ url = (raw or "").strip()
78
+ if not url or len(url) > 2000 or any(c.isspace() for c in url):
79
+ return None
80
+ low = url.lower()
81
+ for scheme in _SCHEMES:
82
+ if low.startswith(scheme):
83
+ return url if len(url) > len(scheme) else None
84
+ return "https://" + url if _DOMAIN.fullmatch(url) else None
85
+
86
+
87
+ # ------------------------------------------------------------------------------------------------------- HTML
88
+ _TAGS = ("b", "strong", "i", "em", "u", "ins", "s", "strike", "del", "a", "code", "pre", "blockquote", "tg-spoiler", "tg-emoji", "span")
89
+ _HTML_PAIR = re.compile(r"<(" + "|".join(re.escape(t) for t in _TAGS) + r")(?:\s[^<>]*)?>.*?</\1\s*>", re.I | re.S)
90
+ _KIND_OF_TAG = {
91
+ "b": "bold", "strong": "bold", "i": "italic", "em": "italic", "u": "underline", "ins": "underline",
92
+ "s": "strike", "strike": "strike", "del": "strike", "tg-spoiler": "spoiler", "span": "spoiler",
93
+ }
94
+
95
+
96
+ def looks_like_html(text: str) -> bool:
97
+ """A supported tag with its closing tag is there (a lone ``<b>`` in a sentence is just text)."""
98
+ return bool(_HTML_PAIR.search(text))
99
+
100
+
101
+ class _Html(HTMLParser):
102
+ """Collects the text and the formatting of an HTML message; what it does not know is kept as it was typed."""
103
+
104
+ def __init__(self) -> None:
105
+ super().__init__(convert_charrefs=True)
106
+ self.parts: List[str] = []
107
+ self.pos = 0 # UTF-16 length of the text so far
108
+ self.open: List[dict] = []
109
+ self.spans: List[Span] = []
110
+
111
+ def text(self, s: str) -> None:
112
+ if s:
113
+ self.parts.append(s)
114
+ self.pos += utf16_len(s)
115
+
116
+ def literal_zone(self) -> bool:
117
+ """Inside <pre> / <code> everything is code, so a tag there is shown as typed."""
118
+ return any(o["tag"] in ("pre", "code") for o in self.open)
119
+
120
+ # --- tags
121
+ def handle_starttag(self, tag, attrs):
122
+ t, a = tag.lower(), {k: (v or "") for k, v in attrs}
123
+ raw = self.get_starttag_text() or ""
124
+ if t == "br" and not self.literal_zone():
125
+ self.text("\n")
126
+ return
127
+ if self.literal_zone():
128
+ top = self.open[-1]
129
+ if t == "code" and top["tag"] == "pre" and self.pos == top["start"] and "lang" not in top:
130
+ cls = a.get("class", "")
131
+ top["lang"] = cls[len("language-"):] if cls.startswith("language-") else ""
132
+ self.open.append({"tag": "code", "start": self.pos, "holder": True})
133
+ else:
134
+ self.text(raw)
135
+ return
136
+ if t == "span" and "tg-spoiler" not in a.get("class", "").split():
137
+ self.text(raw)
138
+ elif t in _TAGS:
139
+ self.open.append({"tag": t, "start": self.pos, "attrs": a})
140
+ else:
141
+ self.text(raw)
142
+
143
+ def handle_startendtag(self, tag, attrs):
144
+ if tag.lower() == "br" and not self.literal_zone():
145
+ self.text("\n")
146
+ else:
147
+ self.text(self.get_starttag_text() or "")
148
+
149
+ def handle_endtag(self, tag):
150
+ t = tag.lower()
151
+ if t == "br":
152
+ return
153
+ idx = next((i for i in range(len(self.open) - 1, -1, -1) if self.open[i]["tag"] == t), None)
154
+ if idx is None:
155
+ self.text(f"</{tag}>")
156
+ return
157
+ while len(self.open) > idx: # a tag opened inside it and never closed ends with it
158
+ self.close_tag(self.open.pop())
159
+
160
+ def close_tag(self, o: dict) -> None:
161
+ length = self.pos - o["start"]
162
+ if length <= 0 or o.get("holder"):
163
+ return
164
+ t, a = o["tag"], o.get("attrs", {})
165
+ if t in _KIND_OF_TAG:
166
+ self.spans.append((_KIND_OF_TAG[t], o["start"], length, None))
167
+ elif t == "code":
168
+ self.spans.append(("code", o["start"], length, None))
169
+ elif t == "pre":
170
+ self.spans.append(("pre", o["start"], length, o.get("lang", "")))
171
+ elif t == "a":
172
+ url = clean_url(a.get("href"))
173
+ if url:
174
+ self.spans.append(("url", o["start"], length, url))
175
+ elif t == "blockquote":
176
+ self.spans.append(("quote", o["start"], length, "expandable" in a))
177
+ elif t == "tg-emoji":
178
+ emoji_id = a.get("emoji-id", "")
179
+ if emoji_id.isdigit():
180
+ self.spans.append(("emoji", o["start"], length, int(emoji_id)))
181
+
182
+ # --- text and the rest
183
+ def handle_data(self, data):
184
+ self.text(data)
185
+
186
+ def handle_comment(self, data):
187
+ self.text(f"<!--{data}-->")
188
+
189
+ def handle_decl(self, decl):
190
+ self.text(f"<!{decl}>")
191
+
192
+ def handle_pi(self, data):
193
+ self.text(f"<?{data}>")
194
+
195
+ def finish(self) -> Tuple[str, List[Span]]:
196
+ self.close()
197
+ while self.open: # a tag that was never closed ends with the text
198
+ self.close_tag(self.open.pop())
199
+ return "".join(self.parts), self.spans
200
+
201
+
202
+ def from_html(source: str) -> Tuple[str, list]:
203
+ """(text, entities) of an HTML message."""
204
+ parser = _Html()
205
+ parser.feed(source)
206
+ text, spans = parser.finish()
207
+ return text, _entities(spans)
208
+
209
+
210
+ # --------------------------------------------------------------------------------------------------- Markdown
211
+ _FENCE = re.compile(r"```(?:([A-Za-z0-9_+#.-]{1,30})\n)?(.+?)```", re.S)
212
+ _EMOJI = re.compile(r"!\[([^\[\]\n]{1,16})\]\(tg://emoji\?id=(\d{1,20})\)")
213
+ _BARE_URL = re.compile(r"(?:https?|tg|ton)://[^\s<>]+", re.I)
214
+ _URL_END = "?!.,:;*_~|\"'" # what may follow a link without being part of it (a mark, or the end of a sentence)
215
+ _KIND_OF_MARK = {("*", 2): "bold", ("*", 1): "italic", ("_", 2): "underline", ("_", 1): "italic", ("~", 2): "strike", ("|", 2): "spoiler"}
216
+ MAX_MARKS = 400 # a message with more marks than this is left as typed (keeps the matching fast)
217
+
218
+
219
+ def _punct(ch: str) -> bool:
220
+ return unicodedata.category(ch)[0] in "PS"
221
+
222
+
223
+ def _flanking(mark: str, run: int, prev: Optional[str], nxt: Optional[str]) -> Tuple[bool, bool]:
224
+ """(can open, can close) for a run of `run` marks between the characters `prev` and `nxt`, by the CommonMark rules:
225
+ it opens when text follows it and closes when text comes before it. A lone ``*`` and ``_`` also need a space or
226
+ punctuation outside, so ``snake_case`` and a censored f*ck ... s*it stay as typed (``**bold**text`` still works)."""
227
+ prev_space, next_space = prev is None or prev.isspace(), nxt is None or nxt.isspace()
228
+ prev_punct, next_punct = prev is not None and _punct(prev), nxt is not None and _punct(nxt)
229
+ left = not next_space and (not next_punct or prev_space or prev_punct)
230
+ right = not prev_space and (not prev_punct or next_space or next_punct)
231
+ if mark == "_" or (mark == "*" and run == 1):
232
+ return left and (not right or prev_punct), right and (not left or next_punct)
233
+ return left, right
234
+
235
+
236
+ def _bare_url(s: str, i: int) -> Optional[str]:
237
+ """A link typed as it is (https://...) that starts at s[i], without what ends the sentence or closes a mark."""
238
+ if i and s[i - 1].isalnum():
239
+ return None
240
+ m = _BARE_URL.match(s, i)
241
+ if not m:
242
+ return None
243
+ url = m.group()
244
+ while url:
245
+ last = url[-1]
246
+ if last in _URL_END or (last in ")]" and url.count(last) > url.count("(" if last == ")" else "[")):
247
+ url = url[:-1]
248
+ else:
249
+ break
250
+ return url if len(url) > url.index("//") + 2 else None
251
+
252
+
253
+ def _link_at(s: str, i: int) -> Optional[Tuple[str, str, int]]:
254
+ """``[label](url)`` that starts at s[i]: (label, url, end) or None."""
255
+ depth, j, limit = 0, i, min(len(s), i + 600)
256
+ while j < limit:
257
+ ch = s[j]
258
+ if ch == "\\":
259
+ j += 2
260
+ continue
261
+ if ch == "[":
262
+ depth += 1
263
+ elif ch == "]":
264
+ depth -= 1
265
+ if depth == 0:
266
+ break
267
+ j += 1
268
+ else:
269
+ return None
270
+ if j + 1 >= len(s) or s[j + 1] != "(":
271
+ return None
272
+ k, depth, limit = j + 2, 1, min(len(s), j + 2 + 2000)
273
+ while k < limit:
274
+ ch = s[k]
275
+ if ch.isspace():
276
+ return None
277
+ if ch == "(":
278
+ depth += 1
279
+ elif ch == ")":
280
+ depth -= 1
281
+ if depth == 0:
282
+ break
283
+ k += 1
284
+ else:
285
+ return None
286
+ url, label = clean_url(s[j + 2:k]), s[i + 1:j]
287
+ return (label, url, k + 1) if url and label.strip() else None
288
+
289
+
290
+ class _Node:
291
+ """A piece of a paragraph: plain text, a code span, an emoji, a link, or a run of marks ("d")."""
292
+
293
+ __slots__ = ("kind", "text", "spans", "arg", "ch", "orig", "left", "can_open", "can_close", "start")
294
+
295
+ def __init__(self, kind, text="", spans=None, arg=None, ch="", orig=0, can_open=False, can_close=False):
296
+ self.kind, self.text, self.spans, self.arg = kind, text, spans or [], arg
297
+ self.ch, self.orig, self.left, self.can_open, self.can_close = ch, orig, orig, can_open, can_close
298
+ self.start = 0
299
+
300
+
301
+ def _inline(s: str, nested: bool = False) -> Tuple[str, List[Span]]:
302
+ """Text and formatting of Markdown inside one paragraph (or one quote)."""
303
+ nodes: List[_Node] = []
304
+ buf: List[str] = []
305
+
306
+ def flush() -> None:
307
+ if buf:
308
+ nodes.append(_Node("t", "".join(buf)))
309
+ buf.clear()
310
+
311
+ i, n = 0, len(s)
312
+ while i < n:
313
+ c = s[i]
314
+ if c == "\\" and i + 1 < n and s[i + 1].isascii() and _punct(s[i + 1]):
315
+ buf.append(s[i + 1])
316
+ i += 2
317
+ continue
318
+ if c == "`":
319
+ run = 1
320
+ while i + run < n and s[i + run] == "`":
321
+ run += 1
322
+ close = re.compile(r"(?<!`)" + "`" * run + r"(?!`)").search(s, i + run)
323
+ if close and close.start() > i + run:
324
+ flush()
325
+ nodes.append(_Node("code", s[i + run:close.start()]))
326
+ i = close.end()
327
+ else:
328
+ buf.append("`" * run)
329
+ i += run
330
+ continue
331
+ if c == "!" and s.startswith("![", i):
332
+ m = _EMOJI.match(s, i)
333
+ if m:
334
+ flush()
335
+ nodes.append(_Node("emoji", m.group(1), arg=int(m.group(2))))
336
+ i = m.end()
337
+ continue
338
+ if c == "[" and not nested:
339
+ link = _link_at(s, i)
340
+ if link:
341
+ flush()
342
+ label, url, end = link
343
+ inner, spans = _inline(label, nested=True)
344
+ nodes.append(_Node("link", inner, spans, url))
345
+ i = end
346
+ continue
347
+ if c in "hHtT":
348
+ url = _bare_url(s, i)
349
+ if url:
350
+ buf.append(url)
351
+ i += len(url)
352
+ continue
353
+ if c in "*_~|":
354
+ run = 1
355
+ while i + run < n and s[i + run] == c:
356
+ run += 1
357
+ if c in "~|" and run != 2:
358
+ buf.append(c * run)
359
+ else:
360
+ flush()
361
+ can_open, can_close = _flanking(c, run, s[i - 1] if i else None, s[i + run] if i + run < n else None)
362
+ nodes.append(_Node("d", ch=c, orig=run, can_open=can_open, can_close=can_close))
363
+ i += run
364
+ continue
365
+ buf.append(c)
366
+ i += 1
367
+ flush()
368
+ return _assemble(nodes)
369
+
370
+
371
+ def _assemble(nodes: List[_Node]) -> Tuple[str, List[Span]]:
372
+ """Match the marks (CommonMark's delimiter-stack way), then lay out the text and the spans."""
373
+ marks = [k for k, nd in enumerate(nodes) if nd.kind == "d"]
374
+ if len(marks) > MAX_MARKS:
375
+ for k in marks:
376
+ nodes[k].can_open = nodes[k].can_close = False
377
+ pairs: List[Tuple[int, int, str]] = []
378
+ for pos, j in enumerate(marks):
379
+ closer = nodes[j]
380
+ while closer.can_close and closer.left > 0:
381
+ found = None
382
+ for kk in range(pos - 1, -1, -1):
383
+ opener = nodes[marks[kk]]
384
+ if opener.ch != closer.ch or not opener.can_open or opener.left <= 0:
385
+ continue
386
+ # a mark that could do both: runs whose lengths add up to a multiple of 3 do not pair (unless each is one)
387
+ both = (opener.can_close or closer.can_open) and (opener.orig + closer.orig) % 3 == 0
388
+ if closer.ch in "*_" and both and not (opener.orig % 3 == 0 and closer.orig % 3 == 0):
389
+ continue
390
+ found = kk
391
+ break
392
+ if found is None:
393
+ break
394
+ opener = nodes[marks[found]]
395
+ use = 2 if opener.left >= 2 and closer.left >= 2 else 1
396
+ pairs.append((marks[found], j, _KIND_OF_MARK[(closer.ch, use)]))
397
+ opener.left -= use
398
+ closer.left -= use
399
+ for between in marks[found + 1:pos]: # what lies between the two can no longer pair across them
400
+ nodes[between].can_open = nodes[between].can_close = False
401
+ out: List[str] = []
402
+ pos = 0
403
+ for nd in nodes:
404
+ nd.start = pos
405
+ piece = nd.ch * nd.left if nd.kind == "d" else nd.text # marks that found no partner stay as typed
406
+ out.append(piece)
407
+ pos += utf16_len(piece)
408
+ spans: List[Span] = []
409
+ for a, b, kind in pairs:
410
+ begin = nodes[a].start + nodes[a].left
411
+ spans.append((kind, begin, nodes[b].start - begin, None))
412
+ for nd in nodes:
413
+ length = utf16_len(nd.text)
414
+ if nd.kind == "code":
415
+ spans.append(("code", nd.start, length, None))
416
+ elif nd.kind == "emoji":
417
+ spans.append(("emoji", nd.start, length, nd.arg))
418
+ elif nd.kind == "link":
419
+ spans.append(("url", nd.start, length, nd.arg))
420
+ spans.extend((k, nd.start + o, ln, arg) for k, o, ln, arg in nd.spans)
421
+ return "".join(out), spans
422
+
423
+
424
+ def _quote_line(line: str) -> Optional[Tuple[str, bool]]:
425
+ """(the line without its mark, whether it starts an expandable quote) when `line` is part of a quote."""
426
+ expandable = line.startswith("**>")
427
+ if expandable or (line.startswith(">") and not line.startswith(">>")): # ">> Download <<" is decoration, not a quote
428
+ body = line[3:] if expandable else line[1:]
429
+ return (body[1:] if body.startswith(" ") else body), expandable
430
+ return None
431
+
432
+
433
+ def _blocks(seg: str) -> Tuple[str, List[Span]]:
434
+ """A stretch of Markdown without code blocks: paragraphs and quotes."""
435
+ runs: List[list] = [] # [is_quote, expandable, lines]
436
+ for line in seg.split("\n"):
437
+ q = _quote_line(line)
438
+ if q is None:
439
+ if runs and not runs[-1][0]:
440
+ runs[-1][2].append(line)
441
+ else:
442
+ runs.append([False, False, [line]])
443
+ elif runs and runs[-1][0] and not q[1]:
444
+ runs[-1][2].append(q[0])
445
+ else:
446
+ runs.append([True, q[1], [q[0]]])
447
+ out: List[str] = []
448
+ spans: List[Span] = []
449
+ pos = 0
450
+ for is_quote, expandable, lines in runs:
451
+ if is_quote and expandable and lines[-1].endswith("||"):
452
+ lines[-1] = lines[-1][:-2]
453
+ text, inner = _inline("\n".join(lines))
454
+ spans.extend((kind, pos + o, n, arg) for kind, o, n, arg in inner)
455
+ if is_quote and text.strip():
456
+ spans.append(("quote", pos, utf16_len(text), expandable))
457
+ out.append(text)
458
+ pos += utf16_len(text) + 1 # + the line break that separates it from the next run
459
+ return "\n".join(out), spans
460
+
461
+
462
+ def from_markdown(source: str) -> Tuple[str, list]:
463
+ """(text, entities) of a Markdown message."""
464
+ out: List[str] = []
465
+ spans: List[Span] = []
466
+ pos = 0
467
+
468
+ def add(text: str, found: List[Span]) -> None:
469
+ nonlocal pos
470
+ spans.extend((kind, pos + o, n, arg) for kind, o, n, arg in found)
471
+ out.append(text)
472
+ pos += utf16_len(text)
473
+
474
+ last = 0
475
+ for m in _FENCE.finditer(source):
476
+ code = m.group(2)
477
+ if m.group(1) is None and code.startswith("\n"):
478
+ code = code[1:]
479
+ if code.endswith("\n"):
480
+ code = code[:-1]
481
+ if not code:
482
+ continue
483
+ add(*_blocks(source[last:m.start()]))
484
+ add(code, [("pre", 0, utf16_len(code), m.group(1) or "")])
485
+ last = m.end()
486
+ add(*_blocks(source[last:]))
487
+ return "".join(out), _entities(spans)
488
+
489
+
490
+ # ------------------------------------------------------------------------------------------- what the bot uses
491
+ def convert(text: str) -> Tuple[str, list, Optional[str]]:
492
+ """(text, entities, "html" | "markdown" | None) for text that carries no Telegram formatting.
493
+
494
+ Text with nothing to read comes back as it was (the third value None). It never raises: text the readers choke
495
+ on is simply used as typed, so a post is never lost to a formatting quirk.
496
+ """
497
+ try:
498
+ if looks_like_html(text):
499
+ new, ents = from_html(text)
500
+ return new, ents, "html"
501
+ new, ents = from_markdown(text)
502
+ except Exception: # noqa: BLE001
503
+ log.warning("could not read the formatting of a text - using it as typed", exc_info=True)
504
+ return text, [], None
505
+ return (new, ents, "markdown") if (ents or new != text) else (text, [], None)
506
+
507
+
508
+ def message_text(m, enabled: bool = True) -> Tuple[str, list, Optional[str]]:
509
+ """(text, entities in the form the bot stores, "html" | "markdown" | None) of a message the owner sent.
510
+
511
+ Telegram's own formatting wins: a message that has some is kept exactly as it is. Otherwise HTML or Markdown in
512
+ the text becomes formatting (unless `enabled` is False). The last value says which one was read.
513
+ """
514
+ text = m.raw_text or ""
515
+ own = ser_entities(m.entities) # (links, @mentions, #tags ... that Telegram finds by itself are not formatting)
516
+ if own or not enabled or not text:
517
+ return text, own, None
518
+ return convert(text)
519
+
520
+
521
+ CHEAT_SHEET = (
522
+ "✍️ <b>Formatting</b>\n\n"
523
+ "Send a post with Telegram's own formatting (bold, italic, quote, spoiler, links ...) and it is published exactly "
524
+ "like that. When you can't use Telegram's editor, type <b>Markdown</b> or <b>HTML</b> instead - the bot turns it "
525
+ "into real formatting. A message that already has Telegram formatting is used as it is, and text the bot doesn't "
526
+ "recognise stays as you typed it. πŸ‘ Preview shows the result before you publish.\n\n"
527
+ "<b>Markdown</b>\n"
528
+ "<code>**bold**</code> <code>*italic*</code> <code>_italic_</code> <code>__underline__</code> "
529
+ "<code>~~strike~~</code> <code>||spoiler||</code>\n"
530
+ "<code>`code`</code> and <code>```code block```</code> (<code>```python</code> and a line break names the language)\n"
531
+ "<code>[text](https://t.me/name)</code> - a link\n"
532
+ "<code>&gt; quote</code> - a line that starts with &gt; is quoted (<code>**&gt;</code> on the first line and "
533
+ "<code>||</code> at the end of the last one make it expandable)\n"
534
+ "<code>\\*</code> - a backslash keeps the next mark as it is. As in any Markdown, the marks must touch the text "
535
+ "(<code>**bold**</code>, not <code>** bold **</code>) and <code>_</code> inside a word does nothing.\n\n"
536
+ "<b>HTML</b>\n"
537
+ "<code>&lt;b&gt;bold&lt;/b&gt;</code> <code>&lt;i&gt;italic&lt;/i&gt;</code> "
538
+ "<code>&lt;u&gt;underline&lt;/u&gt;</code> <code>&lt;s&gt;strike&lt;/s&gt;</code> "
539
+ "<code>&lt;tg-spoiler&gt;spoiler&lt;/tg-spoiler&gt;</code>\n"
540
+ "<code>&lt;code&gt;code&lt;/code&gt;</code> <code>&lt;pre&gt;block&lt;/pre&gt;</code> "
541
+ "<code>&lt;a href=\"https://t.me/name\"&gt;link&lt;/a&gt;</code>\n"
542
+ "<code>&lt;blockquote&gt;quote&lt;/blockquote&gt;</code> (<code>&lt;blockquote expandable&gt;</code> for an "
543
+ "expandable one) and <code>&lt;br&gt;</code> for a line break.\n"
544
+ "Write <code>&amp;lt;</code> for a &lt; that must stay. A text that has an HTML tag with its closing tag is read "
545
+ "as HTML only.\n\n"
546
+ "<b>Example</b>\n"
547
+ "<pre>**Attack on Titan** - Episode 12\n"
548
+ "__Hindi__ | ||spoiler||\n"
549
+ "[Watch here](https://t.me/yourchannel)</pre>\n\n"
550
+ "🧩 Headings, lists, tables, expandable sections, math, maps, pictures and buttons are <b>rich messages</b> - "
551
+ "see /rich."
552
+ )
app/servicemsg.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Service messages: the notices Telegram puts into a channel by itself - "channel name changed", "channel photo
2
+ updated", "<admin> pinned a message", "live stream started" ... The bot removes them from every connected channel.
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import logging
7
+ from dataclasses import dataclass
8
+ from typing import Optional
9
+
10
+ from telethon import errors, functions, types
11
+
12
+ from .tgutil import flood_retry
13
+
14
+ log = logging.getLogger(__name__)
15
+
16
+ # Telegram refusals that mean "the bot has no right to delete here" (worth telling the owner about)
17
+ RIGHTS_ERRORS = ("ChatAdminRequiredError", "ChatWriteForbiddenError", "ChannelPrivateError", "UserNotParticipantError")
18
+
19
+
20
+ def is_service(m) -> bool:
21
+ return isinstance(m, types.MessageService)
22
+
23
+
24
+ def action_label(m) -> str:
25
+ """'PinMessage', 'ChatEditTitle', 'GroupCall' ... - for the log."""
26
+ name = type(getattr(m, "action", None)).__name__
27
+ return name[len("MessageAction"):] if name.startswith("MessageAction") else name
28
+
29
+
30
+ @dataclass
31
+ class Removed:
32
+ deleted: int = 0
33
+ failed: int = 0
34
+ error: Optional[BaseException] = None # the first thing Telegram refused with
35
+
36
+ @property
37
+ def error_name(self) -> Optional[str]:
38
+ return type(self.error).__name__ if self.error is not None else None
39
+
40
+
41
+ async def remove(client, peer, ids: list) -> Removed:
42
+ """Delete these messages, 100 per request. A refusal is reported in the result, never raised."""
43
+ out = Removed()
44
+ ids = sorted(set(ids))
45
+ for i in range(0, len(ids), 100):
46
+ part = ids[i : i + 100]
47
+ try:
48
+ res = await flood_retry(lambda part=part: client(functions.channels.DeleteMessagesRequest(channel=peer, id=part)))
49
+ except errors.RPCError as e:
50
+ out.failed += len(part)
51
+ out.error = out.error or e
52
+ continue
53
+ n = getattr(res, "pts_count", None)
54
+ out.deleted += len(part) if n is None else min(len(part), int(n))
55
+ return out
app/shift_engine.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """/shift: copy posts of one channel into another channel - text, formatting, media, albums, buttons and replies
2
+ - and register the copies in My posts. The source is only read, never changed or deleted.
3
+
4
+ It is the /repost copy loop pointed at two channels. Links from a shifted post to another post of the source channel
5
+ follow the content: when that post was shifted too, the link points at its copy in the destination.
6
+
7
+ Three optional extras are remembered with the shift (job marks), so that continuing a stopped shift keeps them:
8
+ -c afterwards every link to a post of the source, in ANY connected channel, is pointed at the copy
9
+ (crosslinks.relink_after_shift; the source itself is only read);
10
+ -all afterwards the destination gets the source's name, description and profile photo
11
+ (profile_copy.copy_profile);
12
+ --no-media the copies get no files: every post is copied as its text, with its formatting and buttons (mark "nomedia";
13
+ repost_engine.without_files). A post that is only a file has nothing to copy and is left out.
14
+
15
+ When Telegram hides the first new copies (read back right after posting) the shift stops by itself - more copies would
16
+ only be more posts nobody can see - and goes on only when the owner presses Continue (mark "hiddenok").
17
+
18
+ A source that Telegram restricts (a copyright strike: "This channel is unavailable due to copyright infringement", its
19
+ posts marked or shown as a notice) is copied from what My posts saved of its posts - every post that has a saved copy,
20
+ however intact Telegram's version looks (repost_engine.copy_source). A post without a saved copy is copied as Telegram
21
+ hands it out if that is the post itself, and skipped if it is only the notice. A source that can't be read at all (a
22
+ banned or private channel) is copied from My posts alone: mark "fromdb", set when the plan was made that way.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import logging
27
+ from types import SimpleNamespace
28
+ from typing import Any, Awaitable, Callable, Optional
29
+
30
+ from .crosslinks import CrossResult, relink_after_shift, shift_links
31
+ from .profile_copy import copy_profile
32
+ from .repost_engine import (
33
+ STOP_IF_HIDDEN,
34
+ CopyJob,
35
+ DeleteResult,
36
+ RepostOptions,
37
+ RepostPlan,
38
+ RepostResult,
39
+ copy_loop,
40
+ delete_pending,
41
+ plan_from_saved,
42
+ relink_copies,
43
+ saved_lookup,
44
+ saved_units,
45
+ )
46
+ from .restrictions import probe_channel
47
+ from .tgutil import peer_of
48
+
49
+ log = logging.getLogger(__name__)
50
+
51
+
52
+ def source_of(shift) -> SimpleNamespace:
53
+ """The source channel as stored with the shift (it need not be registered in the bot)."""
54
+ return SimpleNamespace(
55
+ id=shift.src_channel_id, access_hash=shift.src_access_hash, username=shift.src_username, title=shift.src_title
56
+ )
57
+
58
+
59
+ async def plan_from_my_posts(
60
+ db, src, first_id=None, last_id=None, unreadable=None, no_media: bool = False
61
+ ) -> Optional[RepostPlan]:
62
+ """The plan of a shift made from My posts alone, for a source that can't be read; None when My posts has nothing
63
+ of that channel (in that range)."""
64
+ plan = plan_from_saved(
65
+ src, await db.sent_posts_from(src.id, first_id or 1), RepostOptions(), first_id=first_id, last_id=last_id,
66
+ unreadable=unreadable, no_media=no_media,
67
+ )
68
+ return None if plan.error else plan
69
+
70
+
71
+ async def run_shift(
72
+ client,
73
+ db,
74
+ shift,
75
+ dst,
76
+ user_id: int,
77
+ *,
78
+ delay: float = 1.2,
79
+ settle_pause: float = 0.7,
80
+ progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None,
81
+ should_stop: Optional[Callable[[], bool]] = None,
82
+ ) -> RepostResult:
83
+ """Copy the posts shift.first_id..shift.last_id of the source into `dst` (a registered channel), in order.
84
+ Safe to run again to continue: posts that already have a copy are skipped."""
85
+ src = source_of(shift)
86
+ idmap = dict(await db.shift_pairs(shift.id, alive_only=False))
87
+ links = shift_links(src, dst, idmap)
88
+ marks = await db.marks_of(shift.id)
89
+ from_db = "fromdb" in marks # the source can't be read: its posts come from My posts alone
90
+ restricted = None
91
+ if not from_db: # does Telegram restrict the source channel itself (a copyright strike)? Then My posts is used
92
+ try:
93
+ _top, restricted, _err = await probe_channel(client, peer_of(src))
94
+ except Exception: # unknown is treated as "not restricted": marks on single posts and the read-back still guard
95
+ log.warning("could not ask Telegram whether the source channel is restricted", exc_info=True)
96
+ job = CopyJob(
97
+ src_peer=peer_of(src),
98
+ dst_peer=peer_of(dst),
99
+ opts=RepostOptions(),
100
+ links=links,
101
+ first_id=shift.first_id,
102
+ last_id=shift.last_id,
103
+ done=await db.shift_done_ids(shift.id),
104
+ idmap=idmap,
105
+ record=lambda rows: db.record_shift(shift.id, dst.id, rows, user_id),
106
+ saved=saved_lookup(db, src.id), # posts Telegram holds back (a copyright strike) are copied from My posts
107
+ use_saved=True,
108
+ units=(lambda: saved_units(db, src.id, shift.first_id, shift.last_id)) if from_db else None,
109
+ from_db=from_db,
110
+ restricted=restricted,
111
+ no_media="nomedia" in marks,
112
+ stop_if_hidden=0 if "hiddenok" in marks else STOP_IF_HIDDEN, # the owner said to go on although Telegram hides them
113
+ )
114
+ res = await copy_loop(client, job, delay=delay, progress=progress, should_stop=should_stop, settle_pause=settle_pause)
115
+ if not res.stopped and not res.aborted:
116
+ res.phase = "finish"
117
+ if progress:
118
+ await progress(res)
119
+ try:
120
+ pairs = await db.shift_pairs(shift.id)
121
+ res.final = await relink_copies(
122
+ client, db, dst, dict(pairs), [n for _, n in pairs], links=links, delay=delay,
123
+ settle_pause=settle_pause, should_stop=should_stop,
124
+ )
125
+ except Exception as e: # the copies are fine; only the links between them were not updated
126
+ log.exception("pointing the links of a shift at the copies failed")
127
+ res.final_error = type(e).__name__
128
+ marks = await db.marks_of(shift.id)
129
+ if "profile" in marks and "profile_done" not in marks:
130
+ await shift_profile(client, db, shift, dst, user_id, res, progress)
131
+ if "relink" in marks and not (res.final is not None and res.final.stopped):
132
+ res.phase = "links"
133
+ res.cross = CrossResult()
134
+
135
+ async def watch(_cross) -> None:
136
+ if progress:
137
+ await progress(res)
138
+
139
+ if progress:
140
+ await progress(res)
141
+ try:
142
+ await relink_after_shift(
143
+ client, db, shift, src, dst, delay=delay, settle_pause=settle_pause, progress=watch,
144
+ should_stop=should_stop, result=res.cross,
145
+ )
146
+ except Exception as e: # the copies are fine; only the links in the other channels were not updated
147
+ log.exception("pointing the links of the other channels at the shifted posts failed")
148
+ res.cross_error = type(e).__name__
149
+ return res
150
+
151
+
152
+ async def shift_profile(client, db, shift, dst, user_id: int, res: RepostResult, progress=None) -> None:
153
+ """-all: the destination takes over the source's name, description and photo (the outcome goes into `res`)."""
154
+ res.phase = "profile"
155
+ if progress:
156
+ await progress(res)
157
+ try:
158
+ res.profile = await copy_profile(client, source_of(shift), dst)
159
+ if res.profile.title: # the destination has a new name: keep the bot's own list right
160
+ await db.save_channel(dst.id, dst.access_hash, res.profile.title, dst.username, user_id)
161
+ if res.profile.ok:
162
+ await db.set_mark(shift.id, "profile_done")
163
+ except Exception as e: # the copies are fine; only the channel's name / description / photo were not copied
164
+ log.exception("copying the channel profile failed")
165
+ res.profile_error = type(e).__name__
166
+
167
+
168
+ async def delete_shift_copies(
169
+ client,
170
+ db,
171
+ dst,
172
+ shift,
173
+ *,
174
+ delay: float = 0.5,
175
+ progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None,
176
+ fallback: Optional[Callable[[list], Awaitable[Any]]] = None,
177
+ ) -> DeleteResult:
178
+ """Undo: remove the copies of this shift from the destination channel (the source is not touched)."""
179
+ todo = await db.shift_pending_new(shift.id, 1_000_000)
180
+
181
+ async def mark(ids: list) -> None:
182
+ await db.mark_shift_deleted(shift.id, dst.id, ids)
183
+
184
+ res = await delete_pending(client, peer_of(dst), todo, mark, delay=delay, progress=progress, fallback=fallback)
185
+ res.remaining = (await db.shift_counts(shift.id))["new_left"]
186
+ res.blocked = res.remaining > 0 and not res.error
187
+ return res
app/suggest.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Auto-suggest the next episode batch: 'Download Episodes 01 to 20' -> 'Download Episodes 21 to 40'."""
2
+ from __future__ import annotations
3
+
4
+ import copy
5
+ import re
6
+ from dataclasses import dataclass, field
7
+ from typing import Optional
8
+
9
+ from telethon.helpers import add_surrogate, del_surrogate
10
+
11
+ from .linkswap import apply_span_replacements
12
+ from .richmsg import is_rich
13
+ from .tgutil import de_entities, ser_entities
14
+
15
+ RANGE_RX = re.compile(r"(?P<a>\d+)(?P<sep>\s*(?:to|[-–—~&])\s*)(?P<pre>(?:ep?\.?\s*)?)(?P<b>\d+)", re.I)
16
+ SINGLE_RX = re.compile(r"(?<![\w.])(?P<label>episodes?|eps?\.?|e)(?P<gap>\s*[-:#]?\s*)(?P<n>\d+)(?!\d)", re.I)
17
+
18
+
19
+ @dataclass
20
+ class Advance:
21
+ new_text: str # the whole string with the numbers moved on
22
+ old_span: str # e.g. "01 to 20"
23
+ new_span: str # e.g. "21 to 40"
24
+
25
+
26
+ def advance_plain(s: str) -> Optional[Advance]:
27
+ """Move the first episode range (or single episode) in `s` on to the next batch."""
28
+ for m in RANGE_RX.finditer(s or ""):
29
+ a_s, b_s = m.group("a"), m.group("b")
30
+ a, b = int(a_s), int(b_s)
31
+ if a > b or b - a > 5000:
32
+ continue
33
+ step = b - a + 1
34
+ width = max(len(a_s), len(b_s)) if (a_s.startswith("0") or b_s.startswith("0")) else 0
35
+ na, nb = str(b + 1).zfill(width), str(b + step).zfill(width)
36
+ new_span = na + s[m.end("a"):m.start("b")] + nb
37
+ return Advance(
38
+ new_text=s[: m.start("a")] + new_span + s[m.end("b"):],
39
+ old_span=s[m.start("a"):m.end("b")],
40
+ new_span=new_span,
41
+ )
42
+ for m in SINGLE_RX.finditer(s or ""):
43
+ n_s = m.group("n")
44
+ width = len(n_s) if n_s.startswith("0") else 0
45
+ nn = str(int(n_s) + 1).zfill(width)
46
+ return Advance(
47
+ new_text=s[: m.start("n")] + nn + s[m.end("n"):],
48
+ old_span=s[m.start("label"):m.end("n")],
49
+ new_span=s[m.start("label"):m.start("n")] + nn,
50
+ )
51
+ return None
52
+
53
+
54
+ @dataclass
55
+ class Suggestion:
56
+ text: str
57
+ entities: list
58
+ buttons: list
59
+ media_kind: Optional[str]
60
+ media_file_id: Optional[str]
61
+ pending: list = field(default_factory=list) # [(row, col)] of buttons that still need a link
62
+ prev_label: str = ""
63
+ new_label: str = ""
64
+ source_post_id: int = 0
65
+
66
+
67
+ def build_suggestion(post) -> Optional[Suggestion]:
68
+ if is_rich(post): # its text lives in blocks Telegram made: the numbers can't be moved on in them
69
+ return None
70
+ rows: list = []
71
+ pending: list = []
72
+ first: Optional[Advance] = None
73
+ prev_label = ""
74
+ for row in post.buttons or []:
75
+ new_row: list = []
76
+ for b in row:
77
+ if b.get("raw"): # other bots' buttons (e.g. reactions) are not carried over
78
+ continue
79
+ b = dict(b)
80
+ b.pop("s", None)
81
+ adv = advance_plain(b.get("t", "")) if b.get("u") else None
82
+ if adv:
83
+ if first is None:
84
+ first, prev_label = adv, b["t"]
85
+ b["t"] = adv.new_text
86
+ b["u"] = None
87
+ pending.append((len(rows), len(new_row)))
88
+ new_row.append(b)
89
+ if new_row:
90
+ rows.append(new_row)
91
+ if not pending or first is None:
92
+ return None
93
+
94
+ text = post.text or ""
95
+ entities = copy.deepcopy(post.entities or [])
96
+ sur = add_surrogate(text)
97
+ repls: list = []
98
+ pos = 0
99
+ while first.old_span:
100
+ i = sur.find(first.old_span, pos)
101
+ if i < 0:
102
+ break
103
+ repls.append((i, i + len(first.old_span), first.new_span))
104
+ pos = i + len(first.old_span)
105
+ if repls:
106
+ new_sur, new_ents = apply_span_replacements(sur, de_entities(entities), repls)
107
+ text, entities = del_surrogate(new_sur), ser_entities(new_ents)
108
+
109
+ return Suggestion(
110
+ text=text,
111
+ entities=entities,
112
+ buttons=rows,
113
+ media_kind=post.media_kind,
114
+ media_file_id=post.media_file_id,
115
+ pending=pending,
116
+ prev_label=prev_label,
117
+ new_label=rows[pending[0][0]][pending[0][1]]["t"],
118
+ source_post_id=post.id,
119
+ )
120
+
121
+
122
+ async def make_suggestion(db, channel_id: int) -> Optional[Suggestion]:
123
+ for p in await db.latest_sent(channel_id, 30):
124
+ s = build_suggestion(p)
125
+ if s:
126
+ return s
127
+ return None
app/sync_engine.py ADDED
@@ -0,0 +1,600 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Keeps My posts in step with the channels: what admins do outside the bot is noticed and recorded.
2
+
3
+ What a look at a channel does
4
+ * every post the bot has saved is read back from Telegram: a post that is gone is removed here, a post that was edited
5
+ gets its saved copy updated (text, formatting, buttons, media);
6
+ * messages that appeared since the last look are saved as new posts (source "adopted");
7
+ * the posts that were in the channel BEFORE the bot was added are read into My posts too, oldest first, up to the
8
+ newest message that existed at the first look. Where the reading stopped is saved, so a long channel takes a few
9
+ looks. Posts the owner told the bot to forget are skipped for good;
10
+ * service messages ("channel name changed", "pinned a message", video chat ...) found on the way are deleted.
11
+
12
+ Safety rules
13
+ * posts the bot touched a moment ago, and messages that appeared a moment ago, are left for the next look (the bot may
14
+ still be saving them);
15
+ * a saved copy is only changed if nobody changed it since it was read (optimistic check in the database);
16
+ * buttons that are missing in the channel are never removed from the saved copy (Telegram sometimes hides a keyboard
17
+ for a while - the saved buttons are what "Check buttons" restores from);
18
+ * if EVERY saved post of a channel looks deleted, the bot first makes sure it can read the channel at all: when it
19
+ still sees other messages there (or the channel's event counter moved by at least that many events, which is what
20
+ really deleting them looks like) the posts are really gone and leave My posts; only when it sees nothing at all
21
+ - more likely the bot lost access - is nothing removed;
22
+ * what TELEGRAM does to a channel is not an admin's edit: a channel it restricts (a copyright strike turns every post
23
+ into "This message couldn't be displayed on your device due to copyright infringement"), a single post it holds
24
+ back, a notice shown instead of a post, or many posts that suddenly all show one and the same text are left exactly
25
+ as saved - nothing is edited, removed or added for them.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ import logging
31
+ import time
32
+ from dataclasses import dataclass, field
33
+ from typing import Any, Optional
34
+
35
+ from telethon import errors, types
36
+
37
+ from .db import as_utc, utcnow
38
+ from .replace_engine import fetch_messages
39
+ from .repost_engine import delete_batch
40
+ from .restrictions import message_restriction, norm_text, probe_channel
41
+ from .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of, with_fingerprint
42
+ from .tgutil import classify_media, explain_rpc, media_from_ref, media_info, peer_of, ser_entities, ser_markup
43
+
44
+ log = logging.getLogger(__name__)
45
+
46
+ CHUNK = 100 # Telegram returns at most 100 messages per request
47
+ GRACE = 120.0 # seconds a post or message must be old before it is judged
48
+ PAUSE = 0.25 # between two requests of a scan
49
+ SLACK_CAP = 300 # a quick look reads this many ids beyond the most likely end of the new messages
50
+ DEEP_EVERY = 24 * 3600 # the automatic looks read every possible id at least this often
51
+ MIN_FOR_ANOMALY = 5
52
+ MASS_SAME = 5 # this many posts that suddenly show the very same new text are not edits by a person
53
+ MAX_PROBE = 300 # requests spent finding the newest message the first time (30 000 ids)
54
+
55
+
56
+ # ----------------------------------------------------------------------------------------------- options
57
+ @dataclass
58
+ class SyncOptions:
59
+ deep: bool = False # read every possible id for new messages, not only the likely ones
60
+ delete_services: bool = True
61
+ adopt: bool = True # save new posts of others
62
+ history: bool = True # also read the posts from before the bot was added into My posts
63
+ history_seconds: Optional[float] = None # ... for at most this long per look (None: as long as it takes)
64
+ grace: float = GRACE
65
+ pause: float = PAUSE
66
+ ignore: Any = field(default_factory=set) # (channel id, message id) of posts the owner told the bot to forget
67
+
68
+
69
+ @dataclass
70
+ class SyncReport:
71
+ channel: Any
72
+ phase: str = ""
73
+ checked: int = 0 # saved posts compared with the channel
74
+ deleted: list = field(default_factory=list) # message ids that were gone: removed from My posts
75
+ edited: list = field(default_factory=list) # message ids whose saved copy was brought up to date
76
+ refreshed: int = 0 # saved copies corrected for trifles (a trailing space ...)
77
+ adopted: list = field(default_factory=list) # message ids of new posts that were saved
78
+ imported: int = 0 # older posts (from before the bot was added) that were added to My posts
79
+ history_unsupported: int = 0 # older messages My posts can't hold (polls, stickers ...)
80
+ history_top: int = 0 # the newest message that counts as older (0: the older posts were not looked at)
81
+ history_to: int = 0 # the older posts have been read up to this message id
82
+ history_done: bool = False # ... and that was all of them
83
+ unsupported: int = 0 # new messages of a kind My posts can't show (polls, stickers ...)
84
+ buttons_missing: list = field(default_factory=list) # saved buttons that the channel shows no keyboard for
85
+ services_deleted: int = 0
86
+ services_failed: int = 0
87
+ services_error: Optional[str] = None # name of the refusal
88
+ restricted: list = field(default_factory=list) # message ids Telegram holds back (copyright ...): left as saved
89
+ restricted_why: Optional[str] = None # what Telegram says about them
90
+ restricted_channel: Optional[str] = None # the whole channel is restricted: nothing was looked at
91
+ young: list = field(default_factory=list) # saved posts the bot touched a moment ago: judge them later
92
+ young_new: list = field(default_factory=list) # new messages that appeared a moment ago: save them later
93
+ changed_meanwhile: int = 0 # saved posts that were changed through the bot while we looked (left alone)
94
+ first_look: bool = False
95
+ busy: bool = False # a long job started: the look was cut short
96
+ anomaly: Optional[str] = None
97
+ error: Optional[str] = None
98
+ scanned_to: int = 0
99
+
100
+ @property
101
+ def changed(self) -> bool:
102
+ return bool(self.deleted or self.edited or self.adopted or self.imported or self.services_deleted)
103
+
104
+
105
+ # ------------------------------------------------------------------------------------- comparing a post
106
+ def age(dt, now) -> float:
107
+ """Seconds since `dt` (never negative); unknown = very old."""
108
+ if dt is None:
109
+ return float("inf")
110
+ return max(0.0, (now - as_utc(dt)).total_seconds())
111
+
112
+
113
+ def media_key(media) -> Optional[tuple]:
114
+ """Which photo / file a message carries (its id - the file reference changes from fetch to fetch)."""
115
+ if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None):
116
+ return ("photo", media.photo.id)
117
+ if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None):
118
+ return ("doc", media.document.id)
119
+ return None
120
+
121
+
122
+ def stored_media_key(ref: Optional[str]) -> Optional[tuple]:
123
+ if not ref:
124
+ return None
125
+ try:
126
+ return media_key(media_from_ref(ref))
127
+ except Exception:
128
+ return ("unreadable", ref[:40]) # differs from anything real: the saved reference gets replaced
129
+
130
+
131
+ def live_rich(m) -> Optional[Rich]:
132
+ """The rich message the live message is (as blocks), or None for an ordinary post."""
133
+ rm = getattr(m, "rich_message", None)
134
+ return rich_from_received(rm) if rm is not None else None
135
+
136
+
137
+ def live_fields(m) -> dict:
138
+ """The saved-post fields of a message as it is in the channel now."""
139
+ kind, ref = media_info(m)
140
+ rich = live_rich(m)
141
+ return {
142
+ "text": plain_of_message(m) if rich is not None else (m.message or ""),
143
+ "entities": [rich_entry(rich)] if rich is not None else ser_entities(m.entities),
144
+ "buttons": ser_markup(m.reply_markup),
145
+ "media_kind": kind,
146
+ "media_file_id": ref,
147
+ }
148
+
149
+
150
+ def message_supported(m) -> bool:
151
+ """Something My posts can show and edit: text, a rich message, or a photo / video / GIF / audio / file."""
152
+ return bool((m.message or "").strip()) or classify_media(m) is not None or is_rich_message(m)
153
+
154
+
155
+ def adopt_fields(m) -> dict:
156
+ f = live_fields(m)
157
+ f["link_preview"] = isinstance(getattr(m, "media", None), types.MessageMediaWebPage)
158
+ return f
159
+
160
+
161
+ # ------------------------------------------------------------------- what Telegram itself does to a channel
162
+ MASS_NOTE = "many posts suddenly show one and the same text - that is Telegram's notice, not an edit"
163
+
164
+
165
+ def split_mass_text(edits: list) -> tuple:
166
+ """(edits to save, edits to hold back). Five or more saved posts that had five different texts and now all show the
167
+ very same text at once: nobody edits like that - Telegram does it to a channel it restricts."""
168
+ groups: dict = {}
169
+ for item in edits:
170
+ new = norm_text(item[1].fields.get("text"))
171
+ if new:
172
+ groups.setdefault(new, []).append(item)
173
+ bad: set = set()
174
+ for items in groups.values():
175
+ if len(items) >= MASS_SAME and len({norm_text(p.text) for p, _ in items}) >= MASS_SAME:
176
+ bad.update(id(i) for i in items)
177
+ return [i for i in edits if id(i) not in bad], [i for i in edits if id(i) in bad]
178
+
179
+
180
+ def hold_back(rep: "SyncReport", ids, why: Optional[str]) -> None:
181
+ rep.restricted.extend(ids)
182
+ rep.restricted_why = rep.restricted_why or why
183
+
184
+
185
+ @dataclass
186
+ class Diff:
187
+ fields: dict = field(default_factory=dict) # what to save
188
+ buttons_missing: bool = False
189
+ quiet: bool = False # only a trifle differs (surrounding spaces): fix it without counting it as an edit
190
+
191
+
192
+ def diff_post(p, m) -> Diff:
193
+ """What differs between the saved post `p` and the live message `m`."""
194
+ live = live_fields(m)
195
+ fields: dict = {}
196
+ saved_rich, now_rich = rich_of(p), live_rich(m) if is_rich_message(m) else None
197
+ first_look = False
198
+ if saved_rich is None and now_rich is None:
199
+ if (p.text or "") != live["text"]:
200
+ fields["text"] = live["text"]
201
+ if list(p.entities or []) != live["entities"]:
202
+ fields["entities"] = live["entities"]
203
+ elif now_rich is not None:
204
+ # A rich message is compared by what Telegram shows of it (a fingerprint of its blocks), never by its text: the
205
+ # saved copy keeps the source the bot sent. A post that became rich in the channel is taken over as its blocks.
206
+ if saved_rich is None or (saved_rich.fp is not None and saved_rich.fp != now_rich.fp):
207
+ fields["text"], fields["entities"] = live["text"], live["entities"]
208
+ elif saved_rich.fp is None: # the bot's own rich post, seen for the first time: remember what Telegram shows
209
+ fields["entities"] = [rich_entry(with_fingerprint(saved_rich, now_rich.fp))]
210
+ first_look = True
211
+ elif live["text"].strip() or live["media_kind"] is not None:
212
+ # the channel shows an ordinary post where a rich message was saved (an empty answer is not trusted)
213
+ fields["text"], fields["entities"] = live["text"], live["entities"]
214
+ # media: replaced media is taken over; media that seems to have vanished is not (a message can't lose its media)
215
+ if live["media_kind"] is not None:
216
+ if p.media_kind != live["media_kind"] or stored_media_key(p.media_file_id) != media_key(m.media):
217
+ fields["media_kind"], fields["media_file_id"] = live["media_kind"], live["media_file_id"]
218
+ missing = False
219
+ if live["buttons"]:
220
+ if list(p.buttons or []) != live["buttons"]:
221
+ fields["buttons"] = live["buttons"]
222
+ elif p.buttons:
223
+ missing = True
224
+ quiet = (set(fields) == {"text"} and (p.text or "").strip() == live["text"].strip()) or (
225
+ first_look and set(fields) == {"entities"}
226
+ )
227
+ return Diff(fields, missing, quiet)
228
+
229
+
230
+ # --------------------------------------------------------------------------------------- talking to Telegram
231
+ def is_gone(m) -> bool:
232
+ return m is None or isinstance(m, types.MessageEmpty)
233
+
234
+
235
+ async def find_top(client, peer, pts: int, floor: int, *, pause: float = PAUSE) -> int:
236
+ """The newest message id that exists. Only the event counter is known (never lower), so look downwards from it;
237
+ `floor` (the newest saved post) is where the looking can stop."""
238
+ hi = pts
239
+ for _ in range(MAX_PROBE):
240
+ if hi <= floor:
241
+ break
242
+ lo = max(floor + 1, hi - CHUNK + 1)
243
+ msgs = await fetch_messages(client, peer, list(range(lo, hi + 1)))
244
+ alive = [m.id for m in msgs if not is_gone(m)]
245
+ if alive:
246
+ return max(alive)
247
+ hi = lo - 1
248
+ await asyncio.sleep(pause)
249
+ return max(floor, hi)
250
+
251
+
252
+ async def sees_live_messages(client, peer, pts: Optional[int], *, pause: float = PAUSE, tries: int = MAX_PROBE) -> bool:
253
+ """True when the bot can read at least one message of the channel (a post or a service message). Then a saved post
254
+ that is missing from the channel really is gone - the bot is not just blind. Looks downwards from the event counter."""
255
+ if not pts or pts < 1:
256
+ return False
257
+ hi = pts
258
+ for _ in range(tries):
259
+ if hi < 1:
260
+ return False
261
+ lo = max(1, hi - CHUNK + 1)
262
+ msgs = await fetch_messages(client, peer, list(range(lo, hi + 1)))
263
+ if any(not is_gone(m) for m in msgs):
264
+ return True
265
+ hi = lo - 1
266
+ await asyncio.sleep(pause)
267
+ return False
268
+
269
+
270
+ async def delete_services(client, peer, ids: list, rep: SyncReport) -> None:
271
+ """Delete service messages and count what happened (the bot only: Telegram may refuse the old ones)."""
272
+ ids = sorted(set(ids))
273
+ for i in range(0, len(ids), CHUNK):
274
+ part = ids[i : i + CHUNK]
275
+ out = await delete_batch(client, peer, part)
276
+ rep.services_deleted += len(out.gone)
277
+ left = len(part) - len(out.gone)
278
+ if left:
279
+ rep.services_failed += left
280
+ rep.services_error = rep.services_error or out.bot_error or "NotDeleted"
281
+
282
+
283
+ # ------------------------------------------------------------------------------------- the three steps
284
+ async def _save_edits(db, rep: SyncReport, edits: list, busy) -> None:
285
+ for p, d in edits:
286
+ if busy():
287
+ rep.busy = True
288
+ return
289
+ if await db.sync_update_post(p.id, p.updated_at, d.fields):
290
+ if d.quiet:
291
+ rep.refreshed += 1
292
+ else:
293
+ rep.edited.append(p.message_id)
294
+ else:
295
+ rep.changed_meanwhile += 1
296
+
297
+
298
+ async def _adopt(db, ch, rep: SyncReport, fresh: list, opts: SyncOptions, busy, now) -> None:
299
+ """Save messages the bot does not know (ascending ids); too fresh ones are left for the next look."""
300
+ known: set = set()
301
+ ids = [m.id for m in fresh]
302
+ for i in range(0, len(ids), 500):
303
+ known |= {p.message_id for p in await db.posts_at(ch.id, ids[i : i + 500])}
304
+ forgotten = await db.ignored_ids(ch.id) if fresh else set()
305
+ todo = []
306
+ for m in fresh:
307
+ if m.id in known or m.id in forgotten or (ch.id, m.id) in opts.ignore:
308
+ continue
309
+ why = message_restriction(m)
310
+ if why: # Telegram holds it back: what it shows now is not what the post says
311
+ hold_back(rep, [m.id], why)
312
+ elif age(m.date, now) < opts.grace:
313
+ rep.young_new.append(m.id)
314
+ elif not message_supported(m):
315
+ rep.unsupported += 1
316
+ else:
317
+ todo.append(m)
318
+ for m in todo:
319
+ if busy():
320
+ rep.busy = True
321
+ return
322
+ _, created = await db.adopt_message(ch.id, m.id, adopt_fields(m), sent_at=m.date)
323
+ if created:
324
+ rep.adopted.append(m.id)
325
+
326
+
327
+ async def _compare_saved(
328
+ client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, moved=None, pts: Optional[int] = None
329
+ ) -> None:
330
+ """Every saved post against the channel. `moved`: how far the channel's event counter has come since the last look
331
+ (None: unknown) - deleting posts is an event each, which tells "everything was deleted" from "I can't see anything".
332
+ `pts`: the channel's event counter now - where the bot looks for other messages to prove that it can read the channel."""
333
+ rep.phase = "comparing the saved posts"
334
+ peer = peer_of(ch)
335
+ posts = await db.sent_posts(ch.id) # the saved copies are read BEFORE the channel is, never after
336
+ now = utcnow()
337
+ judge = []
338
+ for p in posts:
339
+ if min(age(p.updated_at, now), age(p.sent_at, now)) < opts.grace:
340
+ rep.young.append(p.message_id)
341
+ else:
342
+ judge.append(p)
343
+ rep.checked = len(judge)
344
+ by_id = {p.message_id: p for p in judge}
345
+ ids = sorted(by_id)
346
+ gone, edits = [], []
347
+ for i in range(0, len(ids), CHUNK):
348
+ if busy():
349
+ rep.busy = True
350
+ return
351
+ chunk = ids[i : i + CHUNK]
352
+ msgs = await fetch_messages(client, peer, chunk)
353
+ for mid, m in zip(chunk, msgs):
354
+ p = by_id[mid]
355
+ if is_gone(m):
356
+ gone.append(p)
357
+ elif isinstance(m, types.MessageService):
358
+ continue # not a post any more (cannot happen: ids are never reused)
359
+ else:
360
+ why = message_restriction(m, p.text)
361
+ if why: # Telegram's doing, not an admin's: the saved copy stays exactly as it is
362
+ hold_back(rep, [mid], why)
363
+ continue
364
+ d = diff_post(p, m)
365
+ if d.buttons_missing:
366
+ rep.buttons_missing.append(mid)
367
+ if d.fields:
368
+ edits.append((p, d))
369
+ rep.scanned_to = chunk[-1]
370
+ if progress:
371
+ await progress(rep)
372
+ await asyncio.sleep(opts.pause)
373
+ edits, held = split_mass_text(edits)
374
+ if held:
375
+ hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE)
376
+ if gone:
377
+ really = moved is not None and moved >= len(gone) # at least one event for each post that vanished
378
+ everything = len(ids) >= MIN_FOR_ANOMALY and len(gone) == len(ids)
379
+ if everything and not really:
380
+ # No earlier look to compare with (or too few events): is the bot blind, or are the posts really gone? If it
381
+ # can read other messages of the channel it is not blind.
382
+ if busy():
383
+ rep.busy = True
384
+ return
385
+ really = await sees_live_messages(client, peer, pts, pause=opts.pause)
386
+ if everything and not really:
387
+ rep.anomaly = (
388
+ f"All {len(ids)} saved posts look deleted, and I can't read any other message of the channel either, "
389
+ "so none was removed here - check that the bot is still an admin of the channel."
390
+ )
391
+ else:
392
+ gone_ids = [p.message_id for p in gone]
393
+ await db.forget_posts(ch.id, gone_ids)
394
+ rep.deleted.extend(gone_ids)
395
+ await _save_edits(db, rep, edits, busy)
396
+
397
+
398
+ async def _look_for_new(client, db, ch, rep: SyncReport, opts: SyncOptions, state, pts: int, busy, progress) -> None:
399
+ """Messages that appeared since the last look: new posts are saved, service messages deleted."""
400
+ rep.phase = "looking for new posts"
401
+ peer = peer_of(ch)
402
+ now = utcnow()
403
+ if state is None: # the first look: only note where the channel stands
404
+ floor = await db.max_saved_id(ch.id)
405
+ top = await find_top(client, peer, pts, floor, pause=opts.pause)
406
+ rep.first_look, rep.scanned_to = True, top
407
+ await db.save_sync(ch.id, last_top=top, last_pts=pts, deferred=0, deep=True)
408
+ return
409
+ deep = opts.deep or age(state.last_deep, now) > DEEP_EVERY
410
+ if pts == state.last_pts and not state.deferred and not deep:
411
+ return # not a single event since the last look: a quick look would read exactly what it read then
412
+ delta = max(0, pts - state.last_pts)
413
+ slack = min(max(0, state.last_pts - state.last_top), SLACK_CAP)
414
+ soft = pts if deep else min(pts, state.last_top + delta + slack)
415
+ a, highest, had_live = state.last_top + 1, state.last_top, True
416
+ fresh, services = [], []
417
+ while a <= pts:
418
+ if a > soft and not had_live:
419
+ break # past the likely end and the last stretch was empty
420
+ if busy():
421
+ rep.busy = True
422
+ return
423
+ hi = min(a + CHUNK - 1, pts)
424
+ msgs = await fetch_messages(client, peer, list(range(a, hi + 1)))
425
+ had_live = False
426
+ for m in msgs:
427
+ if is_gone(m):
428
+ continue
429
+ had_live = True
430
+ highest = max(highest, m.id)
431
+ if isinstance(m, types.MessageService):
432
+ services.append(m)
433
+ else:
434
+ fresh.append(m)
435
+ rep.scanned_to = hi
436
+ if progress:
437
+ await progress(rep)
438
+ a = hi + 1
439
+ await asyncio.sleep(opts.pause)
440
+ services_ids = [m.id for m in services]
441
+ if opts.delete_services and services_ids:
442
+ await delete_services(client, peer, services_ids, rep)
443
+ if opts.adopt and fresh:
444
+ await _adopt(db, ch, rep, fresh, opts, busy, now)
445
+ if rep.busy:
446
+ return
447
+ new_top = highest
448
+ if rep.young_new: # these have to be looked at again: don't move the mark past them
449
+ new_top = min(new_top, min(rep.young_new) - 1)
450
+ await db.save_sync(
451
+ ch.id, last_top=max(state.last_top, new_top), last_pts=pts, deferred=len(rep.young_new), deep=deep
452
+ )
453
+
454
+
455
+ async def _import_history(client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, state=None) -> None:
456
+ """The posts that were in the channel before the bot was added are read into My posts: from message 1 up to the newest
457
+ message that existed at the first look (what came after is the business of _look_for_new). The place where the
458
+ reading stopped is saved - a long channel takes a few looks, and a restart loses nothing. `state`: where the look
459
+ before this one stopped (None at the very first look: the mark that look has just set is used)."""
460
+ hist = await db.get_history(ch.id)
461
+ if hist is None:
462
+ base = state if state is not None else await db.get_sync(ch.id)
463
+ if base is None:
464
+ return
465
+ hist = await db.start_history(ch.id, base.last_top)
466
+ if hist.done:
467
+ return
468
+ rep.phase = "reading the older posts"
469
+ peer = peer_of(ch)
470
+ began = time.monotonic()
471
+ forgotten = await db.ignored_ids(ch.id)
472
+ rep.history_top = hist.top
473
+ a = hist.next_id
474
+ rep.history_to = a - 1
475
+ while a <= hist.top:
476
+ if busy():
477
+ rep.busy = True
478
+ return
479
+ if opts.history_seconds is not None and time.monotonic() - began > opts.history_seconds:
480
+ return # the next look goes on from here
481
+ hi = min(a + CHUNK - 1, hist.top)
482
+ msgs = await fetch_messages(client, peer, list(range(a, hi + 1)))
483
+ now = utcnow()
484
+ stop = None
485
+ todo = []
486
+ # posts the bot has saved already are none of the reading's business: the comparison of the saved posts looks
487
+ # after them (and counts the ones Telegram holds back there - not a second time here)
488
+ have = {p.message_id for p in await db.posts_at(ch.id, [m.id for m in msgs if not is_gone(m)])}
489
+ for m in msgs:
490
+ if is_gone(m) or isinstance(m, types.MessageService):
491
+ continue
492
+ if age(m.date, now) < opts.grace: # the bot may still be saving it: the next look reads it
493
+ stop = m.id
494
+ break
495
+ if m.id in forgotten or m.id in have or (ch.id, m.id) in opts.ignore:
496
+ continue
497
+ why = message_restriction(m)
498
+ if why:
499
+ hold_back(rep, [m.id], why)
500
+ elif not message_supported(m):
501
+ rep.history_unsupported += 1
502
+ else:
503
+ todo.append(m)
504
+ made = await db.adopt_many(ch.id, [(m.id, adopt_fields(m), m.date) for m in todo]) # (skips what is saved)
505
+ rep.imported += len(made)
506
+ a = hi + 1 if stop is None else stop
507
+ rep.history_done = stop is None and a > hist.top
508
+ await db.save_history(ch.id, next_id=a, imported=len(made), done=rep.history_done)
509
+ rep.history_to = rep.scanned_to = a - 1
510
+ if stop is not None:
511
+ return
512
+ if progress:
513
+ await progress(rep)
514
+ await asyncio.sleep(opts.pause)
515
+ rep.history_done = True # (also the case when the channel had nothing to read)
516
+
517
+
518
+ # ----------------------------------------------------------------------------------------- entry points
519
+ async def sync_channel(client, db, ch, opts: Optional[SyncOptions] = None, *, busy=None, progress=None) -> SyncReport:
520
+ """One full look at a channel (see the module text). Never raises Telegram's refusals: they end up in `report.error`."""
521
+ opts = opts or SyncOptions()
522
+ busy = busy or (lambda: False)
523
+ rep = SyncReport(channel=ch)
524
+ pts, restricted, err = await probe_channel(client, peer_of(ch))
525
+ if pts is None:
526
+ rep.error = err
527
+ return rep
528
+ if restricted: # Telegram restricted the channel (a copyright strike ...): My posts stay untouched
529
+ rep.restricted_channel = restricted
530
+ return rep
531
+ try:
532
+ state = await db.get_sync(ch.id)
533
+ moved = None if state is None else max(0, pts - state.last_pts)
534
+ await _compare_saved(client, db, ch, rep, opts, busy, progress, moved, pts)
535
+ if not rep.busy:
536
+ await _look_for_new(client, db, ch, rep, opts, state, pts, busy, progress)
537
+ if not rep.busy and opts.history:
538
+ await _import_history(client, db, ch, rep, opts, busy, progress, state)
539
+ except errors.RPCError as e:
540
+ rep.error = explain_rpc(e)
541
+ return rep
542
+
543
+
544
+ async def sync_ids(client, db, ch, ids, opts: Optional[SyncOptions] = None, *, adopt_ids=(), busy=None) -> SyncReport:
545
+ """A look at these messages only - the ones an update told about. `adopt_ids`: the ones that are new posts, so a
546
+ message the bot does not know may be saved (an edited message the bot does not know is history: left alone)."""
547
+ opts = opts or SyncOptions()
548
+ busy = busy or (lambda: False)
549
+ rep = SyncReport(channel=ch)
550
+ peer = peer_of(ch)
551
+ ids = sorted(set(ids))
552
+ adopt_set = set(adopt_ids)
553
+ try:
554
+ rows = {p.message_id: p for p in await db.posts_at(ch.id, ids)} # saved copies first, the channel second
555
+ now = utcnow()
556
+ gone, edits, fresh, services = [], [], [], []
557
+ for i in range(0, len(ids), CHUNK):
558
+ if busy():
559
+ rep.busy = True
560
+ return rep
561
+ chunk = ids[i : i + CHUNK]
562
+ msgs = await fetch_messages(client, peer, chunk)
563
+ for mid, m in zip(chunk, msgs):
564
+ row = rows.get(mid)
565
+ recent = row is not None and min(age(row.updated_at, now), age(row.sent_at, now)) < opts.grace
566
+ if is_gone(m):
567
+ if row is not None and not recent:
568
+ gone.append(row)
569
+ elif isinstance(m, types.MessageService):
570
+ services.append(mid)
571
+ elif row is not None:
572
+ why = message_restriction(m, row.text)
573
+ if why: # Telegram's doing, not an admin's: the saved copy stays exactly as it is
574
+ hold_back(rep, [mid], why)
575
+ continue
576
+ if recent:
577
+ rep.young.append(mid)
578
+ continue
579
+ d = diff_post(row, m)
580
+ if d.buttons_missing:
581
+ rep.buttons_missing.append(mid)
582
+ if d.fields:
583
+ edits.append((row, d))
584
+ elif mid in adopt_set:
585
+ fresh.append(m)
586
+ if opts.delete_services and services:
587
+ await delete_services(client, peer, services, rep)
588
+ edits, held = split_mass_text(edits)
589
+ if held:
590
+ hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE)
591
+ if gone:
592
+ gone_ids = [p.message_id for p in gone]
593
+ await db.forget_posts(ch.id, gone_ids)
594
+ rep.deleted.extend(gone_ids)
595
+ await _save_edits(db, rep, edits, busy)
596
+ if opts.adopt and fresh and not rep.busy:
597
+ await _adopt(db, ch, rep, fresh, opts, busy, now)
598
+ except errors.RPCError as e:
599
+ rep.error = explain_rpc(e)
600
+ return rep
app/syncer.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The background side of the sync.
2
+
3
+ * a timer: every SYNC_INTERVAL_MINUTES each connected channel is compared with My posts (app/sync_engine.py);
4
+ * a queue for what Telegram tells the bot while it runs: a post deleted / edited / added in a channel is looked at a few
5
+ seconds later (the wait lets a burst of changes settle, and lets the bot finish saving its own posts first);
6
+ * service messages ("pinned a message", "channel photo changed" ...) are deleted the moment they appear.
7
+
8
+ Nothing here holds the bot's one-long-job lock: a running /repost, /shift, /swap ... always wins, and what happens
9
+ while it runs is picked up by the next timed check.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import logging
15
+ import time
16
+ from typing import Optional
17
+
18
+ from .servicemsg import RIGHTS_ERRORS, action_label, remove
19
+ from .sync_engine import SyncOptions, SyncReport, sync_channel, sync_ids
20
+ from .tgutil import esc, peer_of
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+
25
+ class Syncer:
26
+ def __init__(self, ctx):
27
+ self.ctx = ctx
28
+ # timings (seconds) - the tests make them small
29
+ self.start_delay = 90.0 # after the bot starts, before the first timed check
30
+ self.debounce = 5.0 # quiet time needed before the queue is worked off
31
+ self.max_debounce = 30.0 # ... but never wait longer than this
32
+ self.lock_wait = 30.0 # a long job runs: look again after this
33
+ self.rt_grace = 10.0 # live changes: posts the bot touched / messages younger than this are judged next round
34
+ self.pause = 0.25 # between two requests
35
+ self.cache_ttl = 60.0 # how long "is this channel connected?" is remembered
36
+ self.tell_every = 86400.0 # the same warning goes to the owners at most this often
37
+ self.tell_restricted_every = 7 * 86400.0 # ... a restriction by Telegram can last for weeks: once a week
38
+ self.max_ids = 300 # more changed ids than this in one channel: look at the whole channel instead
39
+ self.max_tries = 8 # a message that stays "too fresh" is given up after this many rounds
40
+ self.history_seconds = 150.0 # a timed check reads a channel's older posts for this long, then goes on next time
41
+ self._busy = asyncio.Lock() # one look at a time
42
+ self._edits: dict = {} # channel id -> message ids edited
43
+ self._news: dict = {} # channel id -> message ids that are new posts
44
+ self._tries: dict = {}
45
+ self._stamp = 0
46
+ self._wake = asyncio.Event()
47
+ self._tasks: list = []
48
+ self._cache: dict = {}
49
+ self._told: dict = {}
50
+ self.last_reports: dict = {} # channel id -> its latest SyncReport
51
+
52
+ # ----------------------------------------------------------------------------------------- running
53
+ @property
54
+ def enabled(self) -> bool:
55
+ return self.ctx.cfg.sync_interval_minutes > 0
56
+
57
+ def start(self) -> None:
58
+ if self._tasks or not self.enabled:
59
+ return
60
+ self._tasks = [
61
+ asyncio.create_task(self._periodic(), name="sync-timer"),
62
+ asyncio.create_task(self._events(), name="sync-live"),
63
+ ]
64
+
65
+ async def stop(self) -> None:
66
+ tasks, self._tasks = self._tasks, []
67
+ for t in tasks:
68
+ t.cancel()
69
+ for t in tasks:
70
+ try:
71
+ await t
72
+ except (asyncio.CancelledError, Exception):
73
+ pass
74
+
75
+ async def _periodic(self) -> None:
76
+ await asyncio.sleep(self.start_delay)
77
+ while True:
78
+ try:
79
+ await self.run_all()
80
+ except asyncio.CancelledError:
81
+ raise
82
+ except Exception:
83
+ log.exception("the timed check of the channels failed")
84
+ await asyncio.sleep(max(5, self.ctx.cfg.sync_interval_minutes) * 60)
85
+
86
+ async def _events(self) -> None:
87
+ while True:
88
+ await self._wake.wait()
89
+ self._wake.clear()
90
+ try:
91
+ await self.flush_events()
92
+ except asyncio.CancelledError:
93
+ raise
94
+ except Exception:
95
+ log.exception("working off the channel changes failed")
96
+
97
+ # ----------------------------------------------------------------------------------------- helpers
98
+ async def channel(self, cid: int):
99
+ """The connected channel with this id, or None (remembered for a minute: busy channels cost no database reads)."""
100
+ now = time.monotonic()
101
+ hit = self._cache.get(cid)
102
+ if hit is not None and now - hit[0] < self.cache_ttl:
103
+ return hit[1]
104
+ ch = await self.ctx.db.get_channel(cid)
105
+ if ch is not None and not ch.active:
106
+ ch = None
107
+ self._cache[cid] = (now, ch)
108
+ return ch
109
+
110
+ def forget_cache(self) -> None:
111
+ self._cache.clear()
112
+
113
+ def exclusive(self):
114
+ """Held (`async with`) while no look at any channel runs - for a change that must not race with one."""
115
+ return self._busy
116
+
117
+ def options(self, **kw) -> SyncOptions:
118
+ ctx = self.ctx
119
+ base = dict(
120
+ delete_services=ctx.cfg.delete_service_messages,
121
+ history=ctx.cfg.import_old_posts,
122
+ ignore=ctx.sync_ignore,
123
+ pause=self.pause,
124
+ )
125
+ base.update(kw)
126
+ return SyncOptions(**base)
127
+
128
+ async def tell_owners(self, ch, key: str, text: str, every: Optional[float] = None) -> None:
129
+ """A warning for the owners - the same one (per channel and kind) at most once a day (or every `every` seconds)."""
130
+ now = time.monotonic()
131
+ k = (ch.id, key)
132
+ if now - self._told.get(k, -1e12) < (self.tell_every if every is None else every):
133
+ return
134
+ self._told[k] = now
135
+ for uid in sorted(self.ctx.cfg.owners):
136
+ try:
137
+ await self.ctx.client.send_message(uid, text, link_preview=False)
138
+ except Exception:
139
+ log.warning("could not warn user %s about %s", uid, ch.id, exc_info=True)
140
+
141
+ async def _after(self, ch, rep: SyncReport) -> None:
142
+ self.last_reports[ch.id] = rep
143
+ if rep.changed or rep.error or rep.anomaly:
144
+ log.info(
145
+ "channel %s: %s removed, %s updated, %s new, %s service messages deleted%s",
146
+ ch.id, len(rep.deleted), len(rep.edited), len(rep.adopted), rep.services_deleted,
147
+ f" - {rep.error or rep.anomaly}" if (rep.error or rep.anomaly) else "",
148
+ )
149
+ if rep.services_failed and rep.services_error in RIGHTS_ERRORS:
150
+ await self.tell_owners(ch, "rights", self._rights_text(ch, rep.services_error))
151
+ if rep.restricted_channel:
152
+ log.info("channel %s is restricted by Telegram (%s): My posts left untouched", ch.id, rep.restricted_channel)
153
+ text = self._restricted_text(ch, rep.restricted_channel)
154
+ await self.tell_owners(ch, "restricted", text, every=self.tell_restricted_every)
155
+ elif rep.restricted:
156
+ log.info("channel %s: %s post(s) held back by Telegram (%s): left untouched", ch.id, len(rep.restricted), rep.restricted_why)
157
+ text = self._held_back_text(ch, len(rep.restricted), rep.restricted_why)
158
+ await self.tell_owners(ch, "held-back", text, every=self.tell_restricted_every)
159
+
160
+ @staticmethod
161
+ def _restricted_text(ch, why: str) -> str:
162
+ return (
163
+ f"🚫 Telegram has restricted <b>{esc(ch.title)}</b> ({esc(why)}). While that lasts I don't change anything in "
164
+ "My posts for this channel - the saved posts stay exactly as they are, whatever the channel shows now."
165
+ )
166
+
167
+ @staticmethod
168
+ def _held_back_text(ch, n: int, why: Optional[str]) -> str:
169
+ return (
170
+ f"🚫 Telegram holds back {n} post(s) of <b>{esc(ch.title)}</b> ({esc(why or 'restricted')}). "
171
+ "Their saved copies in My posts stay exactly as they are."
172
+ )
173
+
174
+ @staticmethod
175
+ def _rights_text(ch, why: Optional[str]) -> str:
176
+ return (
177
+ f"⚠️ I can't delete the service messages (name changes, β€œpinned a message” ...) in <b>{esc(ch.title)}</b> "
178
+ f"({esc(why or 'refused')}). Give the bot the <i>Delete messages</i> right there, or set "
179
+ "DELETE_SERVICE_MESSAGES=false to stop trying."
180
+ )
181
+
182
+ # ------------------------------------------------------------------------------------ full looks
183
+ async def run_all(
184
+ self, chans: Optional[list] = None, *, explicit: bool = False, history: Optional[bool] = None, progress=None
185
+ ) -> list:
186
+ """Look at the connected channels one after the other. `explicit` (the /sync command): the caller holds the
187
+ one-long-job lock and everything is read; the timed check gives way to any long job instead. `history`: True
188
+ reads the channels' older posts even if IMPORT_OLD_POSTS is off (/sync --history)."""
189
+ ctx = self.ctx
190
+ if chans is None:
191
+ chans = await ctx.db.list_channels()
192
+ busy = (lambda: False) if explicit else ctx.lock.locked
193
+ reports: list = []
194
+ for ch in chans:
195
+ if busy():
196
+ break
197
+
198
+ async def prog(rep, ch=ch):
199
+ if progress is not None:
200
+ await progress(ch, rep)
201
+
202
+ try:
203
+ async with self._busy:
204
+ extra = {} if history is None else {"history": history}
205
+ opts = self.options(deep=explicit, history_seconds=None if explicit else self.history_seconds, **extra)
206
+ rep = await sync_channel(ctx.client, ctx.db, ch, opts, busy=busy, progress=prog)
207
+ except asyncio.CancelledError:
208
+ raise
209
+ except Exception as e:
210
+ log.exception("looking at channel %s failed", ch.id)
211
+ rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")
212
+ await self._after(ch, rep)
213
+ reports.append(rep)
214
+ return reports
215
+
216
+ # ----------------------------------------------------------------------------- live: what updates say
217
+ def _touch(self) -> None:
218
+ self._stamp += 1
219
+ self._wake.set()
220
+
221
+ def note_new(self, cid: int, msg) -> None:
222
+ """A post appeared in a channel. The bot's own posts are skipped (it saves them itself)."""
223
+ if not self.enabled or self.ctx.lock.locked() or getattr(msg, "out", False):
224
+ return
225
+ self._news.setdefault(cid, set()).add(msg.id)
226
+ self._touch()
227
+
228
+ def note_edit(self, cid: int, msg) -> None:
229
+ if not self.enabled or self.ctx.lock.locked():
230
+ return
231
+ self._edits.setdefault(cid, set()).add(msg.id)
232
+ self._touch()
233
+
234
+ async def note_deleted(self, cid: int, ids) -> None:
235
+ """Posts were deleted in a channel: they leave My posts at once (nothing to read from Telegram for that)."""
236
+ if not self.enabled:
237
+ return
238
+ ch = await self.channel(cid)
239
+ if ch is None:
240
+ return
241
+ for pending in (self._edits, self._news):
242
+ if cid in pending:
243
+ pending[cid].difference_update(ids)
244
+ n = await self.ctx.db.forget_posts(cid, list(ids))
245
+ if n:
246
+ log.info("%s post(s) were deleted in channel %s: removed from My posts", n, cid)
247
+
248
+ async def on_service(self, cid: int, msg) -> None:
249
+ """A service message appeared: delete it."""
250
+ if not self.ctx.cfg.delete_service_messages:
251
+ return
252
+ ch = await self.channel(cid)
253
+ if ch is None:
254
+ return
255
+ out = await remove(self.ctx.client, peer_of(ch), [msg.id])
256
+ if out.error is None:
257
+ log.info("removed the β€œ%s” notice %s from channel %s", action_label(msg), msg.id, cid)
258
+ return
259
+ log.warning("could not delete the β€œ%s” notice %s in channel %s: %s", action_label(msg), msg.id, cid, out.error_name)
260
+ if out.error_name in RIGHTS_ERRORS:
261
+ await self.tell_owners(ch, "rights", self._rights_text(ch, out.error_name))
262
+
263
+ def _pending(self) -> bool:
264
+ return bool(self._edits or self._news)
265
+
266
+ async def flush_events(self) -> None:
267
+ """Work off the queue once it has been quiet for a moment (and no long job is running)."""
268
+ first = time.monotonic()
269
+ while self._pending():
270
+ stamp = self._stamp
271
+ await asyncio.sleep(self.debounce)
272
+ if stamp != self._stamp and time.monotonic() - first < self.max_debounce:
273
+ continue # more is still coming in: let it settle
274
+ if self.ctx.lock.locked():
275
+ await asyncio.sleep(self.lock_wait)
276
+ continue
277
+ edits, news = self._edits, self._news
278
+ self._edits, self._news = {}, {}
279
+ await self._process(edits, news)
280
+ first = time.monotonic()
281
+
282
+ def _requeue(self, pending: dict, cid: int, mid: int) -> None:
283
+ key = (cid, mid)
284
+ self._tries[key] = self._tries.get(key, 0) + 1
285
+ if self._tries[key] > self.max_tries:
286
+ self._tries.pop(key, None)
287
+ return
288
+ pending.setdefault(cid, set()).add(mid)
289
+
290
+ async def _process(self, edits: dict, news: dict) -> None:
291
+ ctx = self.ctx
292
+ for cid in sorted(set(edits) | set(news)):
293
+ ch = await self.channel(cid)
294
+ if ch is None:
295
+ continue
296
+ e_ids, n_ids = set(edits.get(cid, ())), set(news.get(cid, ()))
297
+ opts = self.options(grace=self.rt_grace, history=False) # live: the older posts wait for the timed check
298
+ try:
299
+ async with self._busy:
300
+ if len(e_ids | n_ids) > self.max_ids: # a burst: one look at the whole channel is cheaper
301
+ rep = await sync_channel(ctx.client, ctx.db, ch, opts, busy=ctx.lock.locked)
302
+ else:
303
+ rep = await sync_ids(
304
+ ctx.client, ctx.db, ch, e_ids | n_ids, opts, adopt_ids=n_ids, busy=ctx.lock.locked
305
+ )
306
+ except asyncio.CancelledError:
307
+ raise
308
+ except Exception as e:
309
+ log.exception("looking at the changes in channel %s failed", cid)
310
+ rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}")
311
+ await self._after(ch, rep)
312
+ if rep.busy: # a long job started in the meantime: let the next timed check have it
313
+ continue
314
+ for mid in set(rep.young):
315
+ self._requeue(self._edits, cid, mid)
316
+ for mid in set(rep.young_new):
317
+ self._requeue(self._news, cid, mid)
318
+ for mid in (e_ids | n_ids) - set(rep.young) - set(rep.young_new):
319
+ self._tries.pop((cid, mid), None)
app/tgutil.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers around Telethon types: entity/button (de)serialisation, media info, raw edits, rights."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import base64
6
+ import copy
7
+ import html
8
+ import logging
9
+ import os
10
+ from dataclasses import dataclass, field
11
+ from types import SimpleNamespace
12
+ from typing import Any, Awaitable, Callable, Optional
13
+
14
+ from telethon import errors, functions, types
15
+ from telethon.extensions import BinaryReader
16
+
17
+ log = logging.getLogger(__name__)
18
+ esc = html.escape
19
+
20
+ # Telegram refusals that do not go away with the next message: the bot has no access (or no right) in that channel
21
+ FATAL = {
22
+ "ChatAdminRequiredError",
23
+ "ChatWriteForbiddenError",
24
+ "ChannelPrivateError",
25
+ "UserBannedInChannelError",
26
+ "ChannelInvalidError",
27
+ "ChatRestrictedError",
28
+ }
29
+
30
+ # ----------------------------------------------------------------------------- entities
31
+ _SIMPLE = {
32
+ "bold": types.MessageEntityBold,
33
+ "italic": types.MessageEntityItalic,
34
+ "underline": types.MessageEntityUnderline,
35
+ "strike": types.MessageEntityStrike,
36
+ "code": types.MessageEntityCode,
37
+ }
38
+ if hasattr(types, "MessageEntitySpoiler"):
39
+ _SIMPLE["spoiler"] = types.MessageEntitySpoiler
40
+
41
+ # entities Telegram works out by itself from the text - never stored
42
+ _AUTO = tuple(
43
+ getattr(types, n)
44
+ for n in (
45
+ "MessageEntityUrl",
46
+ "MessageEntityMention",
47
+ "MessageEntityHashtag",
48
+ "MessageEntityCashtag",
49
+ "MessageEntityBotCommand",
50
+ "MessageEntityEmail",
51
+ "MessageEntityPhone",
52
+ "MessageEntityBankCard",
53
+ )
54
+ if hasattr(types, n)
55
+ )
56
+
57
+
58
+ def _b64(obj: Any) -> str:
59
+ return base64.b64encode(bytes(obj)).decode()
60
+
61
+
62
+ def _unb64(data: str) -> Any:
63
+ return BinaryReader(base64.b64decode(data)).tgread_object()
64
+
65
+
66
+ def ser_entities(entities) -> list:
67
+ """Message entities -> JSON-friendly list (UTF-16 offsets, as Telegram uses)."""
68
+ out: list = []
69
+ for e in entities or []:
70
+ if isinstance(e, _AUTO):
71
+ continue
72
+ done = False
73
+ for key, cls in _SIMPLE.items():
74
+ if isinstance(e, cls):
75
+ out.append({"k": key, "o": e.offset, "l": e.length})
76
+ done = True
77
+ break
78
+ if done:
79
+ continue
80
+ if isinstance(e, types.MessageEntityPre):
81
+ out.append({"k": "pre", "o": e.offset, "l": e.length, "g": e.language or ""})
82
+ elif isinstance(e, types.MessageEntityTextUrl):
83
+ out.append({"k": "url", "o": e.offset, "l": e.length, "u": e.url})
84
+ elif isinstance(e, types.MessageEntityBlockquote):
85
+ out.append({"k": "quote", "o": e.offset, "l": e.length, "c": bool(getattr(e, "collapsed", False))})
86
+ elif isinstance(e, types.MessageEntityCustomEmoji):
87
+ out.append({"k": "emoji", "o": e.offset, "l": e.length, "d": e.document_id})
88
+ else:
89
+ try: # anything else is kept byte-for-byte
90
+ out.append({"k": "raw", "b": _b64(e)})
91
+ except Exception: # pragma: no cover
92
+ log.warning("cannot store entity %r", e)
93
+ return out
94
+
95
+
96
+ def de_entities(data) -> list:
97
+ out: list = []
98
+ for d in data or []:
99
+ k = d.get("k")
100
+ try:
101
+ if k in _SIMPLE:
102
+ out.append(_SIMPLE[k](d["o"], d["l"]))
103
+ elif k == "pre":
104
+ out.append(types.MessageEntityPre(d["o"], d["l"], d.get("g", "")))
105
+ elif k == "url":
106
+ out.append(types.MessageEntityTextUrl(d["o"], d["l"], d["u"]))
107
+ elif k == "quote":
108
+ out.append(types.MessageEntityBlockquote(d["o"], d["l"], True if d.get("c") else None))
109
+ elif k == "emoji":
110
+ out.append(types.MessageEntityCustomEmoji(d["o"], d["l"], d["d"]))
111
+ elif k == "raw":
112
+ out.append(_unb64(d["b"]))
113
+ except Exception: # pragma: no cover
114
+ log.warning("bad stored entity %r", d)
115
+ return out
116
+
117
+
118
+ # ------------------------------------------------------------------------------ buttons
119
+ _LEGACY = hasattr(types, "KeyboardButtonUrl") # Telethon < 1.45 used one class per button kind
120
+
121
+
122
+ def button_url(b) -> Optional[str]:
123
+ """The link of a URL button, else None."""
124
+ if _LEGACY:
125
+ return b.url if isinstance(b, types.KeyboardButtonUrl) else None
126
+ t = getattr(b, "type", None)
127
+ return t.url if isinstance(t, types.InlineButtonTypeUrl) else None
128
+
129
+
130
+ def is_callback_button(b) -> bool:
131
+ if _LEGACY:
132
+ return isinstance(b, types.KeyboardButtonCallback)
133
+ return isinstance(getattr(b, "type", None), types.InlineButtonTypeCallback)
134
+
135
+
136
+ def make_url_button(text: str, url: str, style=None):
137
+ if _LEGACY:
138
+ return types.KeyboardButtonUrl(text, url)
139
+ return types.KeyboardButton(text=text, type=types.InlineButtonTypeUrl(url), style=style)
140
+
141
+
142
+ def with_url(b, new_url: str):
143
+ """Copy of URL button `b` pointing to `new_url`; every other attribute (colour, ...) is kept."""
144
+ nb = copy.copy(b)
145
+ if _LEGACY:
146
+ nb.url = new_url
147
+ else:
148
+ nb.type = copy.copy(b.type)
149
+ nb.type.url = new_url
150
+ return nb
151
+
152
+
153
+ def with_text(b, new_text: str):
154
+ """Copy of button `b` with another name; the link, colour ... are kept."""
155
+ nb = copy.copy(b)
156
+ nb.text = new_text
157
+ return nb
158
+
159
+
160
+ def _style_dump(b) -> Optional[str]:
161
+ st = getattr(b, "style", None)
162
+ if st is None:
163
+ return None
164
+ if not any(getattr(st, f, None) for f in ("bg_primary", "bg_danger", "bg_success", "icon")):
165
+ return None
166
+ try:
167
+ return _b64(st)
168
+ except Exception: # pragma: no cover
169
+ return None
170
+
171
+
172
+ def ser_markup(markup) -> list:
173
+ """Inline keyboard -> rows of {'t': text, 'u': url} (URL buttons) or {'t', 'raw'} (any other kind)."""
174
+ rows: list = []
175
+ if isinstance(markup, types.ReplyInlineMarkup):
176
+ for row in markup.rows:
177
+ r = []
178
+ for b in row.buttons:
179
+ url = button_url(b)
180
+ if url is not None:
181
+ item = {"t": b.text, "u": url}
182
+ s = _style_dump(b)
183
+ if s:
184
+ item["s"] = s
185
+ r.append(item)
186
+ else:
187
+ try:
188
+ r.append({"t": getattr(b, "text", ""), "raw": _b64(b)})
189
+ except Exception: # pragma: no cover
190
+ log.warning("cannot store button %r", b)
191
+ if r:
192
+ rows.append(r)
193
+ return rows
194
+
195
+
196
+ def build_markup(rows) -> Optional[types.ReplyInlineMarkup]:
197
+ out = []
198
+ for row in rows or []:
199
+ btns = []
200
+ for b in row:
201
+ if b.get("raw"):
202
+ try:
203
+ btns.append(_unb64(b["raw"]))
204
+ except Exception: # pragma: no cover
205
+ continue
206
+ elif b.get("u"):
207
+ style = None
208
+ if b.get("s"):
209
+ try:
210
+ style = _unb64(b["s"])
211
+ except Exception: # pragma: no cover
212
+ style = None
213
+ btns.append(make_url_button(b["t"], b["u"], style))
214
+ if btns:
215
+ out.append(types.KeyboardButtonRow(btns))
216
+ return types.ReplyInlineMarkup(out) if out else None
217
+
218
+
219
+ def state_of(text, entities, markup, preview) -> dict:
220
+ """Snapshot used for the undo log."""
221
+ return {
222
+ "text": text or "",
223
+ "entities": ser_entities(entities),
224
+ "buttons": ser_markup(markup),
225
+ "preview": preview, # True/False for text messages, None for media messages
226
+ }
227
+
228
+
229
+ # --------------------------------------------------------------------------------- media
230
+ def classify_media(m) -> Optional[str]:
231
+ """photo | video | animation | audio | document, or None (text / unsupported)."""
232
+ media = getattr(m, "media", None)
233
+ if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None):
234
+ return "photo"
235
+ if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None):
236
+ if m.gif:
237
+ return "animation"
238
+ if m.video:
239
+ return "video"
240
+ if m.audio:
241
+ return "audio"
242
+ if m.voice or m.video_note or m.sticker:
243
+ return None
244
+ return "document"
245
+ return None
246
+
247
+
248
+ # Media is stored as the serialised Telegram media object ("tl:<base64>"). Telethon's Bot-API style
249
+ # file_id helper cannot pack photos with the current Telegram schema, so we don't rely on it.
250
+ _REF_PREFIX = "tl:"
251
+
252
+
253
+ def media_ref(m) -> Optional[str]:
254
+ """A storable reference to the photo / document attached to message `m` (None if it has none)."""
255
+ media = getattr(m, "media", None)
256
+ if isinstance(media, (types.MessageMediaPhoto, types.MessageMediaDocument)):
257
+ try:
258
+ return _REF_PREFIX + _b64(media)
259
+ except Exception: # pragma: no cover
260
+ log.warning("cannot store media reference", exc_info=True)
261
+ return None
262
+
263
+
264
+ pack_file_id = media_ref # older name, kept for the callers
265
+
266
+
267
+ def media_from_ref(ref: str, *, blank_reference: bool = False):
268
+ """Rebuild the media object; `blank_reference` drops the (possibly expired) file reference."""
269
+ media = _unb64(ref[len(_REF_PREFIX):]) if ref.startswith(_REF_PREFIX) else None
270
+ if media is None:
271
+ raise ValueError("unknown media reference")
272
+ if blank_reference:
273
+ media = copy.copy(media)
274
+ inner = copy.copy(media.photo if isinstance(media, types.MessageMediaPhoto) else media.document)
275
+ inner.file_reference = b""
276
+ if isinstance(media, types.MessageMediaPhoto):
277
+ media.photo = inner
278
+ else:
279
+ media.document = inner
280
+ return media
281
+
282
+
283
+ async def with_media(ref: str, call):
284
+ """call(media): first with the stored file reference, then (if Telegram says it expired) without it."""
285
+ try:
286
+ return await call(media_from_ref(ref))
287
+ except errors.RPCError as e:
288
+ if "FileReference" not in type(e).__name__ and type(e).__name__ != "MediaEmptyError":
289
+ raise
290
+ log.info("stored file reference rejected (%s) - retrying without it", type(e).__name__)
291
+ return await call(media_from_ref(ref, blank_reference=True))
292
+
293
+
294
+ def media_info(m) -> tuple:
295
+ kind = classify_media(m)
296
+ return kind, (media_ref(m) if kind else None)
297
+
298
+
299
+ def media_key(media) -> Optional[tuple]:
300
+ """("photo" | "doc", id) of the photo / file in a message's media; the id is the same on every account."""
301
+ if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None):
302
+ return "photo", media.photo.id
303
+ if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None):
304
+ return "doc", media.document.id
305
+ return None
306
+
307
+
308
+ @dataclass
309
+ class MediaFile:
310
+ """A photo or file downloaded from Telegram, with what is needed to upload it again as the same kind of post."""
311
+
312
+ path: str
313
+ kind: str # photo | video | animation | audio | document
314
+ name: str
315
+ mime_type: Optional[str] = None
316
+ attributes: list = field(default_factory=list) # the file's name, video size and length, GIF mark ... as it had them
317
+ thumb_path: Optional[str] = None # the picture Telegram shows for the file (JPEG); None: it has none
318
+
319
+
320
+ async def fetch_media(client, ref: str, kind: str, folder: str) -> MediaFile:
321
+ """Download the photo / file behind the stored media reference `ref` (as `client` sees it) into `folder`.
322
+
323
+ A file's thumbnail comes along: without it the file would be uploaded again with a plain file icon."""
324
+ path = await with_media(ref, lambda media: client.download_media(media, file=folder + os.sep))
325
+ if not path:
326
+ raise ValueError("Telegram gave me nothing to download for that media")
327
+ doc = getattr(media_from_ref(ref), "document", None)
328
+ return MediaFile(
329
+ path=str(path),
330
+ kind=kind,
331
+ name=os.path.basename(str(path)),
332
+ mime_type=getattr(doc, "mime_type", None),
333
+ attributes=list(getattr(doc, "attributes", None) or []),
334
+ thumb_path=await fetch_thumb(client, ref, folder) if doc is not None else None,
335
+ )
336
+
337
+
338
+ async def fetch_thumb(client, ref: str, folder: str) -> Optional[str]:
339
+ """The thumbnail of the file behind `ref` (the largest one Telegram has) as a JPEG in `folder`, or None.
340
+
341
+ Best effort: a file that goes out without its thumbnail is better than an edit that fails."""
342
+ where = os.path.join(folder, "thumb")
343
+ try:
344
+ os.makedirs(where, exist_ok=True)
345
+ path = await with_media(ref, lambda media: client.download_media(media, file=where + os.sep, thumb=-1))
346
+ except (errors.RPCError, OSError, ValueError, TypeError) as e:
347
+ log.info("could not download the thumbnail: %s", type(e).__name__)
348
+ return None
349
+ return str(path) if path and os.path.isfile(str(path)) else None
350
+
351
+
352
+ def utf16_len(s: str) -> int:
353
+ return len(s.encode("utf-16-le")) // 2
354
+
355
+
356
+ # --------------------------------------------------------------------------------- misc
357
+ def peer_of(ch) -> types.InputPeerChannel:
358
+ return types.InputPeerChannel(ch.id, ch.access_hash)
359
+
360
+
361
+ def post_link(ch, message_id: int) -> str:
362
+ if ch.username:
363
+ return f"https://t.me/{ch.username}/{message_id}"
364
+ return f"https://t.me/c/{ch.id}/{message_id}"
365
+
366
+
367
+ def short(s: str, n: int) -> str:
368
+ s = " ".join((s or "").split())
369
+ return s if len(s) <= n else s[: n - 1] + "…"
370
+
371
+
372
+ async def flood_retry(factory: Callable[[], Awaitable[Any]], tries: int = 4) -> Any:
373
+ for _ in range(tries):
374
+ try:
375
+ return await factory()
376
+ except errors.FloodWaitError as e:
377
+ wait = int(getattr(e, "seconds", 5)) + 1
378
+ log.warning("flood wait %ss", wait)
379
+ await asyncio.sleep(min(wait, 900))
380
+ return await factory()
381
+
382
+
383
+ async def edit_raw(
384
+ client,
385
+ peer,
386
+ message_id: int,
387
+ *,
388
+ text: Optional[str] = None,
389
+ entities=None,
390
+ markup=None,
391
+ preview=None,
392
+ media=None,
393
+ rich_message=None,
394
+ ):
395
+ """messages.editMessage with every field explicit.
396
+
397
+ `markup=None` together with `text` (or `rich_message`) removes the keyboard (that is how Telegram behaves);
398
+ a markup-only edit (text=None) leaves the text alone. `media` (an InputMedia) replaces the photo / file.
399
+ `rich_message` (an InputRichMessage*) makes the message that rich message instead of text.
400
+ """
401
+ kw: dict = {"peer": peer, "id": message_id}
402
+ if markup is not None:
403
+ kw["reply_markup"] = markup
404
+ if media is not None:
405
+ kw["media"] = media
406
+ if rich_message is not None:
407
+ kw["rich_message"] = rich_message
408
+ elif text is not None:
409
+ kw["message"] = text
410
+ kw["entities"] = list(entities or [])
411
+ if preview is not None:
412
+ kw["no_webpage"] = not preview
413
+ return await client(functions.messages.EditMessageRequest(**kw))
414
+
415
+
416
+ async def get_rights(client, ch):
417
+ """The bot's own admin rights in a channel, or None if Telegram won't tell us."""
418
+ try:
419
+ res = await client(
420
+ functions.channels.GetParticipantRequest(channel=peer_of(ch), participant=types.InputPeerSelf())
421
+ )
422
+ except Exception as e:
423
+ log.info("could not read own rights in %s: %s", ch.id, e)
424
+ return None
425
+ p = res.participant
426
+ if isinstance(p, (types.ChannelParticipantCreator, types.ChannelParticipantAdmin)):
427
+ r = getattr(p, "admin_rights", None)
428
+ creator = isinstance(p, types.ChannelParticipantCreator)
429
+
430
+ def has(name: str) -> bool:
431
+ return True if (creator and r is None) else bool(getattr(r, name, False))
432
+
433
+ return SimpleNamespace(
434
+ admin=True,
435
+ post=has("post_messages"),
436
+ edit=has("edit_messages"),
437
+ delete=has("delete_messages"),
438
+ invite=has("invite_users"),
439
+ add_admins=has("add_admins"),
440
+ change_info=has("change_info"),
441
+ )
442
+ return SimpleNamespace(
443
+ admin=False, post=False, edit=False, delete=False, invite=False, add_admins=False, change_info=False
444
+ )
445
+
446
+
447
+ _HINTS = {
448
+ "ChatAdminRequiredError": "The bot needs admin rights in that channel (post / edit / delete messages).",
449
+ "MessageAuthorRequiredError": "Telegram wants the message author. Give the bot the 'Edit messages of others' right.",
450
+ "InlineBotRequiredError": "That post was sent through another bot's inline mode, so only that bot can edit it.",
451
+ "MessageEditTimeExpiredError": "Telegram no longer allows editing that message.",
452
+ "MessageIdInvalidError": (
453
+ "Telegram won't let the bot change that message (or it was deleted). If the post is still there, "
454
+ "the usual reason is that its buttons were added by another bot: only that bot may change them."
455
+ ),
456
+ "ButtonUrlInvalidError": "Telegram rejected one of the button links.",
457
+ "ReplyMarkupInvalidError": "Telegram rejected the buttons.",
458
+ "ChatWriteForbiddenError": "The bot can't post in that channel - check its admin rights.",
459
+ "ChannelPrivateError": "The bot can't access that channel any more (removed or banned?).",
460
+ "UserBannedInChannelError": "The bot is banned in that channel.",
461
+ "FileReferenceExpiredError": "The saved media expired - send the media again.",
462
+ "MediaEmptyError": "Telegram could not use that media - send it again.",
463
+ "EntityBoundsInvalidError": "The text formatting doesn't fit the text.",
464
+ "EntitiesTooLongError": "The text has too many formatted pieces (bold, links ...) for Telegram - use less formatting.",
465
+ "MessageTooLongError": "The text is too long for Telegram.",
466
+ "MediaCaptionTooLongError": "The caption is too long for Telegram.",
467
+ }
468
+
469
+
470
+ # Telegram's own error codes (the name of the Python class is only "BadRequestError" for the ones Telethon doesn't know)
471
+ _CODE_HINTS = {
472
+ "RICH_MESSAGE_BLOCK_INVALID": "Telegram would not take one of the blocks of that rich message.",
473
+ }
474
+
475
+
476
+ def explain_rpc(e: BaseException) -> str:
477
+ name = type(e).__name__
478
+ code = getattr(e, "message", None) or ""
479
+ hint = _HINTS.get(name)
480
+ if hint is None and code in _CODE_HINTS:
481
+ hint = f"{_CODE_HINTS[code]} ({code})"
482
+ return f"Telegram refused ({name}). " + (hint if hint is not None else str(e)[:200])
app/ui.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Texts and inline keyboards for the post panel."""
2
+ from __future__ import annotations
3
+
4
+ from telethon import Button
5
+
6
+ from .buttons import count, grid_label, link_positions, missing_links
7
+ from .richmsg import rich_of
8
+ from .tgutil import esc, post_link, short
9
+
10
+ CANCEL = [[Button.inline("βœ–οΈ Cancel", "cx")]]
11
+ KIND_ICON = {None: "πŸ“", "photo": "πŸ–Ό", "video": "🎬", "animation": "🎞", "audio": "🎡", "document": "πŸ“Ž"}
12
+ KIND_NAME = {None: "text", "photo": "photo", "video": "video", "animation": "GIF", "audio": "audio", "document": "file"}
13
+
14
+
15
+ def post_title(p) -> str:
16
+ for row in p.buttons or []:
17
+ for b in row:
18
+ if b.get("t"):
19
+ return b["t"]
20
+ text = (p.text or "").strip()
21
+ return text.splitlines()[0] if text else (KIND_NAME.get(p.media_kind) or "post")
22
+
23
+
24
+ def post_label(p) -> str:
25
+ icon = "πŸ“" if p.status == "draft" else "βœ…"
26
+ return f"{icon} #{p.id} {short(post_title(p), 34)}"
27
+
28
+
29
+ def panel_text(p, ch, note=None) -> str:
30
+ state = "draft (not published yet)" if p.status == "draft" else "published"
31
+ lines = [f"<b>Post #{p.id}</b> Β· {state}", f"Channel: <b>{esc(ch.title)}</b>"]
32
+ if p.status == "sent" and p.message_id:
33
+ lines.append(f'<a href="{post_link(ch, p.message_id)}">Open in the channel</a>')
34
+ rich = rich_of(p)
35
+ if rich is not None:
36
+ origin = {"html": "typed as HTML", "markdown": "typed as Markdown"}.get(rich.fmt, "made in Telegram")
37
+ lines.append(f"Type: 🧩 rich message ({origin})")
38
+ else:
39
+ lines.append(f"Type: {KIND_ICON.get(p.media_kind, 'πŸ“Ž')} {KIND_NAME.get(p.media_kind, p.media_kind)}")
40
+ n, miss = count(p.buttons), missing_links(p.buttons)
41
+ lines.append(f"Buttons: {n}" + (f" (⚠️ {miss} without a link)" if miss else ""))
42
+ if p.source == "adopted":
43
+ lines.append("<i>Picked up from the channel - it was not made with this bot.</i>")
44
+ snippet = short(p.text or "", 220) or "(no text)"
45
+ lines += ["", f"<i>{esc(snippet)}</i>"]
46
+ if note:
47
+ lines += ["", note]
48
+ return "\n".join(lines)
49
+
50
+
51
+ def panel_keyboard(p) -> list:
52
+ pid = p.id
53
+ kb = []
54
+ for r, row in enumerate(p.buttons or []):
55
+ kb.append([Button.inline(grid_label(b), f"bs:{pid}:{r}:{c}") for c, b in enumerate(row)])
56
+ rich = rich_of(p) is not None
57
+ kb.append(
58
+ [Button.inline("✏️ Caption" if p.media_kind else "✏️ Text", f"et:{pid}")]
59
+ + ([] if rich else [Button.inline("πŸ–Ό Media", f"em:{pid}")]) # a rich message has no media slot
60
+ )
61
+ row3 = [Button.inline("βž• Button", f"ba:{pid}"), Button.inline("πŸ“‹ Set buttons", f"bp:{pid}")]
62
+ if p.buttons:
63
+ row3.append(Button.inline("🧹 Clear", f"bc:{pid}"))
64
+ kb.append(row3)
65
+ extra = []
66
+ if not p.media_kind and not rich:
67
+ extra.append(Button.inline(f"πŸ”— Link preview: {'on' if p.link_preview else 'off'}", f"lp:{pid}"))
68
+ if p.media_kind and p.status == "draft":
69
+ extra.append(Button.inline("🚫 Remove media", f"rm:{pid}"))
70
+ if extra:
71
+ kb.append(extra)
72
+ if p.status == "sent" and p.message_id and link_positions(p.buttons):
73
+ kb.append([Button.inline("πŸ”— Mass replace links", f"mlp:{pid}")])
74
+ if p.status == "draft":
75
+ kb.append([Button.inline("πŸ‘ Preview", f"pv:{pid}"), Button.inline("πŸš€ Publish", f"pb:{pid}")])
76
+ kb.append([Button.inline("πŸ—‘ Discard", f"dl:{pid}"), Button.inline("πŸ“š My posts", "pc:d:0")])
77
+ else:
78
+ kb.append([Button.inline("πŸ‘ Preview", f"pv:{pid}"), Button.inline("πŸ—‘ Delete", f"dl:{pid}")])
79
+ kb.append([Button.inline("πŸ“š My posts", f"pc:{p.channel_id}:0")])
80
+ return kb
81
+
82
+
83
+ def button_text(p, r: int, c: int) -> str:
84
+ b = p.buttons[r][c]
85
+ if b.get("raw"):
86
+ return (
87
+ f"πŸ”’ <b>Button from another bot</b> (row {r + 1}, position {c + 1})\n"
88
+ f"Text: <code>{esc(b.get('t') or '')}</code>\n"
89
+ "Buttons like reactions only work with the bot that made them, so you can move or delete it, "
90
+ "but not edit it."
91
+ )
92
+ return (
93
+ f"πŸ”˜ <b>Button</b> (row {r + 1}, position {c + 1})\n"
94
+ f"Text: <code>{esc(b.get('t') or '')}</code>\n"
95
+ f"Link: <code>{esc(b.get('u') or '- none yet -')}</code>"
96
+ )
97
+
98
+
99
+ def button_keyboard(p, r: int, c: int) -> list:
100
+ pid, at = p.id, f"{p.id}:{r}:{c}"
101
+ b = p.buttons[r][c]
102
+ kb = []
103
+ if not b.get("raw"):
104
+ kb.append([Button.inline("✏️ Change text", f"bt:{at}"), Button.inline("πŸ”— Change link", f"bu:{at}")])
105
+ kb.append(
106
+ [
107
+ Button.inline("⬅️", f"bm:{at}:l"),
108
+ Button.inline("⬆️", f"bm:{at}:u"),
109
+ Button.inline("⬇️", f"bm:{at}:d"),
110
+ Button.inline("➑️", f"bm:{at}:r"),
111
+ ]
112
+ )
113
+ kb.append([Button.inline("πŸ—‘ Delete", f"bd:{at}"), Button.inline("πŸ”™ Back", f"po:{pid}")])
114
+ return kb