Spaces:
Running
Running
github-actions[bot] commited on
Commit Β·
ee0695d
1
Parent(s): ac3902b
Automated sync from GitHub
Browse filesThis view is limited to 50 files because it contains too many changes. Β See raw diff
Files changed (50)
- .env.exampleAdded+25
- .gitattributes+8-34
- .gitignoreAdded+7
- Dockerfile+6-15
- app.pyDeleted-147
- app/__init__.pyAdded
- app/autopost.pyAdded+81
- app/backup.pyAdded+337
- app/buttons.pyAdded+150
- app/buttons_sync.pyAdded+186
- app/channelref.pyAdded+119
- app/common.pyAdded+406
- app/config.pyAdded+133
- app/crosslinks.pyAdded+406
- app/db.pyAdded+1067
- app/errorlog.pyAdded+300
- app/expiry.pyAdded+208
- app/handlers/__init__.pyAdded
- app/handlers/autopost.pyAdded+203
- app/handlers/backup.pyAdded+173
- app/handlers/basic.pyAdded+201
- app/handlers/broadcast.pyAdded+268
- app/handlers/channels.pyAdded+182
- app/handlers/checkbtn.pyAdded+115
- app/handlers/create.pyAdded+191
- app/handlers/masslinks.pyAdded+159
- app/handlers/panel.pyAdded+135
- app/handlers/posts.pyAdded+534
- app/handlers/replace.pyAdded+502
- app/handlers/repost.pyAdded+820
- app/handlers/shift.pyAdded+618
- app/handlers/sync.pyAdded+223
- app/handleswap.pyAdded+97
- app/health.pyAdded+26
- app/linkswap.pyAdded+236
- app/picker.pyAdded+104
- app/postlinks.pyAdded+226
- app/profile_copy.pyAdded+170
- app/replace_engine.pyAdded+343
- app/repost_engine.pyAdded+1372
- app/restrictions.pyAdded+77
- app/richmsg.pyAdded+698
- app/richtext.pyAdded+552
- app/servicemsg.pyAdded+55
- app/shift_engine.pyAdded+187
- app/suggest.pyAdded+127
- app/sync_engine.pyAdded+600
- app/syncer.pyAdded+319
- app/tgutil.pyAdded+482
- app/ui.pyAdded+114
12345678910111213141516171819202122232425# --- Telegram -------------------------------------------------------------API_ID=API_HASH=BOT_TOKEN=# Numeric Telegram ids (ask @userinfobot). Owners can manage admins in the bot.OWNER_IDS=
# --- Database -------------------------------------------------------------# PostgreSQL, e.g. a free Neon database. Leave empty to use a local SQLite file (data/bot.db).DATABASE_URL=postgresql://user:password@host/dbname?sslmode=require# "null" = short-lived connections (lets serverless Postgres sleep); "queue" = normal pool for an always-on DBDB_POOL=null
# --- Optional -------------------------------------------------------------# Where the login session is kept. On hosts that wipe files on restart, run `python make_session.py`# once and put the printed text in SESSION_STRING instead.SESSION_PATH=data/botSESSION_STRING=# Seconds between edits during /replace (Telegram rate limits: don't go much lower)EDIT_DELAY=1.2# Also swap links that are typed as plain text in a post (not only hyperlinks and buttons)REPLACE_TYPED_LINKS=true# Some free hosts need an open port: set it and the bot answers "ok" on /PORT=LOG_LEVEL=INFO12345678910111213141516171819202122232425262728293031323334*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12345678*.webp filter=lfs diff=lfs merge=lfs -text*.mp4 filter=lfs diff=lfs merge=lfs -text*.mp3 filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.ttf filter=lfs diff=lfs merge=lfs -text*.otf filter=lfs diff=lfs merge=lfs -text
1234567.envdata/*!data/.gitkeep*.session*.session-journal__pycache__/.pytest_cache/12345678910111213141516FROM python:3.11WORKDIR /codeCOPY ./requirements.txt /code/requirements.txtRUN python3 -m pip install --no-cache-dir --upgrade pipRUN python3 -m pip install --no-cache-dir --upgrade -r /code/requirements.txtCOPY . .CMD ["panel", "serve", "/code/app.py", "--address", "0.0.0.0", "--port", "7860", "--allow-websocket-origin", "*"]RUN mkdir /.cacheRUN chmod 777 /.cacheRUN mkdir .chromaRUN chmod 777 .chroma1234567FROM python:3.12-slimWORKDIR /appENV PYTHONUNBUFFERED=1COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .CMD python -m http.server 7860 & python bot.py
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import ioimport randomfrom typing import List, Tuple
import aiohttpimport panel as pnfrom PIL import Imagefrom transformers import CLIPModel, CLIPProcessor
pn.extension(design="bootstrap", sizing_mode="stretch_width")
ICON_URLS = { "brand-github": "https://github.com/holoviz/panel", "brand-twitter": "https://twitter.com/Panel_Org", "brand-linkedin": "https://www.linkedin.com/company/panel-org", "message-circle": "https://discourse.holoviz.org/", "brand-discord": "https://discord.gg/AXRHnJU6sP",}
async def random_url(_): pet = random.choice(["cat", "dog"]) api_url = f"https://api.the{pet}api.com/v1/images/search" async with aiohttp.ClientSession() as session: async with session.get(api_url) as resp: return (await resp.json())[0]["url"]
@pn.cachedef load_processor_model( processor_name: str, model_name: str) -> Tuple[CLIPProcessor, CLIPModel]: processor = CLIPProcessor.from_pretrained(processor_name) model = CLIPModel.from_pretrained(model_name) return processor, model
async def open_image_url(image_url: str) -> Image: async with aiohttp.ClientSession() as session: async with session.get(image_url) as resp: return Image.open(io.BytesIO(await resp.read()))
def get_similarity_scores(class_items: List[str], image: Image) -> List[float]: processor, model = load_processor_model( "openai/clip-vit-base-patch32", "openai/clip-vit-base-patch32" ) inputs = processor( text=class_items, images=[image], return_tensors="pt", # pytorch tensors ) outputs = model(**inputs) logits_per_image = outputs.logits_per_image class_likelihoods = logits_per_image.softmax(dim=1).detach().numpy() return class_likelihoods[0]
async def process_inputs(class_names: List[str], image_url: str): """ High level function that takes in the user inputs and returns the classification results as panel objects. """ try: main.disabled = True if not image_url: yield "##### β οΈ Provide an image URL" return yield "##### β Fetching image and running model..." try: pil_img = await open_image_url(image_url) img = pn.pane.Image(pil_img, height=400, align="center") except Exception as e: yield f"##### π Something went wrong, please try a different URL!" return class_items = class_names.split(",") class_likelihoods = get_similarity_scores(class_items, pil_img) # build the results column results = pn.Column("##### π Here are the results!", img) for class_item, class_likelihood in zip(class_items, class_likelihoods): row_label = pn.widgets.StaticText( name=class_item.strip(), value=f"{class_likelihood:.2%}", align="center" ) row_bar = pn.indicators.Progress( value=int(class_likelihood * 100), sizing_mode="stretch_width", bar_color="secondary", margin=(0, 10), design=pn.theme.Material, ) results.append(pn.Column(row_label, row_bar)) yield results finally: main.disabled = False
# create widgetsrandomize_url = pn.widgets.Button(name="Randomize URL", align="end")
image_url = pn.widgets.TextInput( name="Image URL to classify", value=pn.bind(random_url, randomize_url),)class_names = pn.widgets.TextInput( name="Comma separated class names", placeholder="Enter possible class names, e.g. cat, dog", value="cat, dog, parrot",)
input_widgets = pn.Column( "##### π Click randomize or paste a URL to start classifying!", pn.Row(image_url, randomize_url), class_names,)
# add interactivityinteractive_result = pn.panel( pn.bind(process_inputs, image_url=image_url, class_names=class_names), height=600,)
# add footerfooter_row = pn.Row(pn.Spacer(), align="center")for icon, url in ICON_URLS.items(): href_button = pn.widgets.Button(icon=icon, width=35, height=35) href_button.js_on_click(code=f"window.open('{url}')") footer_row.append(href_button)footer_row.append(pn.Spacer())
# create dashboardmain = pn.WidgetBox( input_widgets, interactive_result, footer_row,)
title = "Panel Demo - Image Classification"pn.template.BootstrapTemplate( title=title, main=main, main_max_width="min(50%, 698px)", header_background="#F08080",).servable(title=title)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""/autopost: the posts of a whole series - "Episodes 01 to 20", "Episodes 21 to 40", ... - each with a download button.
The ranges are planned here (pure functions, easy to test); the handler in handlers/autopost.py sends them."""from __future__ import annotations
PLACEHOLDER_LINK = "https://t.me/English" # every button starts with this link; the real ones are asked for afterwardsMAX_POSTS = 200 # the most one /autopost run may postMAX_EPISODES = 100_000
USAGE = ( "Usage: <code>/autopost <total episodes> <interval></code>\n" "Example: <code>/autopost 114 20</code> posts Episodes 01 to 20, 21 to 40 ... up to 114, each with a download " "button, and then asks you for the real link of every button.")
def parse_autopost_args(raw: str) -> tuple: """'114 20' -> (114, 20). ValueError (with a message to show) when it can't be used.""" parts = (raw or "").replace(",", " ").split() if len(parts) != 2 or not all(p.isdigit() for p in parts): raise ValueError("I need two numbers: the total number of episodes and the interval.") total, interval = int(parts[0]), int(parts[1]) if total < 1 or interval < 1: raise ValueError("Both numbers must be at least 1.") if total > MAX_EPISODES: raise ValueError(f"The total can be at most {MAX_EPISODES}.") return total, interval
def plan_ranges(total: int, interval: int) -> list: """[(first, last), ...] covering 1..total in steps of `interval`.
The last, shorter range gets its own post when it is longer than half an interval (114 with 20 -> 101 to 114); when it is half an interval or less it is added to the post before it (102 with 20 -> 81 to 102).""" if total < 1 or interval < 1: raise ValueError("total and interval must be at least 1") ranges, start = [], 1 while start <= total: end = min(start + interval - 1, total) ranges.append((start, end)) start = end + 1 if len(ranges) >= 2: a, b = ranges[-1] size = b - a + 1 if size < interval and size * 2 <= interval: ranges.pop() ranges[-1] = (ranges[-1][0], b) return ranges
def pad(n: int) -> str: return f"{n:02d}"
def span(a: int, b: int) -> str: return f"{pad(a)} to {pad(b)}"
def title_of(a: int, b: int) -> str: return f"Episodes {span(a, b)}" if a != b else f"Episode {pad(a)}"
def post_text(a: int, b: int) -> str: return f"{title_of(a, b)}\n\nClick the button below to download π"
def button_label(a: int, b: int) -> str: return f"Download {title_of(a, b)}"
def post_buttons(a: int, b: int, link: str = PLACEHOLDER_LINK) -> list: return [[{"t": button_label(a, b), "u": link}]]
def ranges_summary(ranges: list, show: int = 8) -> str: """'01β20 Β· 21β40 Β· 41β60 Β· β¦ Β· 101β114' (the middle is left out of long lists).""" parts = [f"{pad(a)}β{pad(b)}" if a != b else pad(a) for a, b in ranges] if len(parts) > show: parts = parts[: show - 2] + ["β¦"] + parts[-2:] return " Β· ".join(parts)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337"""Putting a backup made by /export back into the bot (/import).
The backup is a JSON file: {"exported_at", "channels": [...], "posts": [...], "ignored": [...]}. Importing only ADDS:
* a channel the bot already has is left as it is (its title, username and access come from Telegram, which is newer than the file); a channel it does not have is added; * 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 draft that is not already here; * a post the owner has made the bot forget (/posts -> Only forget it in the bot) is not brought back; * nothing is ever deleted or overwritten.
The file is read as data only: every value is checked before it goes near the database."""from __future__ import annotations
import jsonimport loggingfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import Optional
from sqlalchemy import selectfrom sqlalchemy.exc import IntegrityError
from .db import Channel, Database, IgnoredPost, Post, as_utc, utcnow
log = logging.getLogger(__name__)
MAX_BYTES = 40 * 1024 * 1024 # a backup of tens of thousands of posts is a few megabytesCHUNK = 500 # rows saved in one goPOST_KINDS = ("draft", "sent")SOURCES = ("bot", "adopted")
class BackupError(ValueError): """The file can't be used; the message says why (and is safe to show)."""
# ------------------------------------------------------------------------------------------------ readingdef _int(value, what: str) -> int: if isinstance(value, bool) or not isinstance(value, int): raise ValueError(f"{what} is not a whole number") return value
def _text(value, what: str, limit: Optional[int] = None) -> str: if value is None: return "" if not isinstance(value, str): raise ValueError(f"{what} is not text") return value[:limit] if limit else value
def _when(value, what: str, default: Optional[datetime] = None) -> Optional[datetime]: if value in (None, ""): return default if not isinstance(value, str): raise ValueError(f"{what} is not a date") try: d = datetime.fromisoformat(value.strip().replace("Z", "+00:00")) except ValueError: raise ValueError(f"{what} is not a date") return as_utc(d)
def _rows_of(value, what: str) -> list: if value is None: return [] if not isinstance(value, list): raise BackupError(f"β{what}β should be a list.") return value
def channel_row(row) -> dict: """One channel of the file as the values for a Channel row (ValueError if it is not usable).""" if not isinstance(row, dict): raise ValueError("not an object") cid = _int(row.get("id"), "id") if cid == 0: raise ValueError("id is 0") username = _text(row.get("username"), "username", 64).strip().lstrip("@") or None created = _when(row.get("created_at"), "created_at", utcnow()) return dict( id=cid, access_hash=_int(row.get("access_hash", 0) or 0, "access_hash"), title=_text(row.get("title"), "title", 256), username=username, active=bool(row.get("active", True)), added_by=_int(row.get("added_by", 0) or 0, "added_by"), created_at=created, )
def _buttons(value) -> list: if value is None: return [] if not isinstance(value, list): raise ValueError("buttons are not a list") for line in value: if not isinstance(line, list) or not all(isinstance(b, dict) for b in line): raise ValueError("buttons are not rows of buttons") return value
def _entities(value) -> list: if value is None: return [] if not isinstance(value, list) or not all(isinstance(e, dict) for e in value): raise ValueError("formatting is not a list") return value
def post_row(row) -> dict: """One post of the file as the values for a Post row (ValueError if it is not usable).""" if not isinstance(row, dict): raise ValueError("not an object") cid = _int(row.get("channel_id"), "channel_id") mid = row.get("message_id") mid = None if mid is None else _int(mid, "message_id") status = row.get("status") or ("sent" if mid else "draft") if status not in POST_KINDS: raise ValueError(f"status β{str(status)[:20]}β is unknown") if status == "sent" and (mid is None or mid < 1): raise ValueError("a published post without a message id") if status == "draft": mid = None source = row.get("source") if row.get("source") in SOURCES else "bot" kind = row.get("media_kind") if kind is not None and (not isinstance(kind, str) or len(kind) > 16): raise ValueError("media_kind is not usable") ref = row.get("media_file_id") if ref is not None and not isinstance(ref, str): raise ValueError("media_file_id is not text") created = _when(row.get("created_at"), "created_at", utcnow()) return dict( channel_id=cid, message_id=mid, status=status, source=source, text=_text(row.get("text"), "text"), entities=_entities(row.get("entities")), media_kind=kind or None, media_file_id=ref or None, buttons=_buttons(row.get("buttons")), link_preview=bool(row.get("link_preview")), created_by=_int(row.get("created_by", 0) or 0, "created_by"), created_at=created, updated_at=_when(row.get("updated_at"), "updated_at", created), sent_at=_when(row.get("sent_at"), "sent_at"), )
@dataclassclass Backup: exported_at: Optional[str] = None channels: list = field(default_factory=list) # dicts for Channel(**d) posts: list = field(default_factory=list) # dicts for Post(**d) ignored: list = field(default_factory=list) # (channel id, message id) bad_rows: int = 0 # entries of the file that were not usable and are left out
def parse_backup(raw: bytes) -> Backup: """The file's bytes -> a Backup. BackupError (with a message for the person) when it is not an /export file.""" if len(raw) > MAX_BYTES: raise BackupError(f"it is larger than {MAX_BYTES // (1024 * 1024)} MB.") try: data = json.loads(raw.decode("utf-8-sig")) except (UnicodeDecodeError, ValueError): raise BackupError("it is not a JSON file. Send the file that /export made, unchanged.") if not isinstance(data, dict) or ("channels" not in data and "posts" not in data): raise BackupError("it does not look like a backup from /export (no channels and posts in it).") bk = Backup(exported_at=data.get("exported_at") if isinstance(data.get("exported_at"), str) else None) for row in _rows_of(data.get("channels"), "channels"): try: bk.channels.append(channel_row(row)) except (ValueError, TypeError): bk.bad_rows += 1 for row in _rows_of(data.get("posts"), "posts"): try: bk.posts.append(post_row(row)) except (ValueError, TypeError): bk.bad_rows += 1 for row in _rows_of(data.get("ignored"), "ignored"): try: if not isinstance(row, dict): raise ValueError("not an object") bk.ignored.append((_int(row.get("channel_id"), "channel_id"), _int(row.get("message_id"), "message_id"))) except (ValueError, TypeError): bk.bad_rows += 1 if not (bk.channels or bk.posts): raise BackupError("there is nothing in it that can be imported." + (" (All entries were unreadable.)" if bk.bad_rows else "")) return bk
# ------------------------------------------------------------------------------------------------ the plan@dataclassclass ImportPlan: backup: Backup new_channels: list = field(default_factory=list) # channel dicts that are not in the bot yet channels_present: int = 0 # channels of the file the bot has already (left as they are) new_posts: list = field(default_factory=list) # published posts and drafts to add posts_present: int = 0 # published posts at a message id the bot already has drafts_present: int = 0 # drafts that are here already posts_forgotten: int = 0 # posts the owner made the bot forget: not brought back posts_orphaned: int = 0 # posts of a channel that is neither in the bot nor in the file new_ignored: list = field(default_factory=list) # "forgotten" marks to add
@property def sent_to_add(self) -> int: return sum(1 for p in self.new_posts if p["status"] == "sent")
@property def drafts_to_add(self) -> int: return sum(1 for p in self.new_posts if p["status"] == "draft")
@property def nothing_new(self) -> bool: return not (self.new_channels or self.new_posts or self.new_ignored)
async def plan_import(db: Database, backup: Backup) -> ImportPlan: """What importing would do - nothing is written.""" plan = ImportPlan(backup=backup) async with db.Session() as s: have_channels = {int(c) for c in (await s.execute(select(Channel.id))).scalars()} known_marks = {(int(c), int(m)) for c, m in (await s.execute(select(IgnoredPost.channel_id, IgnoredPost.message_id))).all()} wanted = {p["channel_id"] for p in backup.posts} have_posts: set = set() have_drafts: set = set() if wanted: q = select(Post.channel_id, Post.message_id).where(Post.message_id.is_not(None)) have_posts = {(int(c), int(m)) for c, m in (await s.execute(q)).all() if int(c) in wanted} q = select(Post.channel_id, Post.text, Post.created_at).where(Post.status == "draft") have_drafts = {(int(c), t, as_utc(at)) for c, t, at in (await s.execute(q)).all() if int(c) in wanted} in_file: dict = {} for ch in backup.channels: if ch["id"] in have_channels: plan.channels_present += 1 elif ch["id"] not in in_file: in_file[ch["id"]] = ch plan.new_channels.append(ch) marks = set(known_marks) for mark in backup.ignored: if mark[0] in have_channels or mark[0] in in_file: if mark not in marks: marks.add(mark) plan.new_ignored.append(mark) seen_posts: set = set() seen_drafts: set = set() for p in backup.posts: cid = p["channel_id"] if cid not in have_channels and cid not in in_file: plan.posts_orphaned += 1 elif p["status"] == "sent": key = (cid, p["message_id"]) if key in marks: plan.posts_forgotten += 1 elif key in have_posts or key in seen_posts: plan.posts_present += 1 else: seen_posts.add(key) plan.new_posts.append(p) else: key = (cid, p["text"], p["created_at"]) if key in have_drafts or key in seen_drafts: plan.drafts_present += 1 else: seen_drafts.add(key) plan.new_posts.append(p) return plan
# ----------------------------------------------------------------------------------------------- doing it@dataclassclass ImportResult: channels_added: int = 0 posts_added: int = 0 drafts_added: int = 0 marks_added: int = 0 skipped_meanwhile: int = 0 # posts that turned up in the bot while the import was running
async def _save_posts(db: Database, rows: list) -> list: """Save these posts; returns the ones that were saved (one that is there already is skipped, never an error).""" async with db.Session() as s: s.add_all([Post(**r) for r in rows]) try: await s.commit() return list(rows) except IntegrityError: await s.rollback() saved = [] for r in rows: # one is there already: one by one async with db.Session() as s: s.add(Post(**r)) try: await s.commit() saved.append(r) except IntegrityError: await s.rollback() return saved
async def apply_import(db: Database, plan: ImportPlan, progress=None) -> ImportResult: """Write the plan: channels first (posts point at them), then the posts in pieces, then the "forgotten" marks.""" res = ImportResult() if plan.new_channels: async with db.Session() as s: for d in plan.new_channels: if await s.get(Channel, d["id"]) is None: s.add(Channel(**d)) res.channels_added += 1 await s.commit() rows = plan.new_posts for i in range(0, len(rows), CHUNK): part = rows[i : i + CHUNK] saved = await _save_posts(db, part) res.posts_added += sum(1 for r in saved if r["status"] == "sent") res.drafts_added += sum(1 for r in saved if r["status"] == "draft") res.skipped_meanwhile += len(part) - len(saved) if progress is not None: await progress(min(i + CHUNK, len(rows)), len(rows)) for cid, mid in plan.new_ignored: await db.ignore_post(cid, mid) res.marks_added += 1 return res
def stamp(iso: Optional[str]) -> str: """'2026-10-07T10:00:00+00:00' -> '07 Oct 2026, 10:00 UTC' (the text as it is when it can't be read).""" if not iso: return "" try: d = as_utc(datetime.fromisoformat(iso.replace("Z", "+00:00"))) except ValueError: return iso[:40] return d.astimezone(timezone.utc).strftime("%d %b %Y, %H:%M UTC")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Button model: rows of {'t': text, 'u': url} (URL buttons) or {'t', 'raw'} (other bots' buttons, kept as-is)."""from __future__ import annotations
import refrom typing import Optional
MAX_ROW = 8MAX_TOTAL = 100_URL_RX = re.compile(r"(?:https?://|tg://|t\.me/|telegram\.me/)\S+", re.I)
def norm_url(u: str) -> Optional[str]: u = (u or "").strip() if re.match(r"(?i)^(t\.me|telegram\.me)/", u): u = "https://" + u if not re.match(r"(?i)^(https?://|tg://)\S+$", u) or len(u) > 2000: return None return u
def parse_buttons_text(text: str) -> list: """One row per line, 'Text - link'. Several buttons in a row: separate them with ' | '.""" rows: list = [] total = 0 for line in (text or "").strip().splitlines(): line = line.strip() if not line: continue row = [] for part in re.split(r"\s+\|\s+|\s*&&\s*", line): part = part.strip() if not part: continue found = list(_URL_RX.finditer(part)) if not found: raise ValueError(f"No link found in: {part}") m = found[-1] label = part[: m.start()].strip().rstrip("-ββ:|=").strip() if not label: raise ValueError(f"No button text before the link in: {part}") url = norm_url(m.group(0)) if not url: raise ValueError(f"That link doesn't look valid: {m.group(0)}") row.append({"t": label, "u": url}) if len(row) > MAX_ROW: raise ValueError(f"At most {MAX_ROW} buttons fit in one row.") if row: rows.append(row) total += len(row) if total > MAX_TOTAL: raise ValueError(f"At most {MAX_TOTAL} buttons per post.") return rows
def copy_rows(rows: list) -> list: return [[dict(b) for b in row] for row in (rows or [])]
def count(rows: list) -> int: return sum(len(r) for r in rows or [])
def missing_links(rows: list) -> int: return sum(1 for r in rows or [] for b in r if not b.get("u") and not b.get("raw"))
def link_positions(rows: list) -> list: """(row, column) of every button that has a link of its own. Other bots' buttons (reactions...) are left out: they can't be edited.""" 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")]
def valid(rows: list, r: int, c: int) -> bool: return 0 <= r < len(rows) and 0 <= c < len(rows[r])
def add_button(rows: list, btn: dict, new_row: bool = True) -> list: rows = copy_rows(rows) if new_row or not rows or len(rows[-1]) >= MAX_ROW: rows.append([btn]) else: rows[-1].append(btn) return rows
def set_field(rows: list, r: int, c: int, **fields) -> list: rows = copy_rows(rows) if valid(rows, r, c): rows[r][c].update(fields) return rows
def delete_button(rows: list, r: int, c: int) -> list: rows = copy_rows(rows) if valid(rows, r, c): rows[r].pop(c) rows = [row for row in rows if row] return rows
def move_button(rows: list, r: int, c: int, direction: str) -> tuple: """direction: l | r | u | d. Returns (rows, new_r, new_c).""" rows = copy_rows(rows) if not valid(rows, r, c): return rows, r, c b = rows[r][c] if direction == "l": if c > 0: rows[r][c - 1], rows[r][c] = rows[r][c], rows[r][c - 1] c -= 1 elif direction == "r": if c < len(rows[r]) - 1: rows[r][c + 1], rows[r][c] = rows[r][c], rows[r][c + 1] c += 1 elif direction == "u": if r > 0 and len(rows[r - 1]) < MAX_ROW: rows[r].pop(c) pos = min(c, len(rows[r - 1])) rows[r - 1].insert(pos, b) nr, nc = r - 1, pos if not rows[r]: rows.pop(r) r, c = nr, nc elif direction == "d": if r < len(rows) - 1: if len(rows[r + 1]) < MAX_ROW: rows[r].pop(c) pos = min(c, len(rows[r + 1])) rows[r + 1].insert(pos, b) nr, nc = r + 1, pos if not rows[r]: rows.pop(r) nr -= 1 r, c = nr, nc elif len(rows[r]) > 1: # last row with company: split off into a new row below rows[r].pop(c) rows.append([b]) r, c = len(rows) - 1, 0 return rows, r, c
def grid_label(b: dict) -> str: t = (b.get("t") or "").strip() or "β¦" if len(t) > 26: t = t[:25] + "β¦" if b.get("raw"): return "π " + t if not b.get("u"): return "β οΈ " + t return t123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186"""Make sure the buttons shown in a channel are the ones we saved - and fix them when they are not.
Used by /repost (every new post is read back right after it is created) and by "Check buttons" in My posts,which repairs posts whose buttons are saved in the bot but are missing in the channel."""from __future__ import annotations
import asyncioimport loggingfrom dataclasses import dataclass, fieldfrom typing import Awaitable, Callable, Optional
from telethon import errors, types
from .replace_engine import CHUNK, fetch_messages, is_skippablefrom .tgutil import build_markup, button_url, edit_raw, flood_retry, peer_of
log = logging.getLogger(__name__)
ABORT_AFTER = 5 # stop repairing after this many failures in a row# A throw-away keyboard. If Telegram answers "message not modified" to the real keyboard (it believes the post# already has it), we first show this one, then the real one: two real changes.NUDGE_ROWS = [[{"t": "β¦", "u": "https://t.me/telegram"}]]
class ButtonsNotShown(RuntimeError): """Telegram accepted the edit, but the post still does not show the buttons it should."""
def link_buttons(markup) -> list: """[(text, url)] of the link buttons of a keyboard, in reading order.""" out: list = [] if isinstance(markup, types.ReplyInlineMarkup): for row in markup.rows: for b in row.buttons: u = button_url(b) if u is not None: out.append((getattr(b, "text", ""), u)) return out
def link_urls(markup) -> list: return [u for _, u in link_buttons(markup)]
async def live_urls(client, peer, message_id: int) -> Optional[list]: """The link-button URLs the channel shows on a post right now; None if the post is gone.""" msgs = await fetch_messages(client, peer, [message_id]) m = msgs[0] if msgs else None if is_skippable(m): return None return link_urls(m.reply_markup)
async def ensure_markup(client, peer, message_id: int, markup, *, pause: float = 0.7) -> str: """Make post `message_id` show the link buttons of `markup`, and check it by reading the post back.
Returns "fine" (it already did), "set" (one edit was enough) or "nudged" (needed the two-step edit). Raises ButtonsNotShown if the buttons still are not there, LookupError if the post no longer exists. """ want = link_urls(markup) if not want: return "fine" live = await live_urls(client, peer, message_id) if live is None: raise LookupError(f"post {message_id} no longer exists") if live == want: return "fine"
try: await flood_retry(lambda: edit_raw(client, peer, message_id, markup=markup)) except errors.MessageNotModifiedError: pass # Telegram thinks the keyboard is already there - checked below if pause: await asyncio.sleep(pause) if await live_urls(client, peer, message_id) == want: return "set"
log.info("post %s: the edit did not make the buttons show - trying the two-step edit", message_id) for step in (build_markup(NUDGE_ROWS), markup): try: await flood_retry(lambda step=step: edit_raw(client, peer, message_id, markup=step)) except errors.MessageNotModifiedError: pass if pause: await asyncio.sleep(pause) if await live_urls(client, peer, message_id) == want: return "nudged" raise ButtonsNotShown(f"post {message_id} still does not show its buttons")
# ------------------------------------------------------------------------------------ checking@dataclassclass ButtonScan: channel: object total: int = 0 # saved posts that have link buttons fine: int = 0 bad: list = field(default_factory=list) # [(post, live urls, wanted urls)] gone: list = field(default_factory=list) # posts that no longer exist in the channel
async def scan_buttons( client, ch, posts: list, *, progress: Optional[Callable[[ButtonScan], Awaitable[None]]] = None) -> ButtonScan: """Compare the saved link buttons of `posts` with what the channel shows.""" scan = ButtonScan(channel=ch) peer = peer_of(ch) wanted = [] for p in posts: if not p.message_id: continue urls = link_urls(build_markup(p.buttons)) if urls: wanted.append((p, urls)) scan.total = len(wanted) for i in range(0, len(wanted), CHUNK): part = wanted[i : i + CHUNK] msgs = await fetch_messages(client, peer, [p.message_id for p, _ in part]) for (p, urls), m in zip(part, msgs): if is_skippable(m): scan.gone.append(p) elif link_urls(m.reply_markup) == urls: scan.fine += 1 else: scan.bad.append((p, link_urls(m.reply_markup), urls)) if progress: await progress(scan) return scan
@dataclassclass FixResult: fixed: int = 0 nudged: int = 0 # of those, how many needed the two-step edit already: int = 0 # turned out to be fine when looked at again gone: int = 0 failed: list = field(default_factory=list) # [(message id, error name)] aborted: Optional[str] = None stopped: bool = False
async def fix_buttons( client, ch, bad: list, *, delay: float = 1.2, pause: float = 0.7, progress: Optional[Callable[[FixResult], Awaitable[None]]] = None, should_stop: Optional[Callable[[], bool]] = None,) -> FixResult: """Put the saved buttons back on the posts in `bad` (the first item of each entry is the saved post).""" res = FixResult() peer = peer_of(ch) streak = 0 for entry in bad: post = entry[0] if should_stop and should_stop(): res.stopped = True break try: how = await ensure_markup(client, peer, post.message_id, build_markup(post.buttons), pause=pause) except LookupError: res.gone += 1 continue except Exception as e: # one bad post must not stop the others name = type(e).__name__ log.warning("could not fix the buttons of %s: %s %s", post.message_id, name, e) res.failed.append((post.message_id, name)) streak += 1 if streak >= ABORT_AFTER: res.aborted = name break await asyncio.sleep(delay) continue streak = 0 if how == "fine": res.already += 1 else: res.fixed += 1 if how == "nudged": res.nudged += 1 if progress: await progress(res) await asyncio.sleep(delay) return res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Find a channel from what a person types: @username, t.me link, numeric id (-100...), or an invite link.
Used by /shift. The bot can only talk to a channel it can see: registered channels (the database has their accessdetails), channels it has met in updates, public channels by @username, and channels it is a member of (invite link)."""from __future__ import annotations
import refrom dataclasses import dataclassfrom typing import Optional
from telethon import functions, types
from .common import Ctx, UserError
_REF_RX = re.compile(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me)/(?:c/(\d+)|([A-Za-z0-9_]{3,32}))(?:/\d+)?/?$")_INVITE_RX = re.compile(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me|telegram\.dog)/(?:\+|joinchat/)([A-Za-z0-9_-]{6,})/?$")_TG_INVITE_RX = re.compile(r"(?i)^tg://join\?invite=([A-Za-z0-9_-]{6,})$")
def parse_channel_ref(text: str): """@name / t.me link / numeric id -> username (str) or channel id (int); None if unrecognised.""" t = (text or "").strip() m = _REF_RX.match(t) if m: return int(m.group(1)) if m.group(1) else m.group(2) t = t.lstrip("@") if re.fullmatch(r"-?\d+", t): s = str(abs(int(t))) return int(s[3:]) if s.startswith("100") and len(s) > 10 else int(s) if re.fullmatch(r"[A-Za-z0-9_]{3,32}", t): return t return None
def classify_ref(text: str) -> tuple: """-> ("invite", hash) | ("username", name) | ("id", int) | (None, None)""" t = (text or "").strip() m = _INVITE_RX.match(t) or _TG_INVITE_RX.match(t) if m: return "invite", m.group(1) ref = parse_channel_ref(t) if isinstance(ref, int): return "id", ref if isinstance(ref, str): return "username", ref return None, None
@dataclassclass ChannelRef: """A channel as the bot can reach it."""
id: int access_hash: int title: str username: Optional[str] registered: bool # the bot's database knows it (it can be used with /new, /posts ...)
def _from_entity(ent, registered: bool) -> ChannelRef: if not isinstance(ent, types.Channel): raise UserError("That is not a channel (it looks like a user, bot or group). Only channels can be used here.") if not ent.broadcast: raise UserError("That is a group, not a channel. Only channels can be used here.") if not ent.access_hash or getattr(ent, "min", False): raise UserError( "I can see that channel, but Telegram has not given me its access details. Use its @username, or add the " "bot to the channel as an admin and post something there first." ) return ChannelRef(ent.id, ent.access_hash, ent.title or "", ent.username, registered)
async def _entity(client, what): try: return await client.get_entity(what) except Exception: return None
async def resolve_channel(ctx: Ctx, text: str) -> ChannelRef: """The channel `text` points at, or a UserError that says what to do.""" kind, value = classify_ref(text) if kind is None: raise UserError( f"β{text}β is not a channel I understand. Use an @username, a t.me link, the channel id (-100β¦) or an invite link." ) db, client = ctx.db, ctx.client if kind == "username": for ch in await db.list_channels(active_only=False): if ch.username and ch.username.lower() == value.lower(): return ChannelRef(ch.id, ch.access_hash, ch.title, ch.username, ch.active) ent = await _entity(client, value) if ent is None: raise UserError(f"I couldn't find a channel called @{value}. Check the name, or add the bot to it as an admin.") elif kind == "id": ch = await db.get_channel(value) if ch is not None: return ChannelRef(ch.id, ch.access_hash, ch.title, ch.username, ch.active) ent = ctx.seen_channels.get(value) or await _entity(client, types.PeerChannel(value)) if ent is None: raise UserError( f"I don't know a channel with the id {value}. A bot can only use an id for channels it is part of; " "use the @username instead, or add the bot to the channel as an admin." ) else: # invite link: only tells which channel it is; the bot cannot join by itself try: info = await client(functions.messages.CheckChatInviteRequest(hash=value)) except Exception as e: raise UserError(f"That invite link doesn't work ({type(e).__name__}).") chat = getattr(info, "chat", None) if chat is None: raise UserError( "The bot is not a member of that channel, so it cannot use that invite link. Add the bot to the channel " "as an admin first (a bot cannot join by itself)." ) ent = chat known = await db.get_channel(getattr(ent, "id", 0)) return _from_entity(ent, known is not None and known.active)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406"""Shared context, permission guard, message helpers and post send/edit operations."""from __future__ import annotations
import asyncioimport functoolsimport loggingimport shutilimport tempfileimport timefrom dataclasses import dataclass, fieldfrom types import SimpleNamespacefrom typing import Any, Callable, Optional
from telethon import TelegramClient, errors, events
from .buttons_sync import ensure_markup, link_urlsfrom .config import Configfrom .db import Databasefrom .replace_engine import fetch_messages, is_skippablefrom .richmsg import rich_of, send_rich, with_richfrom .tgutil import build_markup, de_entities, edit_raw, esc, explain_rpc, fetch_media, media_info, peer_of, with_mediafrom .userbot import UserbotError, UserbotRefused, edit_problem_text
log = logging.getLogger(__name__)
class UserError(Exception): """An error whose message is safe and useful to show to the user."""
@dataclassclass Ctx: cfg: Config db: Database client: TelegramClient admins: set = field(default_factory=set) state: dict = field(default_factory=dict) # user id -> {"mode": ..., ...} pending: dict = field(default_factory=dict) # tokens for confirm dialogs (replace, repost) seen_channels: dict = field(default_factory=dict) # channel id -> Channel entity seen in updates text_handlers: dict = field(default_factory=dict) # mode -> async fn(event, state) callbacks: dict = field(default_factory=dict) # prefix -> async fn(event, parts) pickers: dict = field(default_factory=dict) # channel chooser kind -> async fn(event, arg, page) that draws it again lock: asyncio.Lock = field(default_factory=asyncio.Lock) # one long job (replace / repost) at a time userbot: Any = None # app.userbot.Userbot or None reporter: Any = None # app.errorlog.ErrorReporter or None expirer: Any = None # app.expiry.Expirer (timed deletions of broadcasts) or None syncer: Any = None # app.syncer.Syncer (keeps My posts in step with the channels) or None sync_ignore: set = field(default_factory=set) # (channel id, message id) of posts the owner made the bot forget
def is_cb(event) -> bool: return isinstance(event, events.CallbackQuery.Event) or getattr(event, "_is_callback", False)
def guard(ctx: Ctx, owner: bool = False) -> Callable: """Only allowed users may use a handler; errors are turned into friendly messages."""
def deco(fn): @functools.wraps(fn) async def wrapper(event): uid = event.sender_id 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) if not ok: try: if is_cb(event): await event.answer("Not allowed.", alert=True) elif getattr(event, "is_private", False): await event.respond("β This bot is private.") except Exception: pass return try: await fn(event) except events.StopPropagation: raise except errors.MessageNotModifiedError: if is_cb(event): try: await event.answer() except Exception: pass except UserError as e: await notify_error(event, str(e)) except errors.RPCError as e: log.error("Telegram refused a request in handler %s (user %s)", fn.__name__, uid, exc_info=True) await notify_error(event, "β " + explain_rpc(e)) except Exception as e: log.exception("Unhandled exception in handler %s (user %s)", fn.__name__, uid) await notify_error(event, f"β οΈ Something went wrong: {type(e).__name__}: {str(e)[:200]}")
return wrapper
return deco
async def notify_error(event, text: str) -> None: try: if is_cb(event): try: await event.answer("That didn't work - see the message below.", alert=False) except Exception: pass await event.respond(esc(text), link_preview=False) except Exception: # pragma: no cover log.exception("could not report an error")
async def say(event, text: str, buttons=None): return await event.respond(text, buttons=buttons, link_preview=False)
async def edit_callback_message(event, text: str, buttons=None): """Edit the message a button was pressed on.
Telethon's CallbackQuery.edit() quietly starts a second `answer` task; the dispatcher has already answered the query, so we call edit_message directly instead. """ query = getattr(event, "query", None) if query is not None and hasattr(event, "client"): return await event.client.edit_message( await event.get_input_chat(), query.msg_id, text, buttons=buttons, link_preview=False ) return await event.edit(text, buttons=buttons, link_preview=False) # test doubles
async def show(event, text: str, buttons=None): """Edit the message a button was pressed on; for normal messages send a new one.""" if is_cb(event): try: return await edit_callback_message(event, text, buttons) except errors.MessageNotModifiedError: return None return await say(event, text, buttons)
def require_owner(ctx: Ctx, event) -> None: if not ctx.cfg.is_owner(event.sender_id): raise UserError("β Only the bot owner can do that.")
# ------------------------------------------------------------------ sending and editingasync def send_post(client, peer, post): ents = de_entities(post.entities) markup = build_markup(post.buttons) rich = rich_of(post) if rich is not None and not post.media_file_id: # a rich message: Telegram builds its blocks from what was kept return await send_rich(client, peer, rich, markup=markup) if post.media_file_id: return await with_media( post.media_file_id, lambda media: client.send_file( peer, media, caption=post.text or "", formatting_entities=ents, buttons=markup ), ) return await client.send_message( peer, post.text, formatting_entities=ents, buttons=markup, link_preview=bool(post.link_preview) )
async def push_edit(client, ch, p, *, replace_media: bool = False) -> None: """Make the live channel message look like `p` (any object with the Post fields).""" peer = peer_of(ch) ents = de_entities(p.entities) markup = build_markup(p.buttons) rich = rich_of(p) if rich is not None and not p.media_kind: await with_rich(rich, lambda inp: edit_raw(client, peer, p.message_id, rich_message=inp, markup=markup)) return if replace_media and p.media_file_id: await with_media( p.media_file_id, lambda media: client.edit_message( peer, p.message_id, text=p.text or "", formatting_entities=ents, buttons=markup, file=media ), ) else: await edit_raw( client, peer, p.message_id, text=p.text or "", entities=ents, markup=markup, preview=None if p.media_kind else bool(p.link_preview), )
# 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# when Telegram dislikes the text itself.USERBOT_EDITS = {"text", "entities", "link_preview"}NOT_THE_USERBOTS_JOB = { "EntityBoundsInvalidError", "EntitiesTooLongError", "MessageTooLongError", "MediaCaptionTooLongError", "MessageEmptyError", "ButtonUrlInvalidError", "ReplyMarkupInvalidError",}
@dataclassclass EditReport: """How the edit of a published post went (for the message the owner gets)."""
by_userbot: bool = False # Telegram refused the bot, so the userbot made the edit bot_error: Optional[str] = None # the name of the error Telegram gave the bot buttons: Optional[str] = None # after the userbot's edit: "kept" | "restored" | "lost" (None: no link buttons saved) notes: list = field(default_factory=list) # what the userbot had to do in the channel (joined, got a right ...) media: Optional[tuple] = None # (kind, reference) of the photo / file the post shows now, as the bot sees it
def edit_report_text(report: Optional[EditReport]) -> str: """The lines to add to the owner's message when the userbot had to make the edit (empty for an ordinary edit).""" if report is None or not report.by_userbot: return "" lines = [f"π€ Telegram refused the bot ({esc(report.bot_error or 'error')}), so the userbot made the edit."] if report.buttons == "kept": lines.append("The buttons are still on the post.") elif report.buttons == "restored": lines.append("Telegram dropped the buttons with that edit, so the bot put them back.") elif report.buttons == "lost": lines.append( "Telegram dropped the buttons with that edit and the bot may not put them back. They stay saved in " "My posts; π§ Check buttons tries again." ) if report.notes: text = "; ".join(report.notes) lines.append("βΉοΈ " + esc(text[:1].upper() + text[1:]) + ".") return "\n".join(lines)
async def put_buttons_back(client, ch, p) -> Optional[str]: """After the userbot's edit: make the post show its saved link buttons again where Telegram dropped them.
"kept" (they were there), "restored", "lost" (Telegram won't let the bot set them), None (none are saved).""" markup = build_markup(p.buttons) if not link_urls(markup): return None try: how = await ensure_markup(client, peer_of(ch), p.message_id, markup) except Exception as e: # noqa: BLE001 - the edit itself worked; only the buttons are missing log.info("could not put the buttons back on %s: %s", p.message_id, type(e).__name__) return "lost" return "kept" if how == "fine" else "restored"
async def live_media(client, ch, message_id: int) -> Optional[tuple]: """(kind, reference) of the photo / file the channel post shows now, as the bot sees it; None if it can't be read.""" try: msgs = await fetch_messages(client, peer_of(ch), [message_id]) except Exception: # noqa: BLE001 return None m = msgs[0] if msgs else None if is_skippable(m): return None kind, ref = media_info(m) return (kind, ref) if kind else None
async def edit_by_userbot(ctx: Ctx, ch, p, *, replace_media: bool, bot_error: str, notify=None) -> Optional[EditReport]: """The userbot makes the live post look like `p`. None when there is no userbot to ask; UserbotError when it fails.
A new photo / file goes through the userbot's own chat with the bot: the bot sends it there and the userbot edits the post with that copy, so nothing is downloaded or uploaded - a big file is as quick as a small one and keeps its thumbnail. Only when that does not work does the bot download the file (with its thumbnail) and the userbot upload it again, which is slow for a big file. `notify(text)` tells the owner what is going on.""" ub = ctx.userbot editor = await ub.editor_for(ch) if ub is not None else None if editor is None: return None report = EditReport(by_userbot=True, bot_error=bot_error) folder = None
async def tell(text: str) -> None: if notify is not None: await notify(text)
fields = dict( text=p.text or "", entities=de_entities(p.entities), preview=None if p.media_kind or rich_of(p) else bool(p.link_preview), rich=None if p.media_kind else rich_of(p), ) try: await tell("β³ Telegram refused the bot, so the userbot is making the edit.") if not (replace_media and p.media_file_id): await editor.edit(p.message_id, **fields) else: done = False media = await editor.media_by_reference(p.media_file_id) if media is not None: try: await editor.edit(p.message_id, media=media, **fields) done = True editor.notes.append("the new file went through the userbot's chat with the bot, so nothing was uploaded") except UserbotRefused as e: if not e.about_media: raise editor.dm_problem = f"Telegram would not take the userbot's copy of the file ({e.name})" if not done: why = editor.dm_problem or "that did not work" editor.notes.append(f"the file was downloaded and uploaded again, because {why}") await tell( "β³ The file can't go through the userbot's chat with the bot, so it is downloaded and uploaded " f"again - a big file takes a while. (Reason: {esc(why)}.)" ) folder = tempfile.mkdtemp(prefix="cpb-media-") try: media = await fetch_media(ctx.client, p.media_file_id, p.media_kind, folder) except (errors.RPCError, OSError, ValueError) as e: raise UserbotError(f"I could not download the new media for the userbot ({type(e).__name__}).") await editor.edit(p.message_id, media=media, **fields) finally: await editor.close() report.notes = list(editor.notes) if folder: shutil.rmtree(folder, ignore_errors=True) if replace_media: report.media = await live_media(ctx.client, ch, p.message_id) report.buttons = await put_buttons_back(ctx.client, ch, p) return report
async def apply_edit_reported(ctx: Ctx, post, ch, *, replace_media: bool = False, notify=None, **changes): """Edit the channel message first (if the post is published), and only then save the change.
The bot edits. If Telegram refuses it (a post that belongs to another bot) and the change is to the text, caption or media, the userbot makes the edit instead. Returns (the saved post, an EditReport).""" report = EditReport() if post.status == "sent" and post.message_id: new = SimpleNamespace(**{**post.as_dict(), **changes}) try: await push_edit(ctx.client, ch, new, replace_media=replace_media) except errors.MessageNotModifiedError: pass except errors.RPCError as e: refused = "β " + explain_rpc(e) if type(e).__name__ in NOT_THE_USERBOTS_JOB or not (replace_media or USERBOT_EDITS & set(changes)): raise UserError(refused + "\nNothing was changed.") try: done = await edit_by_userbot( ctx, ch, new, replace_media=replace_media, bot_error=type(e).__name__, notify=notify ) except UserbotError as ue: log.info("the userbot could not make the edit either: %s", ue) raise UserError(f"{refused} {edit_problem_text(ctx.userbot, fallback_error=str(ue))}\nNothing was changed.") if done is None: raise UserError(f"{refused} {edit_problem_text(ctx.userbot)}\nNothing was changed.") report = done if report.media: # the post now shows the userbot's upload: keep My posts in step with it changes = {**changes, "media_kind": report.media[0], "media_file_id": report.media[1]} return await ctx.db.update_post(post.id, **changes), report
async def apply_edit(ctx: Ctx, post, ch, *, replace_media: bool = False, **changes): """apply_edit_reported for the callers that only want the saved post.""" saved, _ = await apply_edit_reported(ctx, post, ch, replace_media=replace_media, **changes) return saved
def purge_pending(ctx: Ctx, ttl: float = 3600.0) -> None: """Forget confirm dialogs (replace plans, repost choices...) nobody answered for a while.""" now = time.monotonic() stale = [ k for k, v in ctx.pending.items() if not getattr(v, "running", False) and now - getattr(v, "created", now) > ttl ] for k in stale: ctx.pending.pop(k, None)
def on_cb(ctx: Ctx, prefix: str): def deco(fn): ctx.callbacks[prefix] = fn return fn
return deco
def on_text(ctx: Ctx, mode: str): def deco(fn): ctx.text_handlers[mode] = fn return fn
return deco
def set_state(ctx: Ctx, uid: int, mode: str, **data: Any) -> dict: ctx.state[uid] = {"mode": mode, **data} return ctx.state[uid]
def clear_state(ctx: Ctx, uid: int) -> Optional[dict]: return ctx.state.pop(uid, None)
def cmd(name: str, args: bool = False): """Event builder for a private-chat command such as /new or /replace <args>.""" pat = rf"(?is)^/{name}(?:@\w+)?" + (r"(?:\s+(.*))?$" if args else r"\s*$") return events.NewMessage(incoming=True, pattern=pat, func=lambda e: e.is_private)
async def discard_temp(ctx: Ctx, uid: int) -> None: """Drop a half-made draft when the user abandons the flow that was creating it.""" st = ctx.state.get(uid) if st and st.get("temp") and st.get("pid"): p = await ctx.db.get_post(st["pid"]) if p is not None and p.status == "draft": await ctx.db.delete_post(p.id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133"""Settings, read from environment variables (or a .env file)."""from __future__ import annotations
import mathimport osimport tempfilefrom dataclasses import dataclassfrom typing import Optional
try: # python-dotenv is optional; real env vars always win from dotenv import load_dotenv
load_dotenv()except Exception: # pragma: no cover pass
def _ints(name: str) -> frozenset: raw = os.getenv(name, "") or "" out = set() for part in raw.replace(";", ",").replace(" ", ",").split(","): part = part.strip() if part.lstrip("-").isdigit(): out.add(int(part)) return frozenset(out)
def _bool(name: str, default: bool) -> bool: raw = os.getenv(name) if raw is None or raw.strip() == "": return default return raw.strip().lower() in {"1", "true", "yes", "on"}
DEFAULT_ERROR_LOG_CHAT_ID = -1002525172451_OFF = {"0", "off", "none", "false", "no", "disabled", "disable"}
def _chat_id(name: str, default: Optional[int]) -> Optional[int]: """A chat id from the environment: unset or empty -> default, "0" / "off" -> None (switched off).""" raw = (os.getenv(name) or "").strip() if raw == "": return default if raw.lower() in _OFF: return None try: return int(raw) except ValueError: raise SystemExit(f"{name} must be a chat id such as -1001234567890 (or 0 / off to switch it off), not {raw!r}")
def _float(name: str, default: float) -> float: try: return float(os.getenv(name, "") or default) except ValueError: return default
def _whole(name: str, default: int) -> int: """A whole number from the environment; anything that is not a finite number gives the default.""" value = _float(name, float(default)) return int(value) if math.isfinite(value) else default
@dataclass(frozen=True)class Config: api_id: int api_hash: str bot_token: str owners: frozenset admins: frozenset database_url: str db_pool: str session_path: str session_string: str edit_delay: float replace_typed_links: bool port: int log_level: str error_log_chat_id: Optional[int] = None # errors are sent to this chat; None = off userbot_session: str = "" # session text of the helper account that deletes old posts userbot_keep_admin: bool = False # keep the userbot an admin after a clean-up (default: take the right away) delete_service_messages: bool = True # remove "channel name changed", "pinned a message", video chat ... notices sync_interval_minutes: int = 60 # how often every channel is compared with My posts (0 = never on its own) import_old_posts: bool = True # read the posts that were in a channel before the bot was added into My posts markup_input: bool = True # text typed as HTML or Markdown (and sent without Telegram formatting) becomes real formatting
def is_owner(self, uid) -> bool: return uid in self.owners
def is_allowed(self, uid) -> bool: return uid in self.owners or uid in self.admins
def default_session_path() -> str: """Outside the app folder on purpose: a host that publishes that folder (python -m http.server) must not publish the login session. A bot can always log in again with its token, so losing it is harmless.""" return os.path.join(tempfile.gettempdir(), "channel-post-bot", "bot")
def load_config() -> Config: missing = [k for k in ("API_ID", "API_HASH", "BOT_TOKEN") if not os.getenv(k)] owners = _ints("OWNER_IDS") if not owners: missing.append("OWNER_IDS") if missing: raise SystemExit("Missing required settings: " + ", ".join(missing) + " (see .env.example)") try: api_id = int(os.environ["API_ID"]) except ValueError: raise SystemExit("API_ID must be a number") return Config( api_id=api_id, api_hash=os.environ["API_HASH"].strip(), bot_token=os.environ["BOT_TOKEN"].strip(), owners=owners, admins=frozenset(), database_url=(os.getenv("DATABASE_URL") or "sqlite+aiosqlite:///data/bot.db").strip(), db_pool=(os.getenv("DB_POOL") or "null").strip().lower(), session_path=(os.getenv("SESSION_PATH") or default_session_path()).strip(), session_string=(os.getenv("SESSION_STRING") or "").strip(), edit_delay=max(0.3, _float("EDIT_DELAY", 1.2)), replace_typed_links=_bool("REPLACE_TYPED_LINKS", True), port=int(os.getenv("PORT") or 0), log_level=(os.getenv("LOG_LEVEL") or "INFO").upper(), error_log_chat_id=_chat_id("ERROR_LOG_CHAT_ID", DEFAULT_ERROR_LOG_CHAT_ID), userbot_session=(os.getenv("USERBOT_SESSION") or "").strip(), userbot_keep_admin=_bool("USERBOT_KEEP_ADMIN", False), delete_service_messages=_bool("DELETE_SERVICE_MESSAGES", True), sync_interval_minutes=max(0, _whole("SYNC_INTERVAL_MINUTES", 60)), import_old_posts=_bool("IMPORT_OLD_POSTS", True), markup_input=_bool("MARKUP_INPUT", True), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406"""Links to posts that moved: pointed at their new place in EVERY connected channel.
/repost gives every post of a channel a new message id, and /shift -c puts the posts into another channel. A link tothe old post - https://t.me/name/52, https://t.me/c/123/52, a hyperlink behind some text, a button - that sits in ANYconnected channel would lead nowhere once the old post is gone. relink_channels reads the connected channels, findsthose links and points them at the equivalent new post. Only the digits of the id change (for /shift also the channelpart of the link); the text around a link, the formatting and all other buttons stay exactly as they are.
Rules * only a link whose old post HAS a copy is changed: a link to a post that was not copied stays as it is; * running it again changes nothing more - a link that already points at a copy is not an old link any more; * a post is read again right before it is edited, so something an admin changed meanwhile is never overwritten; * a post of somebody else is edited only if the bot has the "Edit messages of others" right; otherwise it is only counted, so the report can say so; * what Telegram holds back (a copyright notice instead of the post) and a channel Telegram restricts are not edited; * nothing is deleted anywhere."""from __future__ import annotations
import asyncioimport loggingfrom dataclasses import dataclass, fieldfrom typing import Any, Awaitable, Callable, Optional
from telethon import errors, types
from .buttons_sync import ensure_markup, link_urlsfrom .postlinks import PostLinks, relink_messagefrom .replace_engine import CHUNK, fetch_messages, is_skippable, preview_flagfrom .restrictions import message_restriction, probe_channelfrom .tgutil import FATAL, edit_raw, esc, flood_retry, get_rights, peer_of, ser_entities, ser_markup
log = logging.getLogger(__name__)
PAUSE = 0.25 # between two reads while a channel is scannedABORT_AFTER = 5 # the same refusal this many times in a row: leave the channel (the others are still done)
@dataclassclass ChannelLinks: """What was found and done in one channel."""
channel: Any scanned: int = 0 # message ids read so far top: int = 0 # the last id that is read checked: int = 0 # posts looked at found: int = 0 # posts with a link to change relinked: int = 0 # posts whose links were changed links: int = 0 # links changed in total not_allowed: int = 0 # posts with a link to change that the bot may not edit (somebody else's, no right) held_back: int = 0 # posts Telegram holds back (copyright ...): left as they are gone: int = 0 # posts that were deleted while we worked failed: list = field(default_factory=list) # [(message id, error name)] skipped: Optional[str] = None # why the channel was not looked at aborted: Optional[str] = None # the refusal that made us give up on this channel
@dataclassclass CrossResult: """What a run did in all the channels (also handed to `progress` while it works)."""
channels: list = field(default_factory=list) # [ChannelLinks], in the order they were done total: int = 0 # channels to look at index: int = 0 # the number of the channel being worked on (1 = the first) current: Optional[ChannelLinks] = None phase: str = "" # scan | edit stopped: bool = False
@property def relinked(self) -> int: return sum(c.relinked for c in self.channels)
@property def links(self) -> int: return sum(c.links for c in self.channels)
@property def failed(self) -> list: return [(c.channel, mid, name) for c in self.channels for mid, name in c.failed]
@property def not_allowed(self) -> int: return sum(c.not_allowed for c in self.channels)
@property def changed_channels(self) -> list: return [c for c in self.channels if c.relinked]
@property def skipped(self) -> list: return [c for c in self.channels if c.skipped]
@property def clean(self) -> bool: """Everything that had to be done was done.""" return not self.stopped and not self.failed and not self.not_allowed and not any(c.aborted for c in self.channels)
async def _edit(client, peer, m, rl) -> None: if rl.text_changed: await edit_raw(client, peer, m.id, text=rl.text, entities=rl.entities, markup=rl.markup, preview=preview_flag(m)) else: # only buttons changed: the text is not sent again await edit_raw(client, peer, m.id, markup=rl.markup)
async def _scan( client, peer, top: int, links: PostLinks, leave: set, mine: set, can_edit_others: bool, res: ChannelLinks, *, pause: float, tick: Callable[[], Awaitable[None]], should_stop: Optional[Callable[[], bool]],) -> list: """Read ids 1..top; the ids of the posts that have links to change (and may be changed) come back, oldest first.""" todo: list = [] a = 1 while a <= top: if should_stop and should_stop(): break hi = min(a + CHUNK - 1, top) for m in await fetch_messages(client, peer, list(range(a, hi + 1))): if m is None or isinstance(m, (types.MessageEmpty, types.MessageService)): continue res.checked += 1 if m.id in leave: continue if message_restriction(m): res.held_back += 1 continue if relink_message(m, links) is None: continue res.found += 1 if not (getattr(m, "out", False) or m.id in mine) and not can_edit_others: res.not_allowed += 1 continue todo.append(m.id) res.scanned = hi a = hi + 1 await tick() if pause and a <= top: await asyncio.sleep(pause) return todo
async def _apply( client, db, ch, peer, ids: list, links: PostLinks, res: ChannelLinks, *, delay: float, settle_pause: float, tick: Callable[[], Awaitable[None]], should_stop: Optional[Callable[[], bool]],) -> bool: """Edit the posts in `ids`, each one read again first. False when the run was stopped.""" streak, last_name = 0, None for mid in ids: if should_stop and should_stop(): return False (m,) = await fetch_messages(client, peer, [mid]) if is_skippable(m): res.gone += 1 continue if message_restriction(m): res.held_back += 1 continue rl = relink_message(m, links) if rl is None: # somebody fixed it meanwhile continue try: await flood_retry(lambda: _edit(client, peer, m, rl)) if link_urls(rl.markup): await ensure_markup(client, peer, m.id, rl.markup, pause=settle_pause) except errors.MessageNotModifiedError: continue except Exception as e: # one bad post must not stop the others name = type(e).__name__ log.warning("could not update the links of %s/%s: %s %s", ch.id, m.id, name, e) res.failed.append((m.id, name)) streak = streak + 1 if name == last_name else 1 last_name = name if name in FATAL or streak >= ABORT_AFTER: res.aborted = name return True continue streak, last_name = 0, None res.relinked += 1 res.links += rl.links fields: dict = {} if rl.text_changed: fields.update(text=rl.text, entities=ser_entities(rl.entities)) if rl.markup_changed: fields["buttons"] = ser_markup(rl.markup) try: await db.update_post_by_message(ch.id, m.id, **fields) except Exception: # the channel is right; the next sync corrects the saved copy log.warning("could not save the new links of %s/%s", ch.id, m.id, exc_info=True) await tick() await asyncio.sleep(delay) return True
async def relink_channels( client, db, links: PostLinks, channels: list, *, leave: Optional[dict] = None, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, progress: Optional[Callable[[CrossResult], Awaitable[None]]] = None, should_stop: Optional[Callable[[], bool]] = None, result: Optional[CrossResult] = None,) -> CrossResult: """Point every link that `links` knows (old post -> its new place) at the new place, in each of `channels`.
`leave` ({channel id: message ids}) are posts that must not be touched, such as the originals of a repost. `result` may be given to watch a run from outside: it is filled in while the run goes on.""" res = result if result is not None else CrossResult() res.total = len(channels) leave = leave or {} if not links.ids: return res
async def tick() -> None: if progress: await progress(res)
for n, ch in enumerate(channels, 1): if should_stop and should_stop(): res.stopped = True break one = ChannelLinks(channel=ch) res.channels.append(one) res.index, res.current, res.phase = n, one, "scan" await tick() peer = peer_of(ch) rights = await get_rights(client, ch) if rights is not None and not rights.admin: one.skipped = "the bot is not an admin there" continue if rights is not None and not (rights.post or rights.edit): one.skipped = "the bot has no right to post or edit there" continue can_others = True if rights is None else bool(rights.edit) top, why, err = await probe_channel(client, peer) if err: one.skipped = err continue if why: one.skipped = f"Telegram restricts this channel ({why})" continue one.top = top or 0 try: todo = await _scan( client, peer, one.top, links, set(leave.get(ch.id, ())), await db.mine_message_ids(ch.id), can_others, one, pause=pause, tick=tick, should_stop=should_stop, ) if should_stop and should_stop(): res.stopped = True break res.phase = "edit" await tick() if not await _apply( client, db, ch, peer, todo, links, one, delay=delay, settle_pause=settle_pause, tick=tick, should_stop=should_stop, ): res.stopped = True break except errors.RPCError as e: # the channel can't be read (any more): the others still can log.warning("could not read %s while pointing links at the new posts: %s", ch.id, type(e).__name__) one.aborted = type(e).__name__ res.phase, res.current = "", None return res
# ------------------------------------------------------------------------------ the three ways to use itasync def relink_after_repost( client, db, ch, mig, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, progress=None, should_stop=None, result: Optional[CrossResult] = None,) -> CrossResult: """After /repost: every link to an old post of `ch`, in any connected channel, points at the copy of that post. The originals themselves are not touched (they are deleted later, or kept if the repost is undone).""" res = result if result is not None else CrossResult() ids = dict(await db.migration_pairs(mid=mig.id)) if not ids: return res await db.set_mark(mig.id, "links") # from now on an undo has to point the links back return await relink_channels( client, db, PostLinks.for_channel(ch, ids), await db.list_channels(), leave={ch.id: set(ids)}, delay=delay, settle_pause=settle_pause, pause=pause, progress=progress, should_stop=should_stop, result=res, )
async def restore_after_undo( client, db, ch, mig, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, progress=None, should_stop=None, result: Optional[CrossResult] = None,) -> CrossResult: """Before the copies of a repost are removed: links that were pointed at them go back to the original posts.""" res = result if result is not None else CrossResult() if not await db.has_mark(mig.id, "links"): return res # no link anywhere was changed for this repost back = {new: old for old, new in await db.migration_pairs(mid=mig.id)} return await relink_channels( client, db, PostLinks.for_channel(ch, back), await db.list_channels(), leave={ch.id: set(back)}, delay=delay, settle_pause=settle_pause, pause=pause, progress=progress, should_stop=should_stop, result=res, )
def shift_links(src, dst, ids: dict) -> PostLinks: """Links to the posts of the source channel -> the equivalent posts of the destination (`ids`: source id -> copy).""" return PostLinks( username=src.username, channel_id=src.id, ids=ids, target_username=dst.username, target_id=dst.id )
async def relink_after_shift( client, db, shift, src, dst, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, progress=None, should_stop=None, result: Optional[CrossResult] = None,) -> CrossResult: """After /shift -c: a link to a post of the source channel, in any connected channel (the source itself is only read, never changed), points at the copy of that post in the destination.""" res = result if result is not None else CrossResult() ids = dict(await db.shift_pairs(shift.id)) if not ids: return res await db.set_mark(shift.id, "links") chans = [c for c in await db.list_channels() if c.id != src.id] return await relink_channels( client, db, shift_links(src, dst, ids), chans, delay=delay, settle_pause=settle_pause, pause=pause, progress=progress, should_stop=should_stop, result=res, )
async def restore_after_shift_undo( client, db, shift, src, dst, *, delay: float = 1.2, settle_pause: float = 0.7, pause: float = PAUSE, progress=None, should_stop=None, result: Optional[CrossResult] = None,) -> CrossResult: """Before the copies of a shift are removed: links that were pointed at them go back to the source posts.""" res = result if result is not None else CrossResult() if not await db.has_mark(shift.id, "links"): return res back = {new: old for old, new in await db.shift_pairs(shift.id)} links = PostLinks( username=dst.username, channel_id=dst.id, ids=back, target_username=src.username, target_id=src.id ) chans = [c for c in await db.list_channels() if c.id != src.id] return await relink_channels( client, db, links, chans, leave={dst.id: set(back)}, delay=delay, settle_pause=settle_pause, pause=pause, progress=progress, should_stop=should_stop, result=res, )
# ------------------------------------------------------------------------------------------ the reportdef _name(ch) -> str: return esc(getattr(ch, "title", None) or str(getattr(ch, "id", "?")))
def report_lines(res: CrossResult, *, what: str = "the new copies", back: bool = False) -> list: """Lines (HTML) for the end of a repost / shift. `what`: where the links point now. `back`: they were pointed back.""" out: list = [] done = [c for c in res.channels if not c.skipped] if res.relinked: n = len(res.changed_channels) out.append( f"π {res.links} link(s) in {res.relinked} post(s) of {n} channel(s) " f"{'point back at the original posts' if back else 'now point at ' + what}." ) if n > 1 or (n == 1 and len(done) > 1): for c in res.changed_channels[:12]: out.append(f"β’ {_name(c.channel)}: {c.links} link(s) in {c.relinked} post(s)") elif done and not res.stopped and not any(c.aborted or c.failed for c in done): out.append(f"π Checked {len(done)} channel(s): no link there needed changing.") if res.not_allowed: names = ", ".join(_name(c.channel) for c in res.channels if c.not_allowed) out.append( f"{res.not_allowed} post(s) with such a link were made by somebody else and the bot may not edit them " f"({names}). Give the bot the βEdit messages of othersβ right and press βπ Update links againβ." ) failed = res.failed if failed: sample = ", ".join(f"{_name(c)} #{mid} {esc(name)}" for c, mid, name in failed[:5]) out.append(f"{len(failed)} post(s) could not get their links updated ({sample}{'β¦' if len(failed) > 5 else ''}).") if any(name in ("MessageIdInvalidError", "MessageAuthorRequiredError") for _, _, name in failed): out.append( "Telegram refuses edits to posts that other bots (or other people) made or put buttons on: those " "links have to be changed by their owner." ) for c in res.channels: if c.aborted: out.append(f"Gave up on {_name(c.channel)} ({esc(c.aborted)}).") skipped = res.skipped if skipped: out.append("Not looked at: " + "; ".join(f"{_name(c.channel)} ({esc(c.skipped)})" for c in skipped[:8])) held = sum(c.held_back for c in res.channels) if held: out.append(f"{held} post(s) are held back by Telegram (copyright notice) and were left alone.") if res.stopped: out.append("βΉ Stopped before every channel was done - press βπ Update links againβ to finish.") return out
def progress_text(res: CrossResult, *, title: str = "Pointing links at the new copies") -> str: """The line shown while a run is going on.""" cur = res.current where = f" - {_name(cur.channel)}" if cur is not None else "" step = f" ({res.index} of {res.total})" if res.total else "" if cur is not None and res.phase == "scan" and cur.top: detail = f"\nReading posts {cur.scanned} of {cur.top}β¦" elif cur is not None and res.phase == "edit": detail = f"\nChanging links: {cur.relinked} of {cur.found - cur.not_allowed} post(s) doneβ¦" else: detail = "" return f"π {title}{step}{where}{detail}\n{res.links} link(s) changed so far."12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067"""Database layer (SQLAlchemy 2.0 async). PostgreSQL in production, SQLite for local tests."""from __future__ import annotations
import asyncioimport loggingimport osfrom datetime import datetime, timezonefrom typing import Any, Optionalfrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from sqlalchemy import ( JSON, BigInteger, Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, delete, desc, func, select, update,)from sqlalchemy.dialects.postgresql import JSONBfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import async_sessionmaker, create_async_enginefrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_columnfrom sqlalchemy.pool import NullPool
log = logging.getLogger(__name__)
JSONType = JSON().with_variant(JSONB(), "postgresql")
def utcnow() -> datetime: return datetime.now(timezone.utc)
class Base(DeclarativeBase): pass
class Channel(Base): __tablename__ = "channels"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False) access_hash: Mapped[int] = mapped_column(BigInteger, default=0) title: Mapped[str] = mapped_column(String(256), default="") username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) active: Mapped[bool] = mapped_column(Boolean, default=True) added_by: Mapped[int] = mapped_column(BigInteger, default=0) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class Post(Base): __tablename__ = "posts" __table_args__ = (UniqueConstraint("channel_id", "message_id", name="uq_post_channel_msg"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) channel_id: Mapped[int] = mapped_column(BigInteger, ForeignKey("channels.id"), index=True) message_id: Mapped[Optional[int]] = mapped_column(BigInteger, nullable=True) status: Mapped[str] = mapped_column(String(16), default="draft", index=True) # draft | sent source: Mapped[str] = mapped_column(String(16), default="bot") # bot | adopted text: Mapped[str] = mapped_column(Text, default="") entities: Mapped[list] = mapped_column(JSONType, default=list) media_kind: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) media_file_id: Mapped[Optional[str]] = mapped_column(Text, nullable=True) buttons: Mapped[list] = mapped_column(JSONType, default=list) link_preview: Mapped[bool] = mapped_column(Boolean, default=False) created_by: Mapped[int] = mapped_column(BigInteger, default=0) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
def as_dict(self) -> dict: return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class Batch(Base): """One /swap run (so it can be undone)."""
__tablename__ = "batches"
id: Mapped[str] = mapped_column(String(32), primary_key=True) old_username: Mapped[str] = mapped_column(String(64)) new_username: Mapped[str] = mapped_column(String(64)) created_by: Mapped[int] = mapped_column(BigInteger, default=0) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) undone: Mapped[bool] = mapped_column(Boolean, default=False)
class Change(Base): __tablename__ = "changes"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) batch_id: Mapped[str] = mapped_column(String(32), ForeignKey("batches.id"), index=True) channel_id: Mapped[int] = mapped_column(BigInteger) message_id: Mapped[int] = mapped_column(BigInteger) old_state: Mapped[dict] = mapped_column(JSONType, default=dict) new_state: Mapped[dict] = mapped_column(JSONType, default=dict) reverted: Mapped[bool] = mapped_column(Boolean, default=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class Migration(Base): """One /repost run: a channel copied post by post, so it can be continued, undone or finished."""
__tablename__ = "migrations"
id: Mapped[str] = mapped_column(String(32), primary_key=True) channel_id: Mapped[int] = mapped_column(BigInteger, index=True) old_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) new_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) include_typed: Mapped[bool] = mapped_column(Boolean, default=True) include_posts: Mapped[bool] = mapped_column(Boolean, default=False) first_id: Mapped[int] = mapped_column(BigInteger) last_id: Mapped[int] = mapped_column(BigInteger) partial: Mapped[bool] = mapped_column(Boolean, default=False) # copying | stopped | incomplete | copied | old_deleted | copies_deleted status: Mapped[str] = mapped_column(String(16), default="copying") created_by: Mapped[int] = mapped_column(BigInteger, default=0) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class MigrationItem(Base): __tablename__ = "migration_items"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) migration_id: Mapped[str] = mapped_column(String(32), ForeignKey("migrations.id"), index=True) old_id: Mapped[int] = mapped_column(BigInteger) new_id: Mapped[int] = mapped_column(BigInteger) old_deleted: Mapped[bool] = mapped_column(Boolean, default=False) new_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
class Shift(Base): """One /shift run: posts of a source channel copied into another channel (so it can be continued or undone)."""
__tablename__ = "shifts"
id: Mapped[str] = mapped_column(String(32), primary_key=True) src_channel_id: Mapped[int] = mapped_column(BigInteger, index=True) src_access_hash: Mapped[int] = mapped_column(BigInteger, default=0) src_title: Mapped[str] = mapped_column(String(256), default="") src_username: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) dst_channel_id: Mapped[int] = mapped_column(BigInteger, index=True) first_id: Mapped[int] = mapped_column(BigInteger) last_id: Mapped[int] = mapped_column(BigInteger) # copying | stopped | incomplete | copied | copies_deleted status: Mapped[str] = mapped_column(String(16), default="copying") created_by: Mapped[int] = mapped_column(BigInteger, default=0) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class ShiftItem(Base): __tablename__ = "shift_items"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) shift_id: Mapped[str] = mapped_column(String(32), ForeignKey("shifts.id"), index=True) old_id: Mapped[int] = mapped_column(BigInteger) # message id in the source channel new_id: Mapped[int] = mapped_column(BigInteger) # message id of the copy in the destination channel new_deleted: Mapped[bool] = mapped_column(Boolean, default=False)
class ScheduledDelete(Base): """A channel message the bot has to delete at a given time (a broadcast with an expiry)."""
__tablename__ = "scheduled_deletes"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) channel_id: Mapped[int] = mapped_column(BigInteger, index=True) message_id: Mapped[int] = mapped_column(BigInteger) delete_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True) group_id: Mapped[str] = mapped_column(String(32), default="") # the broadcast it belongs to status: Mapped[str] = mapped_column(String(12), default="pending") # pending | failed attempts: Mapped[int] = mapped_column(Integer, default=0) last_error: Mapped[Optional[str]] = mapped_column(String(160), nullable=True) created_by: Mapped[int] = mapped_column(BigInteger, default=0) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class ChannelSync(Base): """Where the last look at a channel stopped, so the next one only has to read what is new."""
__tablename__ = "channel_sync"
channel_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False) last_top: Mapped[int] = mapped_column(BigInteger, default=0) # the newest message id that existed then last_pts: Mapped[int] = mapped_column(BigInteger, default=0) # the channel's event counter then deferred: Mapped[int] = mapped_column(Integer, default=0) # new messages left for the next look (too fresh then) last_run: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) last_deep: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True) # last look at every id
class ChannelHistory(Base): """How far the older posts of a channel (the ones sent before the bot was there) have been read into My posts."""
__tablename__ = "channel_history"
channel_id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=False) top: Mapped[int] = mapped_column(BigInteger, default=0) # the newest message id that counts as "older" next_id: Mapped[int] = mapped_column(BigInteger, default=1) # where the reading goes on imported: Mapped[int] = mapped_column(Integer, default=0) # older posts added to My posts so far done: Mapped[bool] = mapped_column(Boolean, default=False) started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
class IgnoredPost(Base): """A post the owner made the bot forget: it stays in the channel, but the sync never takes it over again."""
__tablename__ = "ignored_posts" __table_args__ = (UniqueConstraint("channel_id", "message_id", name="uq_ignored_channel_msg"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) channel_id: Mapped[int] = mapped_column(BigInteger, index=True) message_id: Mapped[int] = mapped_column(BigInteger) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class JobMark(Base): """A fact about a /repost or /shift run that has to outlive a restart, e.g. that links in other channels were pointed at its copies (so that Undo points them back), or which extras a shift was asked for."""
__tablename__ = "job_marks"
job_id: Mapped[str] = mapped_column(String(32), primary_key=True) mark: Mapped[str] = mapped_column(String(24), primary_key=True) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class Admin(Base): __tablename__ = "admins" user_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
def as_utc(dt: Optional[datetime]) -> Optional[datetime]: """A datetime from the database as an aware UTC one (SQLite hands back naive values).""" if dt is None: return None return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt.astimezone(timezone.utc)
def normalize_db_url(url: str) -> tuple: """Turn a plain DATABASE_URL into a SQLAlchemy async URL + connect args.""" connect_args: dict = {} if url.startswith("postgres://"): url = "postgresql://" + url[len("postgres://"):] if url.startswith("postgresql://"): url = "postgresql+asyncpg://" + url[len("postgresql://"):] if url.startswith("postgresql+asyncpg://"): parts = urlsplit(url) keep = [] for k, v in parse_qsl(parts.query, keep_blank_values=True): if k == "sslmode": if v in ("require", "verify-ca", "verify-full"): connect_args["ssl"] = True elif k in ("channel_binding", "options"): continue else: keep.append((k, v)) host = parts.hostname or "" if "-pooler" in host or "pgbouncer" in host: # PgBouncer in transaction mode does not support prepared statements connect_args["statement_cache_size"] = 0 keep.append(("prepared_statement_cache_size", "0")) url = urlunsplit(parts._replace(query=urlencode(keep))) elif url.startswith("sqlite:///"): url = "sqlite+aiosqlite:///" + url[len("sqlite:///"):] return url, connect_args
class Database: def __init__(self, url: str, pool: str = "null"): self.url, connect_args = normalize_db_url(url) kwargs: dict = {"connect_args": connect_args} if self.url.startswith("sqlite"): path = self.url.split(":///", 1)[-1] if path and path != ":memory:": os.makedirs(os.path.dirname(path) or ".", exist_ok=True) elif pool == "queue": kwargs.update(pool_size=5, max_overflow=5, pool_pre_ping=True, pool_recycle=1800) else: # short-lived connections: lets serverless Postgres (e.g. Neon) go to sleep when idle kwargs["poolclass"] = NullPool self.engine = create_async_engine(self.url, **kwargs) self.Session = async_sessionmaker(self.engine, expire_on_commit=False)
async def init(self, retries: int = 6) -> None: last: Optional[BaseException] = None for i in range(retries): try: async with self.engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) return except Exception as e: # cold start of serverless DBs can fail once last = e log.warning("database not ready (%s) - retry %s/%s", e, i + 1, retries) await asyncio.sleep(min(2 ** i, 15)) assert last is not None raise last
async def close(self) -> None: await self.engine.dispose()
async def list_admins(self) -> set[int]: async with self.Session() as s: return set((await s.execute(select(Admin.user_id))).scalars())
async def add_admin(self, uid: int) -> bool: async with self.Session() as s: if await s.get(Admin, uid) is not None: return False s.add(Admin(user_id=uid)) await s.commit() return True
async def remove_admin(self, uid: int) -> bool: async with self.Session() as s: row = await s.get(Admin, uid) if row is None: return False await s.delete(row) await s.commit() return True
# ------------------------------------------------------------------ channels async def list_channels(self, active_only: bool = True) -> list: async with self.Session() as s: q = select(Channel).order_by(Channel.title) if active_only: q = q.where(Channel.active.is_(True)) return list((await s.execute(q)).scalars())
async def get_channel(self, cid: int) -> Optional[Channel]: async with self.Session() as s: return await s.get(Channel, cid)
async def save_channel(self, cid: int, access_hash: int, title: str, username: Optional[str], added_by: int) -> Channel: async with self.Session() as s: ch = await s.get(Channel, cid) if ch is None: ch = Channel(id=cid, access_hash=access_hash, title=title, username=username, added_by=added_by, active=True) s.add(ch) else: ch.access_hash = access_hash or ch.access_hash ch.title = title or ch.title ch.username = username ch.active = True await s.commit() return ch
async def touch_channel_hash(self, cid: int, access_hash: int) -> None: async with self.Session() as s: ch = await s.get(Channel, cid) if ch is not None and access_hash and ch.access_hash != access_hash: ch.access_hash = access_hash await s.commit()
async def set_channel_active(self, cid: int, active: bool) -> None: async with self.Session() as s: ch = await s.get(Channel, cid) if ch is not None: ch.active = active await s.commit()
async def count_channel_posts(self, cid: int) -> int: """Every post of the channel in My posts - published ones and drafts.""" async with self.Session() as s: return int((await s.execute(select(func.count()).select_from(Post).where(Post.channel_id == cid))).scalar_one())
async def delete_channel_data(self, cid: int) -> int: """Everything My posts holds about a channel: its saved posts (published and drafts) and what the sync keeps about them - the posts forgotten on purpose, where the last look and the reading of the older posts stopped - so a channel that is added again starts from scratch. Nothing is touched in Telegram. The channel itself stays registered (switched off) because reposts and shifts that name it still need it, and so do timed deletions. Returns how many posts went.""" async with self.Session() as s: n = (await s.execute(select(func.count()).select_from(Post).where(Post.channel_id == cid))).scalar_one() await s.execute(delete(Post).where(Post.channel_id == cid)) for model in (IgnoredPost, ChannelSync, ChannelHistory): await s.execute(delete(model).where(model.channel_id == cid)) await s.commit() return int(n)
# --------------------------------------------------------------------- posts async def create_post(self, **fields: Any) -> Post: async with self.Session() as s: p = Post(**fields) s.add(p) await s.commit() return p
async def get_post(self, pid: int) -> Optional[Post]: async with self.Session() as s: return await s.get(Post, pid)
async def update_post(self, pid: int, **fields: Any) -> Optional[Post]: async with self.Session() as s: p = await s.get(Post, pid) if p is None: return None for k, v in fields.items(): setattr(p, k, v) p.updated_at = utcnow() await s.commit() return p
async def delete_post(self, pid: int) -> None: async with self.Session() as s: p = await s.get(Post, pid) if p is not None: await s.delete(p) await s.commit()
async def list_posts(self, channel_id: Optional[int], status: Optional[str], offset: int, limit: int) -> tuple: cond = [] if channel_id is not None: cond.append(Post.channel_id == channel_id) if status: cond.append(Post.status == status) async with self.Session() as s: total = (await s.execute(select(func.count()).select_from(Post).where(*cond))).scalar_one() q = ( select(Post) .where(*cond) .order_by(Post.status.asc(), desc(Post.message_id), desc(Post.id)) .offset(offset) .limit(limit) ) rows = list((await s.execute(q)).scalars()) return rows, total
async def latest_sent(self, channel_id: int, limit: int = 30) -> list: async with self.Session() as s: q = ( select(Post) .where(Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None)) .order_by(desc(Post.message_id)) .limit(limit) ) return list((await s.execute(q)).scalars())
async def sent_posts(self, channel_id: int) -> list: """Every published post of a channel, oldest first.""" async with self.Session() as s: q = ( select(Post) .where(Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None)) .order_by(Post.message_id) ) return list((await s.execute(q)).scalars())
async def sent_posts_from(self, channel_id: int, first_message_id: int) -> list: """Published posts of a channel from message id `first_message_id` on, oldest first.""" async with self.Session() as s: q = ( select(Post) .where( Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None), Post.message_id >= first_message_id, ) .order_by(Post.message_id, Post.id) ) return list((await s.execute(q)).scalars())
async def mine_message_ids(self, channel_id: int) -> set: async with self.Session() as s: q = select(Post.message_id).where( Post.channel_id == channel_id, Post.source == "bot", Post.message_id.is_not(None) ) return {r for r in (await s.execute(q)).scalars()}
async def find_by_message(self, channel_id: int, message_id: int) -> Optional[Post]: async with self.Session() as s: q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) return (await s.execute(q)).scalar_one_or_none()
async def forget_posts(self, channel_id: int, message_ids: list) -> int: """Remove the saved posts of these channel messages (they were deleted in the channel) and what hangs on them: a timed deletion that is not needed any more, a "forgotten on purpose" mark. Returns how many posts went.""" if not message_ids: return 0 ids = list(message_ids) async with self.Session() as s: rows = (await s.execute(select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(ids)))).scalars().all() for p in rows: await s.delete(p) for model in (ScheduledDelete, IgnoredPost): extra = await s.execute(select(model).where(model.channel_id == channel_id, model.message_id.in_(ids))) for r in extra.scalars().all(): await s.delete(r) await s.commit() return len(rows)
async def posts_at(self, channel_id: int, message_ids: list) -> list: """The published posts that sit at these message ids.""" if not message_ids: return [] async with self.Session() as s: q = select(Post).where( Post.channel_id == channel_id, Post.status == "sent", Post.message_id.in_(list(message_ids)) ) return list((await s.execute(q)).scalars())
async def release_slot(self, channel_id: int, message_id: int, keep_pid: Optional[int] = None) -> int: """Drop any other saved post at this message id (the sync may have picked the message up a moment earlier).""" async with self.Session() as s: q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) if keep_pid is not None: q = q.where(Post.id != keep_pid) rows = list((await s.execute(q)).scalars()) for p in rows: await s.delete(p) if rows: await s.commit() return len(rows)
async def _drop_slots(self, s, channel_id: int, message_ids: list) -> None: """Inside a transaction: remove saved posts at these ids, so the posts about to be saved can take their place.""" q = select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(list(message_ids))) rows = list((await s.execute(q)).scalars()) for p in rows: await s.delete(p) if rows: await s.flush()
# ------------------------------------------------------- what happens outside the bot async def get_sync(self, channel_id: int) -> Optional[ChannelSync]: async with self.Session() as s: return await s.get(ChannelSync, channel_id)
async def max_saved_id(self, channel_id: int) -> int: """The newest message id among the channel's published posts (0 if there is none).""" async with self.Session() as s: q = select(func.max(Post.message_id)).where( Post.channel_id == channel_id, Post.status == "sent", Post.message_id.is_not(None) ) return int((await s.execute(q)).scalar_one_or_none() or 0)
async def save_sync( self, channel_id: int, *, last_top: int, last_pts: int, deferred: int = 0, deep: bool = False ) -> None: async with self.Session() as s: row = await s.get(ChannelSync, channel_id) if row is None: row = ChannelSync(channel_id=channel_id) s.add(row) now = utcnow() row.last_top, row.last_pts, row.deferred, row.last_run = last_top, last_pts, deferred, now if deep: row.last_deep = now await s.commit()
async def adopt_message(self, channel_id: int, message_id: int, fields: dict, sent_at: Optional[datetime] = None) -> tuple: """Save a post somebody else made in the channel. Returns (post, True), or (None, False) when the bot already has a post at that message id (also when another task saved it a moment ago).""" async with self.Session() as s: q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) if (await s.execute(q)).scalar_one_or_none() is not None: return None, False p = Post(channel_id=channel_id, message_id=message_id, status="sent", source="adopted", created_by=0, sent_at=sent_at or utcnow(), **fields) s.add(p) try: await s.commit() except IntegrityError: await s.rollback() return None, False return p, True
async def adopt_many(self, channel_id: int, items: list) -> list: """items: [(message id, post fields, sent_at)] - save the posts somebody else made, many at once. Returns the message ids that were new (the bot already had a post at the others).""" if not items: return [] ids = [i[0] for i in items] async with self.Session() as s: have = set( (await s.execute(select(Post.message_id).where(Post.channel_id == channel_id, Post.message_id.in_(ids)))).scalars() ) fresh = [i for i in items if i[0] not in have] if not fresh: return [] s.add_all( [ Post(channel_id=channel_id, message_id=mid, status="sent", source="adopted", created_by=0, sent_at=at or utcnow(), **fields) for mid, fields, at in fresh ] ) try: await s.commit() return [i[0] for i in fresh] except IntegrityError: # somebody saved one of them a moment ago: one by one then await s.rollback() made = [] for mid, fields, at in fresh: _, created = await self.adopt_message(channel_id, mid, fields, sent_at=at) if created: made.append(mid) return made
# ------------------------------------------------------------- the channel's older posts async def get_history(self, channel_id: int) -> Optional[ChannelHistory]: async with self.Session() as s: return await s.get(ChannelHistory, channel_id)
async def start_history(self, channel_id: int, top: int) -> ChannelHistory: """Note that the older posts of a channel (message ids 1 to `top`) are to be read in. Does nothing when that has begun already.""" async with self.Session() as s: row = await s.get(ChannelHistory, channel_id) if row is not None: return row row = ChannelHistory(channel_id=channel_id, top=max(0, top), next_id=1, imported=0) if top < 1: # an empty channel: nothing to read row.done, row.finished_at = True, utcnow() s.add(row) try: await s.commit() except IntegrityError: await s.rollback() row = await s.get(ChannelHistory, channel_id) return row
async def save_history(self, channel_id: int, *, next_id: int, imported: int = 0, done: bool = False) -> None: async with self.Session() as s: row = await s.get(ChannelHistory, channel_id) if row is None: return row.next_id = max(row.next_id, next_id) row.imported += imported if done and not row.done: row.done, row.finished_at = True, utcnow() await s.commit()
async def reset_history(self, channel_id: int) -> None: """Read the channel's older posts again at the next look (the posts the bot already has are skipped).""" async with self.Session() as s: row = await s.get(ChannelHistory, channel_id) if row is not None: await s.delete(row) await s.commit()
# ------------------------------------------------------------ posts forgotten on purpose async def ignore_post(self, channel_id: int, message_id: int) -> None: async with self.Session() as s: q = select(IgnoredPost).where(IgnoredPost.channel_id == channel_id, IgnoredPost.message_id == message_id) if (await s.execute(q)).scalar_one_or_none() is not None: return s.add(IgnoredPost(channel_id=channel_id, message_id=message_id)) try: await s.commit() except IntegrityError: await s.rollback()
async def ignored_ids(self, channel_id: int) -> set: async with self.Session() as s: q = select(IgnoredPost.message_id).where(IgnoredPost.channel_id == channel_id) return {int(r) for r in (await s.execute(q)).scalars()}
# ------------------------------------------------------------ facts about a repost / shift run async def set_mark(self, job_id: str, mark: str) -> None: async with self.Session() as s: if await s.get(JobMark, (job_id, mark)) is not None: return s.add(JobMark(job_id=job_id, mark=mark)) try: await s.commit() except IntegrityError: await s.rollback()
async def has_mark(self, job_id: str, mark: str) -> bool: async with self.Session() as s: return await s.get(JobMark, (job_id, mark)) is not None
async def marks_of(self, job_id: str) -> set: async with self.Session() as s: q = select(JobMark.mark).where(JobMark.job_id == job_id) return set((await s.execute(q)).scalars())
async def sync_update_post(self, pid: int, expected: Optional[datetime], fields: dict) -> bool: """Save what the channel shows - but only if the saved post is still exactly as it was when it was read (`expected` is its updated_at then), so a change made through the bot meanwhile is never overwritten.""" async with self.Session() as s: res = await s.execute( update(Post).where(Post.id == pid, Post.updated_at == expected).values(**fields, updated_at=utcnow()) ) await s.commit() return bool(res.rowcount)
# ------------------------------------------------------------ timed deletions async def schedule_deletes(self, rows: list) -> None: """rows: dicts with channel_id, message_id, delete_at, group_id, created_by.""" if not rows: return async with self.Session() as s: s.add_all([ScheduledDelete(**r) for r in rows]) await s.commit()
async def due_deletes(self, now: datetime, limit: int = 500) -> list: async with self.Session() as s: q = ( select(ScheduledDelete) .where(ScheduledDelete.status == "pending", ScheduledDelete.delete_at <= now) .order_by(ScheduledDelete.delete_at, ScheduledDelete.id) .limit(limit) ) return list((await s.execute(q)).scalars())
async def next_delete_at(self) -> Optional[datetime]: async with self.Session() as s: q = select(func.min(ScheduledDelete.delete_at)).where(ScheduledDelete.status == "pending") return as_utc((await s.execute(q)).scalar_one_or_none())
async def pending_deletes(self, group_id: Optional[str] = None, status: str = "pending") -> list: async with self.Session() as s: q = select(ScheduledDelete).where(ScheduledDelete.status == status).order_by(ScheduledDelete.id) if group_id: q = q.where(ScheduledDelete.group_id == group_id) return list((await s.execute(q)).scalars())
async def finish_deletes(self, ids: list) -> None: if not ids: return async with self.Session() as s: for row in (await s.execute(select(ScheduledDelete).where(ScheduledDelete.id.in_(list(ids))))).scalars(): await s.delete(row) await s.commit()
async def retry_delete(self, sid: int, *, at: datetime, error: str) -> None: async with self.Session() as s: row = await s.get(ScheduledDelete, sid) if row is not None: row.attempts += 1 row.delete_at = at row.last_error = error[:160] await s.commit()
async def fail_delete(self, sid: int, error: str) -> None: async with self.Session() as s: row = await s.get(ScheduledDelete, sid) if row is not None: row.attempts += 1 row.status = "failed" row.last_error = error[:160] await s.commit()
# ------------------------------------------------------------- replace history async def create_batch(self, batch_id: str, old: str, new: str, user_id: int) -> None: async with self.Session() as s: s.add(Batch(id=batch_id, old_username=old, new_username=new, created_by=user_id)) await s.commit()
async def _adopt(self, s, channel_id: int, message_id: int, fields: dict, user_id: int) -> None: q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) p = (await s.execute(q)).scalar_one_or_none() if p is not None: for k, v in fields.items(): setattr(p, k, v) p.updated_at = utcnow() else: s.add( Post( channel_id=channel_id, message_id=message_id, status="sent", source="adopted", created_by=user_id, sent_at=utcnow(), **fields, ) )
async def record_changes(self, batch_id: str, channel_id: int, records: list, user_id: int) -> None: """records: [{message_id, old_state, new_state, adopt: {post fields}}]""" if not records: return async with self.Session() as s: for r in records: s.add( Change( batch_id=batch_id, channel_id=channel_id, message_id=r["message_id"], old_state=r["old_state"], new_state=r["new_state"], ) ) await self._adopt(s, channel_id, r["message_id"], r["adopt"], user_id) await s.commit()
async def last_batch(self) -> Optional[Batch]: async with self.Session() as s: q = select(Batch).where(Batch.undone.is_(False)).order_by(desc(Batch.created_at)).limit(1) return (await s.execute(q)).scalar_one_or_none()
async def get_batch(self, batch_id: str) -> Optional[Batch]: async with self.Session() as s: return await s.get(Batch, batch_id)
async def batch_changes(self, batch_id: str) -> list: async with self.Session() as s: q = select(Change).where(Change.batch_id == batch_id, Change.reverted.is_(False)).order_by(Change.id) return list((await s.execute(q)).scalars())
async def count_batch_changes(self, batch_id: str) -> int: async with self.Session() as s: q = select(func.count()).select_from(Change).where(Change.batch_id == batch_id, Change.reverted.is_(False)) return (await s.execute(q)).scalar_one()
async def finish_undo(self, batch_id: str, change_ids: list, restored: list, all_done: bool) -> None: """restored: [(channel_id, message_id, state)] -> refresh the saved post copies.""" async with self.Session() as s: for cid in change_ids: c = await s.get(Change, cid) if c is not None: c.reverted = True for channel_id, message_id, state in restored: q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) p = (await s.execute(q)).scalar_one_or_none() if p is not None: if not state.get("rich"): # a rich message's text was never changed: it stays as saved p.text = state.get("text", "") p.entities = state.get("entities", []) p.buttons = state.get("buttons", []) p.updated_at = utcnow() if all_done: b = await s.get(Batch, batch_id) if b is not None: b.undone = True await s.commit()
# ------------------------------------------------------------------ /repost OPEN_STATES = ("copying", "stopped", "incomplete", "copied")
async def create_migration(self, mid: str, channel_id: int, *, old, new, include_typed: bool, include_posts: bool, first_id: int, last_id: int, partial: bool, user_id: int) -> None: async with self.Session() as s: s.add(Migration(id=mid, channel_id=channel_id, old_username=old, new_username=new, include_typed=include_typed, include_posts=include_posts, first_id=first_id, last_id=last_id, partial=partial, created_by=user_id)) await s.commit()
async def get_migration(self, mid: str) -> Optional[Migration]: async with self.Session() as s: return await s.get(Migration, mid)
async def open_migration(self, channel_id: Optional[int] = None) -> Optional[Migration]: """The newest repost that is not finished yet (copies exist, old posts not deleted / copies not removed).""" async with self.Session() as s: q = select(Migration).where(Migration.status.in_(self.OPEN_STATES)) if channel_id is not None: q = q.where(Migration.channel_id == channel_id) q = q.order_by(desc(Migration.created_at)).limit(1) return (await s.execute(q)).scalar_one_or_none()
async def set_migration_status(self, mid: str, status: str) -> None: async with self.Session() as s: m = await s.get(Migration, mid) if m is not None: m.status = status await s.commit()
async def migration_done_old_ids(self, mid: str) -> set: async with self.Session() as s: q = select(MigrationItem.old_id).where(MigrationItem.migration_id == mid) return set((await s.execute(q)).scalars())
async def record_repost(self, mid: str, channel_id: int, rows: list, user_id: int) -> None: """rows: [{old_id, new_id, post: {Post fields}}] - saves the mapping and registers the new posts.""" if not rows: return async with self.Session() as s: await self._drop_slots(s, channel_id, [r["new_id"] for r in rows]) for r in rows: s.add(MigrationItem(migration_id=mid, old_id=r["old_id"], new_id=r["new_id"])) s.add(Post(channel_id=channel_id, message_id=r["new_id"], status="sent", source="bot", created_by=user_id, sent_at=utcnow(), **r["post"])) await s.commit()
async def migration_pairs( self, mid: Optional[str] = None, channel_id: Optional[int] = None, alive_only: bool = True ) -> list: """[(old id, new id)] of the copies of one repost (`mid`) or of every repost of a channel, oldest repost first. alive_only: leave out copies that were removed again (undo).""" async with self.Session() as s: q = select(MigrationItem.old_id, MigrationItem.new_id).join(Migration, Migration.id == MigrationItem.migration_id) if mid is not None: q = q.where(MigrationItem.migration_id == mid) if channel_id is not None: q = q.where(Migration.channel_id == channel_id) if alive_only: q = q.where(MigrationItem.new_deleted.is_(False)) q = q.order_by(Migration.created_at, MigrationItem.id) return [(a, b) for a, b in (await s.execute(q)).all()]
async def update_post_by_message(self, channel_id: int, message_id: int, **fields: Any) -> Optional[Post]: """Change the saved copy of the post that sits at `message_id` (None if the bot does not know that post).""" async with self.Session() as s: q = select(Post).where(Post.channel_id == channel_id, Post.message_id == message_id) p = (await s.execute(q)).scalar_one_or_none() if p is None: return None for k, v in fields.items(): setattr(p, k, v) p.updated_at = utcnow() await s.commit() return p
async def migration_pending_ids(self, mid: str, which: str, limit: int = 100) -> list: col, flag = (MigrationItem.old_id, MigrationItem.old_deleted) if which == "old" else (MigrationItem.new_id, MigrationItem.new_deleted) async with self.Session() as s: q = select(col).where(MigrationItem.migration_id == mid, flag.is_(False)).order_by(col).limit(limit) return list((await s.execute(q)).scalars())
async def mark_migration_deleted(self, mid: str, channel_id: int, which: str, ids: list) -> None: """The messages are gone from Telegram: flag them and drop their saved post copies.""" if not ids: return col, flag = ("old_id", "old_deleted") if which == "old" else ("new_id", "new_deleted") async with self.Session() as s: q = select(MigrationItem).where(MigrationItem.migration_id == mid, getattr(MigrationItem, col).in_(ids)) for it in (await s.execute(q)).scalars(): setattr(it, flag, True) pq = select(Post).where(Post.channel_id == channel_id, Post.message_id.in_(ids)) for p in (await s.execute(pq)).scalars(): await s.delete(p) await s.commit()
async def migration_counts(self, mid: str) -> dict: async with self.Session() as s: total = (await s.execute(select(func.count()).select_from(MigrationItem).where(MigrationItem.migration_id == mid))).scalar_one() old_left = (await s.execute(select(func.count()).select_from(MigrationItem).where( MigrationItem.migration_id == mid, MigrationItem.old_deleted.is_(False)))).scalar_one() new_left = (await s.execute(select(func.count()).select_from(MigrationItem).where( MigrationItem.migration_id == mid, MigrationItem.new_deleted.is_(False)))).scalar_one() lo = (await s.execute(select(func.min(MigrationItem.new_id)).where(MigrationItem.migration_id == mid))).scalar_one() hi = (await s.execute(select(func.max(MigrationItem.new_id)).where(MigrationItem.migration_id == mid))).scalar_one() return {"copied": total, "old_left": old_left, "new_left": new_left, "first_new": lo, "last_new": hi}
# ------------------------------------------------------------------- /shift SHIFT_OPEN = ("copying", "stopped", "incomplete")
async def create_shift(self, sid: str, *, src, dst_channel_id: int, first_id: int, last_id: int, user_id: int) -> None: """`src`: any object with id, access_hash, title and username (the source channel need not be registered).""" async with self.Session() as s: s.add(Shift(id=sid, src_channel_id=src.id, src_access_hash=src.access_hash or 0, src_title=src.title or "", src_username=src.username, dst_channel_id=dst_channel_id, first_id=first_id, last_id=last_id, created_by=user_id)) await s.commit()
async def get_shift(self, sid: str) -> Optional[Shift]: async with self.Session() as s: return await s.get(Shift, sid)
async def open_shift(self, src_id: Optional[int] = None, dst_id: Optional[int] = None) -> Optional[Shift]: """The newest shift that is not finished (still copying, stopped, or incomplete).""" async with self.Session() as s: q = select(Shift).where(Shift.status.in_(self.SHIFT_OPEN)) if src_id is not None: q = q.where(Shift.src_channel_id == src_id) if dst_id is not None: q = q.where(Shift.dst_channel_id == dst_id) return (await s.execute(q.order_by(desc(Shift.created_at)).limit(1))).scalar_one_or_none()
async def last_finished_shift(self) -> Optional[Shift]: """The newest finished shift that still has copies in its destination - so its Undo can be offered again.""" async with self.Session() as s: alive = select(ShiftItem.id).where(ShiftItem.shift_id == Shift.id, ShiftItem.new_deleted.is_(False)).exists() q = select(Shift).where(Shift.status == "copied", alive).order_by(desc(Shift.created_at)).limit(1) return (await s.execute(q)).scalar_one_or_none()
async def set_shift_status(self, sid: str, status: str) -> None: async with self.Session() as s: sh = await s.get(Shift, sid) if sh is not None: sh.status = status await s.commit()
async def shift_done_ids(self, sid: str) -> set: async with self.Session() as s: q = select(ShiftItem.old_id).where(ShiftItem.shift_id == sid) return set((await s.execute(q)).scalars())
async def shift_pairs(self, sid: str, alive_only: bool = True) -> list: """[(source id, id of the copy)] of one shift, in copy order.""" async with self.Session() as s: q = select(ShiftItem.old_id, ShiftItem.new_id).where(ShiftItem.shift_id == sid) if alive_only: q = q.where(ShiftItem.new_deleted.is_(False)) return [(a, b) for a, b in (await s.execute(q.order_by(ShiftItem.id))).all()]
async def shifted_ids(self, src_id: int, dst_id: int, first: int, last: int) -> set: """Source ids in first..last that already have a live copy in `dst_id` from an earlier shift.""" async with self.Session() as s: q = ( select(ShiftItem.old_id) .join(Shift, Shift.id == ShiftItem.shift_id) .where(Shift.src_channel_id == src_id, Shift.dst_channel_id == dst_id, ShiftItem.new_deleted.is_(False), ShiftItem.old_id >= first, ShiftItem.old_id <= last) ) return set((await s.execute(q)).scalars())
async def record_shift(self, sid: str, dst_channel_id: int, rows: list, user_id: int) -> None: """rows: [{old_id, new_id, post: {Post fields}}] - saves the mapping and registers the copies in My posts.""" if not rows: return async with self.Session() as s: await self._drop_slots(s, dst_channel_id, [r["new_id"] for r in rows]) for r in rows: s.add(ShiftItem(shift_id=sid, old_id=r["old_id"], new_id=r["new_id"])) s.add(Post(channel_id=dst_channel_id, message_id=r["new_id"], status="sent", source="bot", created_by=user_id, sent_at=utcnow(), **r["post"])) await s.commit()
async def shift_counts(self, sid: str) -> dict: async with self.Session() as s: base = ShiftItem.shift_id == sid total = (await s.execute(select(func.count()).select_from(ShiftItem).where(base))).scalar_one() left = (await s.execute(select(func.count()).select_from(ShiftItem).where(base, ShiftItem.new_deleted.is_(False)))).scalar_one() lo = (await s.execute(select(func.min(ShiftItem.new_id)).where(base))).scalar_one() hi = (await s.execute(select(func.max(ShiftItem.new_id)).where(base))).scalar_one() return {"copied": total, "new_left": left, "first_new": lo, "last_new": hi}
async def shift_pending_new(self, sid: str, limit: int = 100) -> list: async with self.Session() as s: q = select(ShiftItem.new_id).where(ShiftItem.shift_id == sid, ShiftItem.new_deleted.is_(False)).order_by(ShiftItem.new_id).limit(limit) return list((await s.execute(q)).scalars())
async def mark_shift_deleted(self, sid: str, dst_channel_id: int, ids: list) -> None: """The copies are gone from Telegram: flag them and drop their saved posts.""" if not ids: return async with self.Session() as s: q = select(ShiftItem).where(ShiftItem.shift_id == sid, ShiftItem.new_id.in_(ids)) for it in (await s.execute(q)).scalars(): it.new_deleted = True pq = select(Post).where(Post.channel_id == dst_channel_id, Post.message_id.in_(ids)) for p in (await s.execute(pq)).scalars(): await s.delete(p) await s.commit()
# -------------------------------------------------------------------- export async def export_all(self) -> dict: def clean(d: dict) -> dict: return {k: (v.isoformat() if isinstance(v, datetime) else v) for k, v in d.items()}
async with self.Session() as s: chans = list((await s.execute(select(Channel))).scalars()) posts = list((await s.execute(select(Post).order_by(Post.id))).scalars()) marks = (await s.execute(select(IgnoredPost.channel_id, IgnoredPost.message_id).order_by(IgnoredPost.id))).all() return { "exported_at": utcnow().isoformat(), "channels": [ clean({c.name: getattr(ch, c.name) for c in ch.__table__.columns}) for ch in chans ], "posts": [clean(p.as_dict()) for p in posts], "ignored": [{"channel_id": int(c), "message_id": int(m)} for c, m in marks], # posts forgotten on purpose }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300"""Send errors to a Telegram chat (ERROR_LOG_CHAT_ID) as a `python` code block.
What is reported: * every log record of level ERROR or higher that carries a message / traceback (handler failures included), * exceptions nobody caught in background tasks ("Unhandled exception in background task <unnamed>:"), * a crash of the whole bot (sent right before it exits).Long tracebacks are cut into several messages, never shortened. Secrets (bot token, API hash, session texts,database password) are replaced by *** before anything leaves the bot. The reporter never raises, never blocks thebot, and protects the chat from floods (identical reports are merged, at most a few per minute)."""from __future__ import annotations
import asyncioimport hashlibimport loggingimport reimport timeimport tracebackfrom collections import dequefrom typing import Optional
from telethon import types
from .tgutil import utf16_len
log = logging.getLogger(__name__)
PART_LIMIT = 3800 # characters per message (Telegram allows 4096; the rest is head-room for the part label)PIECE = 1500 # a single line longer than a message is cut into pieces of this sizeMUTE_SECONDS = 600 # after "can't write to the log chat" stay quiet this longMIN_SECRET = 6 # shorter secrets are not redacted (they would mangle ordinary text)
# ----------------------------------------------------------------------------- text helpersdef split_report(text: str, limit: int = PART_LIMIT) -> list: """Cut a report into messages of at most `limit` characters at line breaks. Nothing is dropped.""" if len(text) <= limit: return [text] room = limit - 40 # space for the "(part 3/12)" label pieces: list = [] for line in text.split("\n"): while len(line) > room: # a single huge line: cut it size = min(PIECE, room) pieces.append(line[:size]) line = line[size:] pieces.append(line) parts: list = [] cur: list = [] # the lines of the part being built used = 0 for piece in pieces: add = len(piece) + (1 if cur else 0) if cur and used + add > room: parts.append("\n".join(cur)) cur, used = [piece], len(piece) else: cur.append(piece) used += add if cur: parts.append("\n".join(cur)) n = len(parts) return [f"(part {i}/{n})\n{p}" for i, p in enumerate(parts, 1)]
def redact(text: str, secrets) -> str: for s in sorted({s for s in secrets if s and len(s) >= MIN_SECRET}, key=len, reverse=True): text = text.replace(s, "***") return text
def format_exception(exc: BaseException) -> str: return "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
def _task_label(task) -> str: name = getattr(task, "get_name", lambda: "")() if task is not None else "" if not name or re.fullmatch(r"Task-\d+", name): return "<unnamed>" return name
# ---------------------------------------------------------------------------------- reporterclass ErrorReporter: def __init__( self, client, chat_id: Optional[int], *, bot_token: str = "", secrets=(), per_minute: int = 12, dedupe_seconds: float = 60.0, gap: float = 1.0, part_gap: float = 0.6, ): self.client = client self.chat_id = chat_id self.bot_token = bot_token self.secrets = [s for s in (*secrets, bot_token) if s] # the login token is always hidden too self.per_minute = per_minute self.dedupe_seconds = dedupe_seconds self.gap = gap self.part_gap = part_gap self._loop: Optional[asyncio.AbstractEventLoop] = None self._queue: Optional[asyncio.Queue] = None self._task: Optional[asyncio.Task] = None self._peer = None self._muted_until = 0.0 self._recent: dict = {} # report key -> [time of the first, number suppressed since] self._times: deque = deque() # when reports were accepted (for the per-minute limit) self._skipped = 0 # reports dropped by the limit since the last one that went out
@property def enabled(self) -> bool: return bool(self.chat_id)
# ------------------------------------------------------------------ life cycle def start(self) -> None: if not self.enabled or self._task is not None: return self._loop = asyncio.get_running_loop() self._queue = asyncio.Queue(maxsize=100) self._task = self._loop.create_task(self._worker(), name="error-reporter")
async def stop(self, wait: float = 5.0) -> None: """Let queued reports go out (for a few seconds at most), then stop.""" task, self._task = self._task, None if task is None: return try: await asyncio.wait_for(self._queue.join(), wait) except Exception: pass task.cancel() try: await task except BaseException: pass
# ---------------------------------------------------------------------- input def submit(self, title: str, tb: str = "") -> None: """Queue a report. Safe to call from any thread; never raises.""" try: loop = self._loop if not self.enabled or loop is None or loop.is_closed(): return try: here = asyncio.get_running_loop() except RuntimeError: here = None if here is loop: self._enqueue(title, tb) else: loop.call_soon_threadsafe(self._enqueue, title, tb) except Exception: pass
def _enqueue(self, title: str, tb: str) -> None: try: now = time.monotonic() if now < self._muted_until or self._queue is None: return last_line = next((ln for ln in reversed(tb.splitlines()) if ln.strip()), "") key = hashlib.sha1(f"{title}|{last_line}".encode("utf-8", "replace")).hexdigest() prev = self._recent.get(key) merged = 0 if prev is not None: if now - prev[0] < self.dedupe_seconds: prev[1] += 1 # same error again: counted, reported with the next one return merged = prev[1] self._recent[key] = [now, 0] if len(self._recent) > 200: for k in sorted(self._recent, key=lambda k: self._recent[k][0])[:100]: self._recent.pop(k, None) while self._times and now - self._times[0] > 60: self._times.popleft() if len(self._times) >= self.per_minute: self._skipped += 1 return self._times.append(now) skipped, self._skipped = self._skipped, 0 try: self._queue.put_nowait((title, tb, merged, skipped)) except asyncio.QueueFull: self._skipped += 1 + skipped except Exception: pass
def loop_exception_handler(self, loop, context) -> None: """asyncio calls this for exceptions nobody retrieved (set it with loop.set_exception_handler).""" try: exc = context.get("exception") task = context.get("task") or context.get("future") if task is not None and exc is not None: title = f"Unhandled exception in background task {_task_label(task)}:" else: title = (context.get("message") or "Unhandled error in the event loop") + ":" tb = format_exception(exc) if exc is not None else "" self.submit(title, tb) except Exception: pass finally: loop.default_exception_handler(context) # keep the normal log line too
# --------------------------------------------------------------------- output async def _worker(self) -> None: assert self._queue is not None while True: item = await self._queue.get() try: await self._deliver(*item) except asyncio.CancelledError: raise except Exception as e: name = type(e).__name__ log.warning("could not write to the error log chat: %s %s", name, str(e)[:150]) if isinstance(e, (ValueError, PermissionError)) or "Forbidden" in name or "Private" in name: # the bot is not a member of that chat (or may not write there): stop trying for a while self._muted_until = time.monotonic() + MUTE_SECONDS self._peer = None finally: self._queue.task_done() await asyncio.sleep(self.gap)
async def _deliver(self, title: str, tb: str, merged: int = 0, skipped: int = 0) -> None: if self._peer is None: self._peer = await self.client.get_input_entity(self.chat_id) text = title + (("\n\n" + tb.rstrip("\n")) if tb else "") notes = [] if merged: notes.append(f"(+{merged} identical report(s) suppressed)") if skipped: notes.append(f"({skipped} report(s) were skipped because too many errors came in)") if notes: text += "\n\n" + "\n".join(notes) text = redact(text, self.secrets) parts = split_report(text) for i, part in enumerate(parts): await self.client.send_message( self._peer, part, formatting_entities=[types.MessageEntityPre(0, utf16_len(part), "python")], link_preview=False, ) if i < len(parts) - 1: await asyncio.sleep(self.part_gap)
async def check(self) -> Optional[str]: """None when the log chat can be reached, otherwise a short reason (used once at start-up).""" if not self.enabled: return None try: self._peer = await self.client.get_input_entity(self.chat_id) return None except Exception as e: return ( f"{type(e).__name__}: {str(e)[:120]} - add the bot to that chat " "(as a member, or as an admin who may post)" )
async def report_fatal(self, title: str, exc: BaseException) -> None: """The bot is going down: send the crash straight away (the queue may not get the time).""" if not self.enabled: return try:
async def go() -> None: if not self.client.is_connected(): await self.client.connect() if self.bot_token and not await self.client.is_user_authorized(): await self.client.sign_in(bot_token=self.bot_token) await self._deliver(title + ":", format_exception(exc))
await asyncio.wait_for(go(), 20) except Exception as e: log.warning("could not send the crash report: %s %s", type(e).__name__, str(e)[:150])
# ------------------------------------------------------------------------------ loggingclass TelegramLogHandler(logging.Handler): """Forwards log records (ERROR and up) to the reporter."""
def __init__(self, reporter: ErrorReporter, level: int = logging.ERROR): super().__init__(level) self.reporter = reporter
def emit(self, record: logging.LogRecord) -> None: try: if record.name.startswith("app.errorlog") or record.name == "asyncio": return # our own messages would loop; asyncio's go through loop_exception_handler title = record.getMessage() tb = "" if record.exc_info and record.exc_info[0] is not None: tb = "".join(traceback.format_exception(*record.exc_info)) title += ":" if not record.name.startswith(("app", "bot", "__main__")): title = f"[{record.name}] {title}" self.reporter.submit(title, tb) except Exception: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208"""Timed deletion: a broadcast with an expiry ("/broadcast 1h") is removed from every channel - and from My posts -when its time is up.
The deletions are saved in the database (table scheduled_deletes), so a restart loses nothing: posts that came due whilethe bot was off are deleted as soon as it is back. The Expirer wakes up only when something is due; it does not poll thedatabase, so a sleeping serverless database stays asleep."""from __future__ import annotations
import asyncioimport loggingimport refrom datetime import datetime, timedeltafrom typing import Optional
from .db import as_utc, utcnowfrom .repost_engine import delete_batchfrom .tgutil import esc, peer_of
log = logging.getLogger(__name__)
MIN_SECONDS = 60MAX_SECONDS = 366 * 86400MAX_ATTEMPTS = 5RETRY_AFTER = 600 # seconds between attempts, times the attempt numberLOCK_WAIT = 60 # a long job (repost...) is running: look again in a minute
_UNITS = { "m": 60, "min": 60, "mins": 60, "minute": 60, "minutes": 60, "h": 3600, "hr": 3600, "hrs": 3600, "hour": 3600, "hours": 3600, "d": 86400, "day": 86400, "days": 86400, "w": 604800, "week": 604800, "weeks": 604800,} # fmt: skip_PART = re.compile(r"(\d+)\s*([a-z]+)")DURATION_HELP = "Use minutes, hours or days: 50m, 1h, 5d (or 1d12h). Leave the time out to keep the message forever."
def parse_duration(text: str) -> int: """'50m' -> 3000, '1h' -> 3600, '5d' -> 432000, '1d12h' -> 129600 (seconds). ValueError with a message if unusable.""" t = (text or "").strip().lower().replace(",", " ") if not t or not re.fullmatch(r"(?:\d+\s*[a-z]+\s*)+", t): raise ValueError(f"I can't read β{(text or '').strip()[:30]}β as a time. {DURATION_HELP}") total = 0 for n, unit in _PART.findall(t): if unit not in _UNITS: raise ValueError(f"β{n}{unit}β - I don't know the unit β{unit}β. {DURATION_HELP}") total += int(n) * _UNITS[unit] if total < MIN_SECONDS: raise ValueError("The shortest time is 1 minute.") if total > MAX_SECONDS: raise ValueError("The longest time is 1 year (365d).") return total
def human(seconds: int) -> str: """3000 -> '50 minutes', 3600 -> '1 hour', 129600 -> '1 day 12 hours'.""" seconds = int(seconds) days, rest = divmod(seconds, 86400) hours, rest = divmod(rest, 3600) minutes = rest // 60 parts = [] for n, word in ((days, "day"), (hours, "hour"), (minutes, "minute")): if n: parts.append(f"{n} {word}" + ("s" if n != 1 else "")) return " ".join(parts[:2]) or "under a minute"
def stamp(dt: datetime) -> str: return as_utc(dt).strftime("%d %b %Y, %H:%M UTC")
class Expirer: """Deletes scheduled messages when they come due. `start()` runs it in the background."""
def __init__(self, ctx, *, notify=None): self.ctx = ctx self._next: Optional[datetime] = None self._wake = asyncio.Event() self._task: Optional[asyncio.Task] = None self._notify = notify # async fn(user_id, text) used to tell someone a deletion failed for good
# ------------------------------------------------------------------------- running def start(self) -> None: if self._task is None: self._task = asyncio.create_task(self.run(), name="expirer")
async def stop(self) -> None: if self._task is not None: self._task.cancel() try: await self._task except (asyncio.CancelledError, Exception): pass self._task = None
def notify(self, when: datetime) -> None: """Something was scheduled for `when`: make sure the loop wakes up in time.""" when = as_utc(when) if self._next is None or when < self._next: self._next = when self._wake.set()
async def load(self) -> None: """The one look at the database (when the bot starts): when is the first deletion due?""" try: self._next = await self.ctx.db.next_delete_at() except Exception: log.exception("could not read the scheduled deletions")
async def run(self) -> None: await self.load() while True: delay = None if self._next is None else max(0.0, (self._next - utcnow()).total_seconds()) try: await asyncio.wait_for(self._wake.wait(), timeout=delay) except asyncio.TimeoutError: pass self._wake.clear() if self._next is not None and self._next <= utcnow(): try: await self.sweep() except asyncio.CancelledError: raise except Exception: log.exception("deleting scheduled messages failed") self._next = utcnow() + timedelta(seconds=RETRY_AFTER)
# --------------------------------------------------------------------------- work async def sweep(self, now: Optional[datetime] = None) -> dict: """Delete everything that is due at `now`. Returns {'deleted': n, 'retry': n, 'failed': n}.""" ctx, db = self.ctx, self.ctx.db now = now or utcnow() stats = {"deleted": 0, "retry": 0, "failed": 0, "waiting": False} due = await db.due_deletes(now) if due and ctx.lock.locked(): # a repost / shift is running: don't pull posts out from under it stats["waiting"] = True self._next = now + timedelta(seconds=LOCK_WAIT) return stats by_channel: dict = {} for row in due: by_channel.setdefault(row.channel_id, []).append(row) for cid, rows in by_channel.items(): await self._sweep_channel(cid, rows, now, stats) self._next = await db.next_delete_at() return stats
async def _sweep_channel(self, cid: int, rows: list, now: datetime, stats: dict) -> None: ctx, db = self.ctx, self.ctx.db ch = await db.get_channel(cid) if ch is None: for r in rows: await db.fail_delete(r.id, "the channel was removed from the bot") stats["failed"] += 1 return peer = peer_of(ch) ids = sorted({r.message_id for r in rows}) gone: set = set() error: Optional[str] = None try: for i in range(0, len(ids), 100): out = await delete_batch(ctx.client, peer, ids[i : i + 100], None) gone |= out.gone error = error or out.bot_error left = [m for m in ids if m not in gone] ub = getattr(ctx, "userbot", None) if left and ub is not None and ub.enabled: # the bot may not delete old posts: the userbot tries fallback, deleter = await ub.fallback_for(ch) try: if fallback is not None: for i in range(0, len(left), 100): out = await delete_batch(ctx.client, peer, left[i : i + 100], fallback) gone |= out.gone error = out.fallback_error or error finally: if deleter is not None: await deleter.close() except Exception as e: log.exception("deleting scheduled messages of channel %s failed", cid) error = type(e).__name__ done = [r for r in rows if r.message_id in gone] await db.finish_deletes([r.id for r in done]) await db.forget_posts(cid, sorted(gone)) stats["deleted"] += len(done) for r in rows: if r.message_id in gone: continue why = error or "Telegram did not delete it" if r.attempts + 1 >= MAX_ATTEMPTS: await db.fail_delete(r.id, why) stats["failed"] += 1 await self._tell(r, ch, why) else: await db.retry_delete(r.id, at=now + timedelta(seconds=RETRY_AFTER * (r.attempts + 1)), error=why) stats["retry"] += 1
async def _tell(self, row, ch, why: str) -> None: """A deletion failed for good: tell the person who sent the broadcast.""" text = ( f"β οΈ I could not delete the expired broadcast post {row.message_id} in <b>{esc(ch.title)}</b> " f"({esc(why)}). Delete it by hand, then use βOnly forget it in the botβ in /posts." ) try: if self._notify is not None: await self._notify(row.created_by, text) elif row.created_by: await self.ctx.client.send_message(row.created_by, text, link_preview=False) except Exception: log.warning("could not tell user %s about the failed deletion", row.created_by, exc_info=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"""/autopost <total> <interval>: post "Episodes 01 to 20", "Episodes 21 to 40", ... with a download button each,then ask for the real link of every button. Owners and admins."""from __future__ import annotations
import asyncioimport loggingimport reimport secretsimport timefrom dataclasses import dataclass, fieldfrom types import SimpleNamespace
from telethon import Button, errors
from .. import pickerfrom ..autopost import ( MAX_POSTS, PLACEHOLDER_LINK, USAGE, button_label, parse_autopost_args, plan_ranges, post_buttons, post_text, ranges_summary, title_of,)from ..common import ( Ctx, UserError, clear_state, cmd, discard_temp, edit_callback_message, guard, on_cb, purge_pending, say, send_post, show,)from ..db import utcnowfrom ..tgutil import esc, explain_rpc, flood_retry, get_rights, peer_offrom .masslinks import begin_queue
log = logging.getLogger(__name__)
@dataclassclass AutoChoice: """/autopost was typed with good numbers; the channel still has to be picked."""
user: int total: int interval: int ranges: list created: float = field(default_factory=time.monotonic)
@dataclassclass AutoResult: posts: list = field(default_factory=list) # the saved Post rows, in the order they were posted failure: str = "" # why it stopped before the end (empty = all posted)
async def post_series(ctx: Ctx, ch, ranges: list, user_id: int, *, delay: float = 1.0, progress=None) -> AutoResult: """Send one post per range to `ch` and save each in My posts. Stops at the first post Telegram refuses.""" res = AutoResult() for n, (a, b) in enumerate(ranges, 1): text, buttons = post_text(a, b), post_buttons(a, b) shape = SimpleNamespace(text=text, entities=[], buttons=buttons, media_file_id=None, link_preview=False) try: sent = await flood_retry(lambda: send_post(ctx.client, peer_of(ch), shape)) except errors.RPCError as e: res.failure = f"{title_of(a, b)}: {explain_rpc(e)}" break except Exception as e: log.exception("autopost: posting %s failed", title_of(a, b)) res.failure = f"{title_of(a, b)}: {type(e).__name__}" break res.posts.append( await ctx.db.create_post( channel_id=ch.id, message_id=sent.id, status="sent", source="bot", created_by=user_id, text=text, entities=[], buttons=buttons, link_preview=False, sent_at=utcnow(), ) ) if progress: await progress(n) if n < len(ranges): await asyncio.sleep(delay) return res
def register(ctx: Ctx) -> None: client, db, cfg = ctx.client, ctx.db, ctx.cfg
@client.on(cmd("autopost", args=True)) @guard(ctx) async def h_autopost(event): purge_pending(ctx) raw = (event.pattern_match.group(1) or "").strip() if not raw: await say(event, USAGE) return try: total, interval = parse_autopost_args(raw) except ValueError as e: raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE).replace("<", "<").replace(">", ">")) ranges = plan_ranges(total, interval) if len(ranges) > MAX_POSTS: raise UserError(f"That would be {len(ranges)} posts - at most {MAX_POSTS} at once. Use a bigger interval.") chans = await db.list_channels() if not chans: raise UserError("No channels yet. Register one with /addchannel first.") uid = event.sender_id await discard_temp(ctx, uid) clear_state(ctx, uid) token = secrets.token_hex(4) ctx.pending[token] = AutoChoice(user=uid, total=total, interval=interval, ranges=ranges) await show_picker(event, token, 0)
async def show_picker(event, token: str, page: int) -> None: choice = ctx.pending.get(token) if not isinstance(choice, AutoChoice) or choice.user != event.sender_id: raise UserError("That list has expired. Run /autopost again.") chans = await db.list_channels() if not chans: raise UserError("No channels yet. Register one with /addchannel first.") first = choice.ranges[0] head = ( f"π <b>Autopost</b>: {len(choice.ranges)} post(s) for {choice.total} episodes (every {choice.interval})\n" f"{ranges_summary(choice.ranges)}\n\n" f"Each post says β{esc(title_of(*first))}β with the button β{esc(button_label(*first))}β. The buttons get " f"the link {esc(PLACEHOLDER_LINK)} for now; when everything is posted I ask you for the real link of " "each button, one after the other.\n\n" "π’ <b>Which channel should I post them in?</b>" ) text, kb = picker.render( chans, page, head=head, kind="ap", arg=token, choose=lambda c: f"apc:{token}:{c.id}", extra_rows=[[Button.inline("βοΈ Cancel", f"apx:{token}")]], ) await show(event, text, kb)
ctx.pickers["ap"] = show_picker
@on_cb(ctx, "apc") async def cb_pick(event, parts): token, cid = parts[0], int(parts[1]) choice = ctx.pending.get(token) if not isinstance(choice, AutoChoice) or choice.user != event.sender_id: raise UserError("That list has expired. Run /autopost again.") ch = await db.get_channel(cid) if ch is None or not ch.active: raise UserError("That channel is not registered any more. Run /autopost again.") rights = await get_rights(client, ch) if rights is not None and not (rights.admin and rights.post): raise UserError("The bot needs the βPost messagesβ admin right in that channel.") if ctx.lock.locked(): raise UserError("Another long job (replace / repost / shift) is still running. Try again in a minute.") ctx.pending.pop(token, None) # a second press on the list can't post everything twice last = [0.0]
async def prog(n): if time.monotonic() - last[0] < 3: return last[0] = time.monotonic() try: await edit_callback_message(event, f"π€ Posting in <b>{esc(ch.title)}</b>: {n} of {len(choice.ranges)}β¦") except Exception: pass
async with ctx.lock: res = await post_series(ctx, ch, choice.ranges, event.sender_id, delay=cfg.edit_delay, progress=prog) if not res.posts: raise UserError(f"Nothing was posted. {res.failure}") done = [(p.id, 0, 0) for p in res.posts] lines = [ f"β
Posted {len(res.posts)} of {len(choice.ranges)} in <b>{esc(ch.title)}</b>", ranges_summary(choice.ranges[: len(res.posts)]), f"Their buttons open {esc(PLACEHOLDER_LINK)} until you send the real links.", ] if res.failure: lines.append(f"\nβ οΈ Stopped early - {esc(res.failure)}\nThe rest was not posted; run /autopost again for it.") await edit_callback_message(event, "\n".join(lines)) await begin_queue(ctx, event, kind="auto", cid=ch.id, items=done, new=True)
@on_cb(ctx, "apx") async def cb_cancel(event, parts): ctx.pending.pop(parts[0], None) await edit_callback_message(event, "Cancelled - nothing was posted.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173"""/import (owner only): put a backup made by /export back.
The steps: /import β send the file β a preview of what would be added β β
Import. Importing only adds, it neverchanges or deletes anything that is here (see app/backup.py for the rules)."""from __future__ import annotations
import loggingimport secretsimport timefrom dataclasses import dataclass, field
from telethon import Button
from ..backup import MAX_BYTES, BackupError, ImportPlan, ImportResult, apply_import, parse_backup, plan_import, stampfrom ..common import ( Ctx, UserError, clear_state, cmd, guard, on_cb, on_text, purge_pending, require_owner, say, set_state, show,)
log = logging.getLogger(__name__)
ASK = ( "π₯ <b>Import a backup</b>\n" "Send me the file that /export made (<code>channel-posts-export.json</code>) as your next message - the file " "itself, unchanged.\n\n" "Importing only <b>adds</b>: channels and posts that are here already are left exactly as they are, and nothing is " "deleted. You see what would be added before anything happens. /cancel stops.")
@dataclassclass PendingImport: """A backup that was read and is waiting for the owner's OK (or is being imported)."""
user: int plan: ImportPlan running: bool = False created: float = field(default_factory=time.monotonic)
def preview_text(plan: ImportPlan) -> str: bk = plan.backup sent_total = sum(1 for p in bk.posts if p["status"] == "sent") drafts_total = len(bk.posts) - sent_total made = f" (made {stamp(bk.exported_at)})" if bk.exported_at else "" lines = [f"π₯ <b>Backup file read</b>{made}", ""] lines.append(f"π’ Channels: {len(bk.channels)} in the file - {len(plan.new_channels)} new, {plan.channels_present} here already") lines.append(f"π Published posts: {sent_total} in the file - {plan.sent_to_add} to add, {plan.posts_present} here already") if drafts_total: lines.append(f"π Drafts: {drafts_total} in the file - {plan.drafts_to_add} to add, {plan.drafts_present} here already") if plan.new_ignored: lines.append(f"π {len(plan.new_ignored)} post(s) that were made to be forgotten stay forgotten here too") if plan.posts_forgotten: lines.append(f"π {plan.posts_forgotten} post(s) you made this bot forget are not brought back") if plan.posts_orphaned: lines.append(f"β’ {plan.posts_orphaned} post(s) belong to a channel that is neither here nor in the file - left out") if bk.bad_rows: lines.append(f"β’ {bk.bad_rows} entr{'y' if bk.bad_rows == 1 else 'ies'} of the file could not be read - left out") lines.append("") if plan.nothing_new: lines.append("There is nothing new in this file - everything in it is here already.") else: lines.append("Nothing that is here now is changed or deleted.") if plan.new_channels: lines.append( "A channel that is new here works only if this bot is an admin there. On a different bot, send " "/addchannel for it once afterwards - its posts stay." ) return "\n".join(lines)
def result_text(res: ImportResult) -> str: lines = ["β
<b>Imported</b>", ""] if res.channels_added: lines.append( f"π’ {res.channels_added} channel(s) added - check them in /channels " "(on a different bot, send /addchannel for each one once so the bot gets its own access)" ) lines.append(f"π {res.posts_added} published post(s) added to My posts") if res.drafts_added: lines.append(f"π {res.drafts_added} draft(s) added") if res.marks_added: lines.append(f"π {res.marks_added} βforgottenβ mark(s) added") if res.skipped_meanwhile: lines.append(f"β’ {res.skipped_meanwhile} post(s) turned up here meanwhile and were left as they are") return "\n".join(lines)
def register(ctx: Ctx) -> None: client, db = ctx.client, ctx.db
@client.on(cmd("import")) @guard(ctx, owner=True) async def h_import(event): set_state(ctx, event.sender_id, "import") await say(event, ASK, [[Button.inline("βοΈ Cancel", "cx")]])
@on_text(ctx, "import") async def got_file(event, st): require_owner(ctx, event) msg = event.message f = getattr(msg, "file", None) if f is None: raise UserError("Please send the backup FILE (the one /export made), not text. /cancel stops.") if (getattr(f, "size", None) or 0) > MAX_BYTES: 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.") note = await say(event, "π₯ Reading the fileβ¦") data = await msg.download_media(file=bytes) if not isinstance(data, (bytes, bytearray)): raise UserError("I could not download that file. Send it again, or /cancel.") try: plan = await plan_import(db, parse_backup(bytes(data))) except BackupError as e: raise UserError(f"That file can't be imported: {e}\nSend the right file, or /cancel.") clear_state(ctx, event.sender_id) purge_pending(ctx) if plan.nothing_new: await note.edit(preview_text(plan), buttons=None) return token = secrets.token_hex(4) ctx.pending[token] = PendingImport(user=event.sender_id, plan=plan) kb = [[Button.inline("β
Import", f"imy:{token}"), Button.inline("βοΈ Cancel", f"imx:{token}")]] await note.edit(preview_text(plan), buttons=kb)
@on_cb(ctx, "imx") async def cb_cancel(event, parts): require_owner(ctx, event) pend = ctx.pending.get(parts[0]) if isinstance(pend, PendingImport) and not pend.running: ctx.pending.pop(parts[0], None) await show(event, "Cancelled - nothing was imported.")
@on_cb(ctx, "imy") async def cb_import(event, parts): require_owner(ctx, event) pend = ctx.pending.get(parts[0]) if not isinstance(pend, PendingImport): raise UserError("This import has expired (or was done already). Send /import again.") if pend.running: raise UserError("This import is already running.") if ctx.lock.locked(): raise UserError("Another long job (replace, repost, shift, sync ...) is still running - try again when it has finished.") last = [0.0]
async def prog(done: int, total: int) -> None: if time.monotonic() - last[0] < 3: return last[0] = time.monotonic() try: await show(event, f"π₯ Importingβ¦ {done} of {total} post(s)") except Exception: log.debug("progress update failed", exc_info=True)
async with ctx.lock: pend.running = True try: res = await apply_import(db, pend.plan, progress=prog) finally: ctx.pending.pop(parts[0], None) if ctx.syncer is not None: ctx.syncer.forget_cache() # the channels that came in are known to the live watch from now on await show(event, result_text(res), [[Button.inline("π My posts", "pl")]])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201"""/start /help /cancel /export /userbot, plus the routers for free text and inline-button presses (/import is in backup.py)."""from __future__ import annotations
import ioimport jsonimport logging
from telethon import events
from ..common import Ctx, UserError, cmd, clear_state, discard_temp, guard, say, showfrom ..picker import PAGE_CBfrom ..richmsg import RICH_HELP, RICH_HELP_HTMLfrom ..richtext import CHEAT_SHEETfrom ..tgutil import esc
log = logging.getLogger(__name__)
HELP = ( "<b>Channel Post Bot</b>\n\n" "<b>Posts</b>\n" "/new - create a post (text or media, with buttons)\n" "/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" "/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" "/formatting - bold, italic, links, quotes ...: Telegram's own formatting is kept, or type HTML / Markdown instead\n" "/rich - rich messages: headings, lists, tables, expandable sections, math, maps, pictures, buttons ... typed as HTML / Markdown, or sent as a Telegram rich message\n" "/cancel - stop what you're doing\n\n" "<b>Channels</b>\n" "/addchannel - register a channel (the bot must be an admin there)\n" "/channels - list your channels, or take one out (the bot asks whether its saved posts in My posts are deleted too)\n\n" "<b>Owner tools</b>\n" "/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" "/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" "/swap @old @new - swap the username inside t.me links (button links and hyperlinks) in all channels\n" "/handleswap @old @new - change the username @old written in posts (text, captions, button names) to @new in all channels; links stay\n" "/undo - undo the last /swap or /handleswap\n" "/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" "/shift @source @destination [from_id] [to_id] [-c] [-all] [--no-media] - copy posts from one channel into another (buttons kept, listed in My posts); " "a channel Telegram restricts (copyright strike) is copied from My posts; " "-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; " "--no-media: no files, only the text and buttons\n" "/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" "/userbot - status of the helper account that, by itself and without asking, deletes and edits the posts the bot is not allowed to\n" "/export - download a JSON backup of your channels and posts\n" "/import - put a backup made by /export back (only adds: nothing that exists is changed or deleted)" "\n/admins - list admins (owner)\n/addadmin 123456789 - add an admin (owner)\n/removeadmin 123456789 - remove an admin (owner)")
def register(ctx: Ctx) -> None: client, db = ctx.client, ctx.db
@client.on(cmd("admins")) @guard(ctx, owner=True) async def h_admins(event): ids = sorted(ctx.admins | set(ctx.cfg.admins)) await say(event, "Admins: " + (", ".join(map(str, ids)) if ids else "none"))
@client.on(cmd("addadmin")) @guard(ctx, owner=True) async def h_addadmin(event): parts = (event.raw_text or "").split() if len(parts) != 2 or not parts[1].isdigit() or int(parts[1]) <= 0: raise UserError("Use /addadmin followed by a numeric Telegram user ID.") uid = int(parts[1]) if ctx.cfg.is_owner(uid): raise UserError("That user is already an owner.") if not await db.add_admin(uid): await say(event, f"{uid} is already an admin.") return ctx.admins.add(uid) await say(event, f"Added {uid} as an admin.")
@client.on(cmd("removeadmin")) @guard(ctx, owner=True) async def h_removeadmin(event): parts = (event.raw_text or "").split() if len(parts) != 2 or not parts[1].isdigit() or int(parts[1]) <= 0: raise UserError("Use /removeadmin followed by a numeric Telegram user ID.") uid = int(parts[1]) if not await db.remove_admin(uid): await say(event, f"{uid} is not an admin.") return ctx.admins.discard(uid) await say(event, f"Removed {uid} as an admin.")
@client.on(cmd("start")) @client.on(cmd("help")) @guard(ctx) async def h_help(event): await say(event, HELP)
@client.on(cmd("formatting")) @guard(ctx) async def h_formatting(event): await say(event, CHEAT_SHEET)
@client.on(cmd("rich")) @guard(ctx) async def h_rich(event): await say(event, RICH_HELP) await say(event, RICH_HELP_HTML)
@client.on(cmd("cancel")) @guard(ctx) async def h_cancel(event): await discard_temp(ctx, event.sender_id) clear_state(ctx, event.sender_id) await say(event, "Cancelled.")
@client.on(cmd("export")) @guard(ctx, owner=True) async def h_export(event): data = await db.export_all() buf = io.BytesIO(json.dumps(data, ensure_ascii=False, indent=1).encode("utf-8")) buf.name = "channel-posts-export.json" await event.respond( f"π¦ Backup: {len(data['channels'])} channel(s), {len(data['posts'])} post(s). " "To put it back (on this bot or a new one), send /import and then this file.", file=buf, )
@client.on(cmd("userbot")) @guard(ctx, owner=True) async def h_userbot(event): ub = ctx.userbot if ub is None or not ub.enabled: await say( event, "π€ <b>Userbot: not set up.</b>\n" "The bot does its work itself first. If Telegram refuses - deleting posts older than 48 hours, or " "editing a post that belongs to another bot (/replace, text and caption edits) - a helper account, " "the userbot, takes over by itself, without asking you each time: it joins the channel through an " "invite link the bot makes, the bot gives it the βDelete messagesβ or βEdit messages of othersβ right " "if it has the βAdd new adminsβ right, and gives the rights back afterwards.\n\n" "To set it up: on your own computer run <code>python make_userbot_session.py</code> with a " "<b>separate</b> Telegram account, and put the printed text into the bot's secrets as " "<code>USERBOT_SESSION</code>. Then send /start to this bot from that account (new media reaches the " "userbot through its chat with the bot - that is what makes a replace quick). See the README.", ) return if not ub.ready: await ub.connect() kept = "stays an admin" if ub.keep_admin else "is made admin only while it deletes or edits" await say( event, f"π€ <b>Userbot:</b> {esc(ub.describe())}\nIt {kept} (USERBOT_KEEP_ADMIN).\n" "It must have started this bot (/start from that account): new media for an edit goes through its chat " "with the bot, which is what makes a big file as quick as a small one.", )
@client.on( events.NewMessage(incoming=True, func=lambda e: e.is_private and not (e.raw_text or "").startswith("/")) ) @guard(ctx) async def h_free_text(event): st = ctx.state.get(event.sender_id) if not st: await say(event, "Use /new to create a post or /posts to manage your posts. /help lists everything.") return fn = ctx.text_handlers.get(st["mode"]) if fn is None: clear_state(ctx, event.sender_id) await say(event, "That step is no longer active. Start again with /new.") return await fn(event, st)
@client.on(events.CallbackQuery()) @guard(ctx) async def h_callback(event): try: await event.answer() # stop the loading spinner right away except Exception: pass data = event.data.decode("utf-8", "replace") prefix, *parts = data.split(":") fn = ctx.callbacks.get(prefix) if fn is None: await event.respond("This button is no longer active. Use /new or /posts.") return await fn(event, parts)
async def cb_noop(event, parts): await event.answer()
async def cb_cancel(event, parts): uid = event.sender_id await discard_temp(ctx, uid) clear_state(ctx, uid) await show(event, "Cancelled.")
async def cb_channel_page(event, parts): """β βΆ under a channel chooser: draw the same chooser again on another page.""" kind, arg, page = parts[0], parts[1], int(parts[2]) draw = ctx.pickers.get(kind) if draw is None: raise UserError("This list is no longer active. Start the command again.") await draw(event, arg, page)
ctx.callbacks["noop"] = cb_noop ctx.callbacks["cx"] = cb_cancel ctx.callbacks[PAGE_CB] = cb_channel_page123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268"""/broadcast [time] (also spelled /boardcast): one message to every connected channel. Owner only.
With a time (50m, 1h, 5d) the message is deleted again from all the channels - and from My posts - when the time is up;without one it stays."""from __future__ import annotations
import asyncioimport loggingimport secretsimport timefrom dataclasses import dataclass, fieldfrom datetime import datetime, timedeltafrom types import SimpleNamespacefrom typing import Optional
from telethon import Button, errors
from ..buttons import parse_buttons_textfrom ..common import ( Ctx, UserError, clear_state, cmd, discard_temp, edit_callback_message, guard, on_cb, on_text, purge_pending, require_owner, say, send_post, set_state, show,)from ..db import utcnowfrom ..expiry import human, parse_duration, stampfrom ..richmsg import block_count, block_labels, is_block_invalid, refused_blocks, rich_offrom ..tgutil import esc, explain_rpc, flood_retry, peer_offrom ..ui import CANCELfrom .panel import markup_note, read_content
log = logging.getLogger(__name__)
BUTTON_HELP = ( "β <b>Buttons?</b> Send one row per line as <code>Button text - link</code> " "(several in one row: separate them with <code> | </code>), or skip.")
@dataclassclass BroadcastDraft: """The message is made and previewed; the owner still has to confirm."""
user: int content: dict # text, entities, media_kind, media_file_id buttons: list ttl: Optional[int] # seconds until it is deleted again; None = it stays created: float = field(default_factory=time.monotonic)
@dataclassclass BroadcastResult: group_id: str delete_at: Optional[datetime] ttl: Optional[int] = None # seconds it stays; None = for good sent: list = field(default_factory=list) # [(channel, message id)] failed: list = field(default_factory=list) # [(channel, reason)]
def shape_of(draft: BroadcastDraft) -> SimpleNamespace: c = draft.content return SimpleNamespace( text=c.get("text") or "", entities=c.get("entities") or [], buttons=draft.buttons, media_kind=c.get("media_kind"), media_file_id=c.get("media_file_id"), link_preview=False, )
async def send_broadcast(ctx: Ctx, chans: list, draft: BroadcastDraft, *, delay: float = 1.0, progress=None) -> BroadcastResult: """Post the message in every channel, save each copy in My posts and, if it expires, schedule its deletion.""" db = ctx.db delete_at = utcnow() + timedelta(seconds=draft.ttl) if draft.ttl else None res = BroadcastResult(group_id=secrets.token_hex(6), delete_at=delete_at, ttl=draft.ttl) shape = shape_of(draft) for n, ch in enumerate(chans, 1): try: sent = await flood_retry(lambda: send_post(ctx.client, peer_of(ch), shape)) except errors.RPCError as e: res.failed.append((ch, explain_rpc(e))) continue except Exception as e: log.exception("broadcast: posting in channel %s failed", ch.id) res.failed.append((ch, type(e).__name__)) continue await db.create_post( channel_id=ch.id, message_id=sent.id, status="sent", source="bot", created_by=draft.user, text=shape.text, entities=shape.entities, media_kind=shape.media_kind, media_file_id=shape.media_file_id, buttons=shape.buttons, link_preview=False, sent_at=utcnow(), ) res.sent.append((ch, sent.id)) if delete_at is not None: # saved at once, so a restart in the middle loses nothing await db.schedule_deletes( [dict(channel_id=ch.id, message_id=sent.id, delete_at=delete_at, group_id=res.group_id, created_by=draft.user)] ) if ctx.expirer is not None: ctx.expirer.notify(delete_at) if progress: await progress(n) if n < len(chans): await asyncio.sleep(delay) return res
def report(res: BroadcastResult, total: int) -> str: lines = [f"π£ <b>Broadcast sent</b> to {len(res.sent)} of {total} channel(s)"] lines += [f"β
{esc(ch.title)}" for ch, _ in res.sent] lines += [f"β {esc(ch.title)} - {esc(why)}" for ch, why in res.failed] if res.delete_at is not None and res.sent: lines += ["", f"π It is deleted from these channels and from My posts in {human(res.ttl)} ({stamp(res.delete_at)})."] elif res.sent: lines += ["", "π No time was given, so it stays in the channels."] return "\n".join(lines)
def register(ctx: Ctx) -> None: client, db, cfg = ctx.client, ctx.db, ctx.cfg
@client.on(cmd("broadcast", args=True)) @client.on(cmd("boardcast", args=True)) @guard(ctx, owner=True) async def h_broadcast(event): purge_pending(ctx) raw = (event.pattern_match.group(1) or "").strip() ttl = None if raw: try: ttl = parse_duration(raw) except ValueError as e: raise UserError(str(e)) chans = await db.list_channels() if not chans: raise UserError("No channels yet. Register one with /addchannel first.") uid = event.sender_id await discard_temp(ctx, uid) set_state(ctx, uid, "bc_content", ttl=ttl) when = ( f"β³ It is deleted from all channels - and from My posts - {human(ttl)} after it is sent." if ttl else "π No time given: it stays in the channels for good. (For a timed one use e.g. <code>/broadcast 1h</code>.)" ) await say( event, f"π£ <b>Broadcast</b> to {len(chans)} channel(s)\n{when}\n\n" "βοΈ <b>Send the message now.</b> Text, or a photo / video / GIF / file with a caption. Formatting is kept " "(or type HTML / Markdown - /formatting shows how; rich blocks: /rich).", CANCEL, )
@on_text(ctx, "bc_content") async def h_content(event, st): m = event.message if m.grouped_id and st.get("group") == m.grouped_id: return # the other items of an album: only the first one is used if m.grouped_id: st["group"] = m.grouped_id content = await read_content(ctx, event) set_state(ctx, event.sender_id, "bc_buttons", ttl=st["ttl"], content=content) await say(event, markup_note(content.how) + BUTTON_HELP, [[Button.inline("β No buttons", "brs")], CANCEL[0]])
async def confirm_step(event, st, rows: list) -> None: uid = event.sender_id draft = BroadcastDraft(user=uid, content=st["content"], buttons=rows, ttl=st["ttl"]) chans = await db.list_channels() if not chans: clear_state(ctx, uid) raise UserError("No channels any more. Register one with /addchannel first.") shape = shape_of(draft) try: await send_post(client, await event.get_input_chat(), shape) # the preview except errors.RPCError as e: rich, which = rich_of(shape), "" if rich is not None and rich.fmt == "blocks" and is_block_invalid(e): # name the blocks Telegram won't take bad = await refused_blocks(client, await event.get_input_chat(), rich) if bad: which = f"\nIt won't take these blocks (of {block_count(rich)}): {block_labels(rich, bad)}." raise UserError("β " + explain_rpc(e) + which + "\nThe message can't be sent like this - send it again.") token = secrets.token_hex(4) ctx.pending[token] = draft clear_state(ctx, uid) names = "\n".join(f"β’ {esc(c.title)}" for c in chans[:15]) + (f"\nβ’ β¦ and {len(chans) - 15} more" if len(chans) > 15 else "") when = ( f"β³ Deleted again {human(draft.ttl)} after sending." if draft.ttl else "π Permanent (no time given)." ) await say( event, f"π That is the message. Send it to <b>{len(chans)}</b> channel(s)?\n{names}\n\n{when}", [[Button.inline("π£ Send to all channels", f"brc:{token}")], [Button.inline("βοΈ Cancel", f"brn:{token}")]], )
@on_text(ctx, "bc_buttons") async def h_buttons(event, st): if event.message.grouped_id: return try: rows = parse_buttons_text(event.raw_text or "") except ValueError as e: raise UserError(f"β {e}\n\nTry again, or tap βNo buttonsβ.") if not rows: raise UserError("Send at least one button as βText - linkβ, or tap βNo buttonsβ.") await confirm_step(event, st, rows)
@on_cb(ctx, "brs") async def cb_no_buttons(event, parts): require_owner(ctx, event) st = ctx.state.get(event.sender_id) if not st or st.get("mode") != "bc_buttons": raise UserError("That step is no longer active. Start again with /broadcast.") await confirm_step(event, st, [])
@on_cb(ctx, "brn") async def cb_cancel(event, parts): require_owner(ctx, event) ctx.pending.pop(parts[0], None) await show(event, "Cancelled - nothing was sent.")
@on_cb(ctx, "brc") async def cb_send(event, parts): require_owner(ctx, event) token = parts[0] draft = ctx.pending.get(token) if not isinstance(draft, BroadcastDraft) or draft.user != event.sender_id: raise UserError("That broadcast has expired. Start again with /broadcast.") chans = await db.list_channels() if not chans: raise UserError("No channels any more. Register one with /addchannel first.") if ctx.lock.locked(): raise UserError("Another long job (replace / repost / shift) is still running. Try again in a minute.") ctx.pending.pop(token, None) # a second press can't send it twice last = [0.0]
async def prog(n): if time.monotonic() - last[0] < 3: return last[0] = time.monotonic() try: await edit_callback_message(event, f"π£ Sendingβ¦ {n} of {len(chans)} channel(s)") except Exception: pass
async with ctx.lock: res = await send_broadcast(ctx, chans, draft, delay=cfg.edit_delay, progress=prog) await edit_callback_message(event, report(res, len(chans)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182"""Channel registration: /addchannel, /channels."""from __future__ import annotations
import loggingimport re
from telethon import Button, events, types
from .. import pickerfrom ..channelref import parse_channel_reffrom ..common import Ctx, UserError, clear_state, cmd, guard, on_cb, on_text, require_owner, say, set_state, showfrom ..tgutil import esc, get_rightsfrom ..ui import CANCEL
log = logging.getLogger(__name__)
ADD_HELP = ( "π’ <b>Add a channel</b>\n" "1. Make the bot an admin of the channel with the rights <i>Post messages</i>, <i>Edit messages of others</i> " "and <i>Delete messages</i>.\n" "2. Then <b>forward any post from that channel to me</b>, or send its @username (public channels).\n\n" "Tip for private channels: if forwarding doesn't work, post something in the channel while the bot is " "running, then forward that post.")NEEDS_ACCESS = ( "I can see the channel, but Telegram hasn't given me its access details yet. Post something in the " "channel while the bot is running (or send the @username if it's public), then forward a post again.")
def rights_line(r) -> str: if r is None: return "rights unknown" if not r.admin: return "β οΈ not an admin there" ok = lambda v: "β
" if v else "β" # noqa: E731 return f"post {ok(r.post)} Β· edit others' posts {ok(r.edit)} Β· delete {ok(r.delete)}"
def register(ctx: Ctx) -> None: client, db = ctx.client, ctx.db
# remember channels whose full details (access hash) we have seen in updates @client.on(events.NewMessage(func=lambda e: bool(e.is_channel) and not e.is_group)) async def watch_channels(event): try: chat = await event.get_chat() if isinstance(chat, types.Channel) and chat.access_hash and not getattr(chat, "min", False): prev = ctx.seen_channels.get(chat.id) ctx.seen_channels[chat.id] = chat if prev is None or prev.access_hash != chat.access_hash: await db.touch_channel_hash(chat.id, chat.access_hash) except Exception: # pragma: no cover log.debug("channel watcher failed", exc_info=True)
@client.on(cmd("addchannel")) @guard(ctx, owner=True) async def h_addchannel(event): set_state(ctx, event.sender_id, "add_channel") await say(event, ADD_HELP, CANCEL)
@on_text(ctx, "add_channel") async def h_add_channel(event, st): m = event.message ent = None fwd = m.forward if fwd is not None and isinstance(getattr(fwd, "chat", None), types.Channel): ent = fwd.chat if getattr(ent, "min", False) or not getattr(ent, "access_hash", None): ent = ctx.seen_channels.get(ent.id, ent) else: ref = parse_channel_ref(m.raw_text or "") if ref is None: raise UserError("Forward a post from the channel to me, or send its @username.") if isinstance(ref, int): ent = ctx.seen_channels.get(ref) if ent is None: try: ent = await client.get_entity(ref if isinstance(ref, str) else types.PeerChannel(ref)) except Exception: ent = None if not isinstance(ent, types.Channel): raise UserError("I couldn't find that channel.\n\n" + re.sub(r"<[^>]+>", "", ADD_HELP)) if not ent.broadcast: raise UserError("That is a group, not a channel. Only channels are supported.") if not ent.access_hash or getattr(ent, "min", False): raise UserError(NEEDS_ACCESS) rights = await get_rights(client, ent) if rights is not None and not rights.admin: raise UserError("The bot is not an admin of that channel yet. Add it as an admin, then try again.") await db.save_channel(ent.id, ent.access_hash, ent.title or "", ent.username, event.sender_id) clear_state(ctx, event.sender_id) warn = "" if rights is not None and not (rights.post and rights.edit and rights.delete): warn = "\n\nβ οΈ Missing rights: give the bot <i>Post</i>, <i>Edit messages of others</i> and <i>Delete</i> so everything works." await say( event, f"β
Added <b>{esc(ent.title or '')}</b>\n{rights_line(rights)}{warn}\n\nCreate a post with /new.", )
async def show_channels(event, arg: str = "", page: int = 0) -> None: """The list of channels; the owner's number buttons choose one to remove.""" chans = await db.list_channels() if not chans: raise UserError("No channels yet. Use /addchannel.") owner = ctx.cfg.is_owner(event.sender_id) text, kb = picker.render( chans, page, head="π’ <b>Your channels</b>", kind="ch", choose=(lambda c: f"chd:{c.id}") if owner else None, with_username=True, hint="To take a channel out of the bot, tap its number.", ) await show(event, text, kb or None)
ctx.pickers["ch"] = show_channels
@client.on(cmd("channels")) @guard(ctx) async def h_channels(event): await show_channels(event)
@on_cb(ctx, "chd") async def cb_remove_channel(event, parts): """A number was tapped: ask what becomes of the channel's saved posts before it is taken out of the bot.""" require_owner(ctx, event) ch = await db.get_channel(int(parts[0])) if ch is None or not ch.active: await show_channels(event) return back = Button.inline("π Back", f"{picker.PAGE_CB}:ch::0") n = await db.count_channel_posts(ch.id) if not n: # nothing saved: nothing to ask about await show( event, f"β Take <b>{esc(ch.title)}</b> out of the bot?\nIt has no saved posts. You can add it again with /addchannel.", [[Button.inline("β
Yes, remove it", f"chy:{ch.id}:0"), back]], ) return await show( event, f"β Take <b>{esc(ch.title)}</b> out of the bot.\n\n" f"Do you also want to delete its saved posts - the {n} post(s) My posts holds for this channel? " "Nothing is deleted in the channel itself.", [ [Button.inline("π Yes, delete them too", f"chy:{ch.id}:1"), Button.inline("π¦ No, keep them", f"chy:{ch.id}:0")], [back], ], )
@on_cb(ctx, "chy") async def cb_remove_channel_yes(event, parts): """chy:<channel>:1 removes the channel and deletes its saved posts, chy:<channel>:0 (or an old button without the second part) removes only the channel and keeps them.""" require_owner(ctx, event) cid = int(parts[0]) wipe = len(parts) > 1 and parts[1] == "1" ch = await db.get_channel(cid) name = f"<b>{esc(ch.title)}</b>" if ch is not None else "The channel" await db.set_channel_active(cid, False) gone = 0 sy = ctx.syncer if sy is not None: sy.forget_cache() if wipe: await show(event, f"β³ Deleting the saved posts of {name}β¦") # no look at the channel may be saving posts while they are deleted (it would bring some back) if sy is not None: async with sy.exclusive(): gone = await db.delete_channel_data(cid) else: gone = await db.delete_channel_data(cid) ctx.sync_ignore.difference_update({k for k in ctx.sync_ignore if k[0] == cid}) text = ( f"β
{name} was removed from the bot, and its {gone} saved post(s) were deleted from My posts. Nothing was deleted " "in the channel. If you add it again with /addchannel, its posts are read in again." ) else: text = f"β
{name} was removed from the bot. Its saved posts are kept; add it again with /addchannel and they are there again." await show(event, text)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115"""Check buttons (owner only): compare the buttons saved in the bot with what a channel really shows, and repair."""from __future__ import annotations
import loggingimport time
from telethon import Button, errors
from ..buttons_sync import fix_buttons, scan_buttonsfrom ..common import Ctx, UserError, on_cb, require_owner, showfrom ..tgutil import esc
log = logging.getLogger(__name__)SAMPLE = 12
def register(ctx: Ctx) -> None: client, db, cfg = ctx.client, ctx.db, ctx.cfg
async def load(parts): ch = await db.get_channel(int(parts[0])) if ch is None: raise UserError("That channel is not registered.") if ctx.lock.locked(): raise UserError("Another long job (replace / repost) is still running.") return ch
def throttled(event, make_text, every: float = 3.0): last = [0.0]
async def upd(obj, force: bool = False) -> None: now = time.monotonic() if not force and now - last[0] < every: return last[0] = now try: await show(event, make_text(obj)) except errors.MessageNotModifiedError: pass except Exception: log.debug("progress update failed", exc_info=True)
return upd
@on_cb(ctx, "pk") async def cb_check(event, parts): require_owner(ctx, event) ch = await load(parts) title = esc(ch.title) async with ctx.lock: await show(event, f"π§ Checking the buttons of <b>{title}</b>β¦") posts = await db.sent_posts(ch.id) scan = await scan_buttons( client, ch, posts, progress=throttled(event, lambda s: f"π§ Checking <b>{title}</b>: {s.fine + len(s.bad) + len(s.gone)}/{s.total}β¦") ) lines = [f"π§ <b>{title}</b> - checked {scan.total} post(s) that have link buttons."] kb = [] if not scan.total: lines.append("None of the saved posts has link buttons, so there is nothing to check.") else: lines.append(f"β
{scan.fine} show their buttons correctly.") if scan.bad: ids = ", ".join(f"#{p.message_id}" for p, _, _ in scan.bad[:SAMPLE]) more = "β¦" if len(scan.bad) > SAMPLE else "" lines.append( f"β οΈ <b>{len(scan.bad)}</b> are saved with buttons here, but the channel shows them without those buttons " f"(or with different links): {ids}{more}" ) kb.append([Button.inline(f"π§ Fix {len(scan.bad)} post(s)", f"pkf:{ch.id}")]) elif scan.total: lines.append("Everything matches.") if scan.gone: ids = ", ".join(f"#{p.message_id}" for p in scan.gone[:SAMPLE]) lines.append( f"βΉοΈ {len(scan.gone)} saved post(s) no longer exist in the channel ({ids}{'β¦' if len(scan.gone) > SAMPLE else ''})." ) kb.append([Button.inline("π Back", f"pc:{ch.id}:0")]) await show(event, "\n".join(lines), kb)
@on_cb(ctx, "pkf") async def cb_fix(event, parts): require_owner(ctx, event) ch = await load(parts) title = esc(ch.title) async with ctx.lock: await show(event, f"π§ Looking again at <b>{title}</b>β¦") scan = await scan_buttons(client, ch, await db.sent_posts(ch.id)) if not scan.bad: res = None else: total = len(scan.bad) res = await fix_buttons( client, ch, scan.bad, delay=cfg.edit_delay, progress=throttled(event, lambda r: f"π§ Fixing <b>{title}</b>: {r.fixed + r.already}/{total}β¦"), ) if res is None: text = f"β
<b>{title}</b>: all buttons match now - nothing to fix." else: lines = [f"π§ <b>{title}</b> - put the saved buttons back on <b>{res.fixed}</b> post(s)."] if res.nudged: lines.append(f"{res.nudged} of them needed a second edit before Telegram showed the buttons.") if res.already: lines.append(f"{res.already} were already fine when I got to them.") if res.gone: lines.append(f"{res.gone} no longer exist in the channel.") if res.failed: sample = ", ".join(f"#{m} {esc(n)}" for m, n in res.failed[:8]) lines.append(f"β οΈ <b>{len(res.failed)} failed</b> ({sample}{'β¦' if len(res.failed) > 8 else ''}).") if res.aborted: lines.append(f"Stopped early: Telegram refused {esc(res.aborted)} several times in a row.") text = "\n".join(lines) await show(event, text, [[Button.inline("π§ Check again", f"pk:{ch.id}"), Button.inline("π Back", f"pc:{ch.id}:0")]])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"""/new: create a post, with the episode-range auto-suggestion."""from __future__ import annotations
import logging
from telethon import Button
from .. import pickerfrom ..buttons import norm_url, parse_buttons_text, set_fieldfrom ..common import Ctx, UserError, clear_state, cmd, discard_temp, guard, on_cb, on_text, say, set_state, showfrom ..suggest import make_suggestionfrom ..tgutil import esc, shortfrom ..ui import CANCEL, KIND_NAMEfrom .panel import markup_note, read_content, show_panel
log = logging.getLogger(__name__)
BUTTON_HELP = ( "β <b>Now the buttons</b>\n" "Send one row per line as <code>Button text - link</code>.\n" "Several buttons in one row: separate them with <code> | </code>.\n\n" "Example:\n<code>Download Episodes 01 to 20 - https://t.me/yourbot?start=abc</code>\n\n" "Or send /skip to post without buttons.")
def register(ctx: Ctx) -> None: client, db = ctx.client, ctx.db
async def ask_content(event, cid: int) -> None: set_state(ctx, event.sender_id, "new_content", cid=cid) await show( event, "βοΈ <b>Send the post now.</b>\nText, or a photo / video / GIF / file with a caption. " "Formatting (bold, links, spoilers...) is kept. No Telegram editor at hand? Type HTML or Markdown - /formatting shows how; " "headings, lists, tables, math and the other rich blocks: /rich.", CANCEL, )
async def start_for_channel(event, cid: int) -> None: ch = await db.get_channel(cid) if ch is None: raise UserError("That channel is not registered. Use /addchannel.") sug = await make_suggestion(db, cid) if sug is None: await ask_content(event, cid) return lines = [ f"π‘ <b>Suggestion for {esc(ch.title)}</b>", f"Your last button post: <code>{esc(sug.prev_label)}</code>", "The next one would be:", ] if (sug.text or "").strip(): lines.append(f"β’ Message: <i>{esc(short(sug.text, 120))}</i>") lines.append(f"β’ Button: <code>{esc(sug.new_label)}</code>") if sug.media_kind: lines.append(f"β’ Media: same {KIND_NAME.get(sug.media_kind, 'file')} as that post (you can change it before publishing)") lines.append("\nUse it and I'll only ask for the button link.") kb = [ [Button.inline("β
Use suggestion", f"ns:{cid}"), Button.inline("βοΈ Customize", f"nn:{cid}")], CANCEL[0], ] await show(event, "\n".join(lines), kb)
async def ask_link(event, post, pos) -> None: r, c = pos label = post.buttons[r][c]["t"] await say( event, f"π Send the link for the button <code>{esc(label)}</code>\n" "(for example <code>https://t.me/yourbot?start=abc</code>)", CANCEL, )
@client.on(cmd("new")) @guard(ctx) async def h_new(event): uid = event.sender_id await discard_temp(ctx, uid) clear_state(ctx, uid) chans = await db.list_channels() if not chans: raise UserError("No channels yet. Register one with /addchannel first.") if len(chans) == 1: await start_for_channel(event, chans[0].id) return await show_picker(event, "", 0)
async def show_picker(event, arg: str, page: int) -> None: chans = await db.list_channels() if not chans: raise UserError("No channels yet. Register one with /addchannel first.") text, kb = picker.render( chans, page, head="π’ <b>Which channel is this post for?</b>", kind="nc", choose=lambda c: f"nc:{c.id}", extra_rows=CANCEL ) await show(event, text, kb)
ctx.pickers["nc"] = show_picker
@on_cb(ctx, "nc") async def cb_channel(event, parts): await discard_temp(ctx, event.sender_id) await start_for_channel(event, int(parts[0]))
@on_cb(ctx, "nn") async def cb_customize(event, parts): await ask_content(event, int(parts[0]))
@on_cb(ctx, "ns") async def cb_use_suggestion(event, parts): uid, cid = event.sender_id, int(parts[0]) sug = await make_suggestion(db, cid) if sug is None: raise UserError("There is nothing to suggest any more - send the post yourself with /new.") await discard_temp(ctx, uid) post = await db.create_post( channel_id=cid, created_by=uid, status="draft", source="bot", text=sug.text, entities=sug.entities, buttons=sug.buttons, media_kind=sug.media_kind, media_file_id=sug.media_file_id, link_preview=False, ) set_state(ctx, uid, "new_link", pid=post.id, pending=list(sug.pending), temp=True) await show(event, f"β
Using the suggestion: <code>{esc(sug.new_label)}</code>") await ask_link(event, post, sug.pending[0])
@on_text(ctx, "new_link") async def h_new_link(event, st): url = norm_url(event.raw_text or "") if not url: raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc") post = await db.get_post(st["pid"]) if post is None: clear_state(ctx, event.sender_id) raise UserError("That draft is gone. Start again with /new.") r, c = st["pending"][0] post = await db.update_post(post.id, buttons=set_field(post.buttons, r, c, u=url)) st["pending"] = st["pending"][1:] if st["pending"]: await ask_link(event, post, st["pending"][0]) return clear_state(ctx, event.sender_id) await show_panel(ctx, event, post.id, note="β
Ready. Preview it, or tap <b>Publish</b>.", new=True)
@on_text(ctx, "new_content") async def h_new_content(event, st): m = event.message if m.grouped_id and st.get("group") == m.grouped_id: return # the other items of an album: only the first one is used if m.grouped_id: st["group"] = m.grouped_id content = await read_content(ctx, event) post = await db.create_post( channel_id=st["cid"], created_by=event.sender_id, status="draft", source="bot", buttons=[], link_preview=False, **content, ) set_state(ctx, event.sender_id, "new_buttons", pid=post.id, temp=True) await say(event, markup_note(content.how) + BUTTON_HELP, CANCEL)
@on_text(ctx, "new_buttons") async def h_new_buttons(event, st): if event.message.grouped_id: return try: rows = parse_buttons_text(event.raw_text or "") except ValueError as e: raise UserError(f"β {e}\n\nTry again, or send /skip.") if not rows: raise UserError("Send at least one button as βText - linkβ, or /skip.") await db.update_post(st["pid"], buttons=rows) clear_state(ctx, event.sender_id) await show_panel(ctx, event, st["pid"], note="β
Ready. Preview it, or tap <b>Publish</b>.", new=True)
@client.on(cmd("skip")) @guard(ctx) async def h_skip(event): st = ctx.state.get(event.sender_id) if not st or st["mode"] != "new_buttons": raise UserError("There is nothing to skip right now.") clear_state(ctx, event.sender_id) await show_panel(ctx, event, st["pid"], note="β
Ready (no buttons). Preview it, or tap <b>Publish</b>.", new=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""New links, one button after the other.
* "Mass replace links" in the panel of a published button post: the bot asks for a new link for that post's button and, after each answer, for the next button post of the channel (posts without a link button are skipped).* /autopost uses the same steps to ask for the real link of every button it posted.
The position in the list lives in the user's state; each answer changes the button in the channel at once."""from __future__ import annotations
import logging
from telethon import Button, errors
from ..buttons import link_positions, norm_url, set_fieldfrom ..common import Ctx, UserError, clear_state, is_cb, on_cb, on_text, say, set_state, showfrom ..tgutil import build_markup, edit_raw, esc, explain_rpc, flood_retry, peer_of, post_link, shortfrom .panel import load_post
log = logging.getLogger(__name__)
MODE = "link_queue"HEADINGS = {"mass": "π <b>Mass replace links</b>", "auto": "π <b>Links for the new posts</b>"}
async def set_link(ctx: Ctx, post, ch, r: int, c: int, url: str): """Point button (r, c) of a published post at `url`: the buttons of the channel message change (only the buttons, the text stays as it is), then the saved post follows.""" rows = set_field(post.buttons, r, c, u=url) if post.status == "sent" and post.message_id: try: await flood_retry(lambda: edit_raw(ctx.client, peer_of(ch), post.message_id, markup=build_markup(rows))) except errors.MessageNotModifiedError: pass # it already had that link except errors.RPCError as e: raise UserError("β " + explain_rpc(e) + "\nThe link of this button was NOT changed.") return await ctx.db.update_post(post.id, buttons=rows)
def mass_items(posts) -> list: """[(post id, row, column)] of every link button in `posts`, in the order given.""" return [[p.id, r, c] for p in posts for r, c in link_positions(p.buttons)]
async def current_target(ctx: Ctx, st: dict): """(post, channel, row, column) the list is at, moving past buttons that are gone; None when the list is finished.""" while st["i"] < len(st["items"]): pid, r, c = st["items"][st["i"]] post = await ctx.db.get_post(pid) if post is not None and post.status == "sent" and post.message_id and (r, c) in link_positions(post.buttons): ch = await ctx.db.get_channel(post.channel_id) if ch is not None: return post, ch, r, c st["i"] += 1 st["gone"] += 1 return None
def summary(st: dict, stopped: bool) -> str: left = max(0, len(st["items"]) - st["i"]) if stopped else 0 bits = [f"{st['done']} link(s) replaced"] if st["skipped"]: bits.append(f"{st['skipped']} skipped") if st["gone"]: bits.append(f"{st['gone']} button(s) no longer there") if left: bits.append(f"{left} not asked") return ("Stopped. " if stopped else "β
<b>All done.</b> ") + ", ".join(bits) + "."
def prompt_for(st: dict, post, ch, r: int, c: int) -> str: total = len(st["items"]) b = post.buttons[r][c] lines = [f"{HEADINGS[st['kind']]} Β· <b>{esc(ch.title)}</b> ({st['i'] + 1} of {total})", ""] where = f"Post #{post.id}" if post.message_id: where = f'<a href="{post_link(ch, post.message_id)}">Post #{post.id}</a>' several = len(link_positions(post.buttons)) label = f"β{esc(short(b.get('t') or '', 60))}β" lines.append(f"{where} Β· button {label}" + (f" (button {r + 1}.{c + 1} of {several} links)" if several > 1 else "")) lines.append(f"Now: <code>{esc(b.get('u') or '')}</code>") lines += ["", "π Send the new link for this button."] return "\n".join(lines)
async def ask(ctx: Ctx, event, st: dict, lead: str = "", *, new: bool = True) -> None: """Ask for the next link, or finish. `lead` (what just happened) goes in front, in the same message.""" tgt = await current_target(ctx, st) kb_done = [[Button.inline("π My posts", "pl")]] send = say if (new or not is_cb(event)) else show if tgt is None: clear_state(ctx, event.sender_id) await send(event, (lead + "\n\n" if lead else "") + summary(st, False), kb_done) return post, ch, r, c = tgt kb = [[Button.inline("β Skip this one", f"lqs:{st['i']}"), Button.inline("βοΈ Cancel", "lqx")]] await send(event, (lead + "\n\n" if lead else "") + prompt_for(st, post, ch, r, c), kb)
async def begin_queue(ctx: Ctx, event, *, kind: str, cid: int, items: list, lead: str = "", new: bool = True) -> None: """Start asking: `items` is [(post id, row, column)] in the order the links are wanted.""" 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) await ask(ctx, event, st, lead, new=new)
def register(ctx: Ctx) -> None: db = ctx.db
# ------------------------------------------------------------- the panel option @on_cb(ctx, "mlp") async def cb_mass_start(event, parts): post, ch = await load_post(ctx, parts[0]) if post.status != "sent" or not post.message_id: raise UserError("Mass replace works on published posts only.") if not link_positions(post.buttons): raise UserError("This post has no button with a link.") posts = await db.sent_posts_from(ch.id, post.message_id) await begin_queue(ctx, event, kind="mass", cid=ch.id, items=mass_items(posts), new=False)
# ---------------------------------------------------------------- the answers @on_text(ctx, MODE) async def h_link(event, st): url = norm_url(event.raw_text or "") if not url: raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc") tgt = await current_target(ctx, st) if tgt is None: # everything this list was about has vanished meanwhile await ask(ctx, event, st) return post, ch, r, c = tgt label = post.buttons[r][c].get("t") or "" await set_link(ctx, post, ch, r, c, url) st["i"] += 1 st["done"] += 1 await ask(ctx, event, st, f"β
<b>{esc(short(label, 40))}</b> now opens <code>{esc(url)}</code>")
def live(event, parts): st = ctx.state.get(event.sender_id) if not st or st.get("mode") != MODE: raise UserError("That list is no longer active.") if parts and parts[0].isdigit() and int(parts[0]) != st["i"]: raise UserError("That button belongs to an earlier step - use the newest message.") return st
@on_cb(ctx, "lqs") async def cb_skip(event, parts): st = live(event, parts) st["i"] += 1 st["skipped"] += 1 await ask(ctx, event, st, "β Skipped.", new=False)
@on_cb(ctx, "lqx") async def cb_stop(event, parts): st = ctx.state.get(event.sender_id) if not st or st.get("mode") != MODE: await show(event, "Cancelled.") return clear_state(ctx, event.sender_id) await show(event, summary(st, True), [[Button.inline("π My posts", "pl")]])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Helpers shared by the create and post-management handlers (not a handler module itself)."""from __future__ import annotations
from typing import Optional
from telethon import types
from ..buttons import validfrom ..common import Ctx, UserError, is_cb, say, showfrom ..richmsg import Rich, RichError, check as check_rich, entry as rich_entry, plain_of, read_typed, receivedfrom ..richtext import message_textfrom ..tgutil import classify_media, pack_file_id, ser_entities, utf16_lenfrom ..ui import button_keyboard, button_text, panel_keyboard, panel_text
CAPTION_MAX = 1024TEXT_MAX = 4096
async def load_post(ctx: Ctx, pid): post = await ctx.db.get_post(int(pid)) if post is None: raise UserError("That post no longer exists.") ch = await ctx.db.get_channel(post.channel_id) if ch is None: raise UserError("Its channel was removed from the bot. Add it again with /addchannel.") return post, ch
async def show_panel(ctx: Ctx, event, pid, note=None, new: bool = False) -> None: post, ch = await load_post(ctx, pid) text, kb = panel_text(post, ch, note), panel_keyboard(post) if new or not is_cb(event): await say(event, text, kb) else: await show(event, text, kb)
async def show_button_screen(ctx: Ctx, event, pid, r: int, c: int, new: bool = False) -> None: post, _ = await load_post(ctx, pid) if not valid(post.buttons or [], r, c): await show_panel(ctx, event, pid, new=new) return text, kb = button_text(post, r, c), button_keyboard(post, r, c) if new or not is_cb(event): await say(event, text, kb) else: await show(event, text, kb)
def check_lengths(text: str, has_media: bool) -> None: n = utf16_len(text or "") if has_media and n > CAPTION_MAX: raise UserError(f"A caption can have at most {CAPTION_MAX} characters (yours has {n}).") if not has_media and n > TEXT_MAX: raise UserError(f"A text post can have at most {TEXT_MAX} characters (yours has {n}).")
class Content(dict): """Post fields (text, entities, media_kind, media_file_id).
`how` says what the text was read as: "html" or "markdown" (turned into formatting), "rich" (a rich message sent natively, kept as it is), "rich-html" / "rich-markdown" (typed, and Telegram builds the blocks), or None."""
how = None
def markup_note(how, sep: str = "\n\n") -> str: """A line for the owner when their text was read as HTML or Markdown, followed by `sep` (empty otherwise).""" if not how: return "" if how == "rich": return f"π§© Rich message kept as it is - π Preview shows it.{sep}" if how.startswith("rich-"): lang = "HTML" if how == "rich-html" else "Markdown" return f"π§© Rich message read from {lang} - π Preview shows what Telegram makes of it (/rich).{sep}" return f"π¨ Formatting read from {'HTML' if how == 'html' else 'Markdown'} - see /formatting.{sep}"
def is_rich_how(how) -> bool: return bool(how) and how.startswith("rich")
def read_text(m, markup: bool = True, rich: Optional[Rich] = None, allow_rich: bool = True) -> tuple: """(text, entities, how) of what the owner sent - see Content.how.
A rich message (`rich`: sent natively, kept block for block) or text typed as HTML / Markdown that needs blocks becomes a rich post: `text` is its plain-text version and its only entity is the rich entry. Otherwise it is an ordinary text with Telegram's own formatting, or HTML / Markdown turned into formatting. A message that has Telegram formatting of its own is used as it is. `allow_rich` is False where a rich message can't be (a caption).""" how = None if rich is not None: if not allow_rich: raise UserError("A caption can't be a rich message. Rich messages are for text posts.") how = "rich" elif allow_rich and markup and not ser_entities(m.entities): rich = read_typed(m.raw_text or "") how = f"rich-{rich.fmt}" if rich is not None else None if rich is None: return message_text(m, markup) try: check_rich(rich) except RichError as e: raise UserError(str(e)) return plain_of(rich), [rich_entry(rich)], how
async def read_native(ctx: Ctx, event) -> Optional[Rich]: """The rich message the owner sent natively (or forwarded), or None for an ordinary message.""" try: return await received(ctx.client, event) except RichError as e: raise UserError(str(e))
def extract_content(m, markup: bool = True, rich: Optional[Rich] = None) -> Content: """A message from the user -> post fields (text, entities, media).
Telegram's own formatting is kept as it is; without any, `markup` lets HTML or Markdown in the text become formatting (or a rich message, when it has blocks only those have). `rich`: the message is a rich message sent natively.""" kind = classify_media(m) if m.media and kind is None and not isinstance(m.media, types.MessageMediaWebPage): raise UserError("That kind of message can't be used in a post. Send text, a photo, video, GIF, audio or a file.") text, entities, how = read_text(m, markup, rich if not kind else None, allow_rich=not kind) if not kind and not text.strip() and not is_rich_how(how): raise UserError("Send some text, or a photo / video / GIF / file.") if not is_rich_how(how): check_lengths(text, bool(kind)) content = Content(text=text, entities=entities, media_kind=kind, media_file_id=pack_file_id(m) if kind else None) content.how = how return content
async def read_content(ctx: Ctx, event) -> Content: """extract_content for a message that just arrived (a rich message sent natively is read, in full, first).""" return extract_content(event.message, ctx.cfg.markup_input, await read_native(ctx, event))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534"""/posts: list, open and edit posts (text, caption, media, buttons), publish drafts, delete."""from __future__ import annotations
import logging
from telethon import Button, errors
from .. import pickerfrom ..buttons import ( MAX_ROW, add_button, count, delete_button, missing_links, move_button, norm_url, parse_buttons_text, set_field, valid,)from ..common import ( Ctx, UserError, apply_edit, apply_edit_reported, clear_state, cmd, edit_report_text, guard, on_cb, on_text, say, send_post, set_state, show,)from ..db import utcnowfrom ..repost_engine import delete_batchfrom ..richmsg import ( block_count, block_labels, digest, entry as rich_entry, is_block_invalid, is_rich, pack_blocks, plain_of, refused_blocks, rich_of, unpack_blocks, without_blocks,)from ..tgutil import classify_media, esc, explain_rpc, pack_file_id, peer_of, post_linkfrom ..ui import CANCEL, post_labelfrom ..userbot import delete_problem_textfrom .panel import ( check_lengths, is_rich_how, load_post, markup_note, read_native, read_text, show_button_screen, show_panel,)
log = logging.getLogger(__name__)PAGE = 8UPDATED = "β
Updated in the channel."
def register(ctx: Ctx) -> None: client, db = ctx.client, ctx.db
def note_for(post, report=None) -> str: extra = edit_report_text(report) return (UPDATED if post.status == "sent" else "β
Saved.") + (f"\n{extra}" if extra else "")
# ------------------------------------------------------------------ lists async def channel_chooser(event, arg: str = "", page: int = 0) -> None: chans = await db.list_channels() drafts = [[Button.inline("πΎ Drafts (all channels)", "pc:d:0")]] if not chans: await show(event, "π <b>My posts</b>\n\nNo channels yet. Add one with /addchannel.", drafts) return text, kb = picker.render( chans, page, head="π <b>My posts</b> - pick a channel:", kind="ps", choose=lambda c: f"pc:{c.id}:0", extra_rows=drafts ) await show(event, text, kb)
ctx.pickers["ps"] = channel_chooser
@client.on(cmd("posts")) @guard(ctx) async def h_posts(event): await channel_chooser(event)
@on_cb(ctx, "pl") async def cb_channel_chooser(event, parts): await channel_chooser(event)
@on_cb(ctx, "pc") async def cb_list(event, parts): key, page = parts[0], int(parts[1]) if key == "d": cid, status, title = None, "draft", "Drafts" else: cid, status = int(key), None ch = await db.get_channel(cid) title = ch.title if ch else "Channel" rows, total = await db.list_posts(cid, status, page * PAGE, PAGE) pages = max(1, -(-total // PAGE)) if page >= pages: page = pages - 1 rows, total = await db.list_posts(cid, status, page * PAGE, PAGE) kb = [[Button.inline(post_label(p), f"po:{p.id}")] for p in rows] if pages > 1: # "Prev" is always there: on the first page it jumps to the last one nav = [Button.inline("β¬
οΈ Prev", f"pc:{key}:{(page - 1) % pages}"), Button.inline(f"{page + 1}/{pages}", "noop")] if page < pages - 1: nav.append(Button.inline("Next β‘οΈ", f"pc:{key}:{page + 1}")) kb.append(nav) if cid is not None and ctx.cfg.is_owner(event.sender_id): kb.append([Button.inline("π§ Check buttons", f"pk:{cid}")]) kb.append([Button.inline("π Channels", "pl")]) head = f"π <b>{esc(title)}</b> - {total} post(s)" if not rows: head += "\n\nNothing here yet. Create a post with /new." await show(event, head, kb)
@on_cb(ctx, "po") async def cb_open(event, parts): clear_state(ctx, event.sender_id) await show_panel(ctx, event, parts[0])
# ------------------------------------------------------------ text / caption @on_cb(ctx, "et") async def cb_edit_text(event, parts): post, _ = await load_post(ctx, parts[0]) set_state(ctx, event.sender_id, "edit_text", pid=post.id) what = "caption" if post.media_kind else "text" more = "" if post.media_kind else " Rich messages (headings, lists, tables ...) too: /rich." await say(event, f"βοΈ Send the new {what}. Formatting is kept - or type HTML / Markdown (/formatting shows how).{more}", CANCEL)
@on_text(ctx, "edit_text") async def h_edit_text(event, st): m = event.message if classify_media(m): raise UserError("Send text only here. To change the media, use πΌ Media.") post, ch = await load_post(ctx, st["pid"]) native = await read_native(ctx, event) text, entities, how = read_text(m, ctx.cfg.markup_input, native, allow_rich=not post.media_kind) if not post.media_kind and not text.strip() and not is_rich_how(how): raise UserError("A text post can't be empty.") if not is_rich_how(how): check_lengths(text, bool(post.media_kind)) post, report = await apply_edit_reported(ctx, post, ch, text=text, entities=entities) clear_state(ctx, event.sender_id) await show_panel(ctx, event, post.id, note=markup_note(how, "\n") + note_for(post, report), new=True)
# ------------------------------------------------------------------- media @on_cb(ctx, "em") async def cb_edit_media(event, parts): post, _ = await load_post(ctx, parts[0]) if is_rich(post): raise UserError( "A rich message has no media slot. Put pictures into the text itself (see /rich), " "or send new text without rich blocks first." ) set_state(ctx, event.sender_id, "edit_media", pid=post.id) extra = "" if post.media_kind else "\nThe current text becomes its caption." await say(event, f"πΌ Send the new photo / video / GIF / audio / file.{extra}", CANCEL)
@on_text(ctx, "edit_media") async def h_edit_media(event, st): m = event.message if m.grouped_id and st.get("group") == m.grouped_id: return if m.grouped_id: st["group"] = m.grouped_id kind = classify_media(m) if not kind: raise UserError("Send a photo, video, GIF, audio file or document.") post, ch = await load_post(ctx, st["pid"]) check_lengths(post.text or "", True)
async def notify(text: str) -> None: await say(event, text)
post, report = await apply_edit_reported( ctx, post, ch, replace_media=True, notify=notify, media_kind=kind, media_file_id=pack_file_id(m) ) clear_state(ctx, event.sender_id) await show_panel(ctx, event, post.id, note=note_for(post, report), new=True)
@on_cb(ctx, "rm") async def cb_remove_media(event, parts): post, ch = await load_post(ctx, parts[0]) if post.status != "draft": raise UserError("Media can't be removed from a published post - Telegram doesn't allow it.") if not (post.text or "").strip(): raise UserError("Add some text first, then remove the media (a post needs text or media).") await db.update_post(post.id, media_kind=None, media_file_id=None) await show_panel(ctx, event, post.id, note="β
Media removed.")
@on_cb(ctx, "lp") async def cb_link_preview(event, parts): post, ch = await load_post(ctx, parts[0]) post = await apply_edit(ctx, post, ch, link_preview=not post.link_preview) await show_panel(ctx, event, post.id)
# ----------------------------------------------------------------- buttons async def commit_buttons(event, post, ch, rows, *, new_msg: bool = True, note: str = None): post = await apply_edit(ctx, post, ch, buttons=rows) await show_panel(ctx, event, post.id, note=note or note_for(post), new=new_msg) return post
@on_cb(ctx, "ba") async def cb_add_button(event, parts): post, _ = await load_post(ctx, parts[0]) if count(post.buttons) >= 100: raise UserError("A post can have at most 100 buttons.") set_state(ctx, event.sender_id, "btn_add_text", pid=post.id) await say( event, "β Send the button as <code>Button text - link</code>, or just the button text and I'll ask for the link.", CANCEL, )
async def place_button(event, pid, btn: dict) -> None: post, ch = await load_post(ctx, pid) if post.buttons and len(post.buttons[-1]) < MAX_ROW: set_state(ctx, event.sender_id, "btn_place", pid=post.id, btn=btn) await say( event, f"Where should <code>{esc(btn['t'])}</code> go?", [ [Button.inline("β¬οΈ New row", f"bk:{post.id}:n"), Button.inline("β‘οΈ Same row", f"bk:{post.id}:s")], CANCEL[0], ], ) return clear_state(ctx, event.sender_id) await commit_buttons(event, post, ch, add_button(post.buttons, btn, True))
@on_text(ctx, "btn_add_text") async def h_btn_add_text(event, st): txt = (event.raw_text or "").strip() if not txt: raise UserError("Send the button text.") try: rows = parse_buttons_text(txt) except ValueError: rows = [] if rows: if len(rows) == 1 and len(rows[0]) == 1: await place_button(event, st["pid"], rows[0][0]) return raise UserError("That's several buttons. Send one at a time, or use π Set buttons to replace them all.") if len(txt) > 64: raise UserError("Keep the button text under 64 characters.") set_state(ctx, event.sender_id, "btn_add_url", pid=st["pid"], text=txt) await say(event, f"π Now send the link for <code>{esc(txt)}</code>.", CANCEL)
@on_text(ctx, "btn_add_url") async def h_btn_add_url(event, st): url = norm_url(event.raw_text or "") if not url: raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc") await place_button(event, st["pid"], {"t": st["text"], "u": url})
@on_cb(ctx, "bk") async def cb_place(event, parts): st = ctx.state.get(event.sender_id) if not st or st.get("mode") != "btn_place" or str(st.get("pid")) != parts[0]: raise UserError("That step expired. Tap β Button again.") post, ch = await load_post(ctx, parts[0]) rows = add_button(post.buttons, st["btn"], new_row=(parts[1] == "n")) clear_state(ctx, event.sender_id) await commit_buttons(event, post, ch, rows, new_msg=False)
@on_cb(ctx, "bp") async def cb_paste(event, parts): post, _ = await load_post(ctx, parts[0]) set_state(ctx, event.sender_id, "btn_paste", pid=post.id) warn = "" if any(b.get("raw") for r in post.buttons for b in r): warn = "\nβ οΈ This also removes buttons made by other bots (like reactions)." await say( event, "π Send <b>all</b> the buttons - one row per line as <code>Text - link</code>, " "with <code> | </code> between buttons in one row. This replaces the current buttons." + warn, CANCEL, )
@on_text(ctx, "btn_paste") async def h_btn_paste(event, st): try: rows = parse_buttons_text(event.raw_text or "") except ValueError as e: raise UserError(f"β {e}\n\nTry again.") if not rows: raise UserError("Send at least one button as βText - linkβ.") post, ch = await load_post(ctx, st["pid"]) clear_state(ctx, event.sender_id) await commit_buttons(event, post, ch, rows)
@on_cb(ctx, "bc") async def cb_clear(event, parts): await show( event, "Remove <b>all</b> buttons from this post?", [[Button.inline("π§Ή Yes, remove", f"bcy:{parts[0]}"), Button.inline("β©οΈ Back", f"po:{parts[0]}")]], )
@on_cb(ctx, "bcy") async def cb_clear_yes(event, parts): post, ch = await load_post(ctx, parts[0]) await commit_buttons(event, post, ch, [], new_msg=False)
@on_cb(ctx, "bs") async def cb_select(event, parts): clear_state(ctx, event.sender_id) await show_button_screen(ctx, event, parts[0], int(parts[1]), int(parts[2]))
@on_cb(ctx, "bt") async def cb_btn_text(event, parts): set_state(ctx, event.sender_id, "btn_text", pid=parts[0], r=int(parts[1]), c=int(parts[2])) await say(event, "βοΈ Send the new button text.", CANCEL)
@on_text(ctx, "btn_text") async def h_btn_text(event, st): txt = (event.raw_text or "").strip() if not txt: raise UserError("Send the new button text.") if len(txt) > 64: raise UserError("Keep the button text under 64 characters.") post, ch = await load_post(ctx, st["pid"]) if not valid(post.buttons, st["r"], st["c"]): raise UserError("That button no longer exists.") post = await apply_edit(ctx, post, ch, buttons=set_field(post.buttons, st["r"], st["c"], t=txt)) clear_state(ctx, event.sender_id) await show_button_screen(ctx, event, post.id, st["r"], st["c"], new=True)
@on_cb(ctx, "bu") async def cb_btn_url(event, parts): set_state(ctx, event.sender_id, "btn_url", pid=parts[0], r=int(parts[1]), c=int(parts[2])) await say(event, "π Send the new link for this button.", CANCEL)
@on_text(ctx, "btn_url") async def h_btn_url(event, st): url = norm_url(event.raw_text or "") if not url: raise UserError("That doesn't look like a link. Send something like https://t.me/yourbot?start=abc") post, ch = await load_post(ctx, st["pid"]) if not valid(post.buttons, st["r"], st["c"]): raise UserError("That button no longer exists.") post = await apply_edit(ctx, post, ch, buttons=set_field(post.buttons, st["r"], st["c"], u=url)) clear_state(ctx, event.sender_id) await show_button_screen(ctx, event, post.id, st["r"], st["c"], new=True)
@on_cb(ctx, "bm") async def cb_move(event, parts): pid, r, c, d = parts[0], int(parts[1]), int(parts[2]), parts[3] post, ch = await load_post(ctx, pid) rows, nr, nc = move_button(post.buttons, r, c, d) if rows == post.buttons: return # already at the edge post = await apply_edit(ctx, post, ch, buttons=rows) await show_button_screen(ctx, event, post.id, nr, nc)
@on_cb(ctx, "bd") async def cb_btn_delete(event, parts): post, ch = await load_post(ctx, parts[0]) rows = delete_button(post.buttons, int(parts[1]), int(parts[2])) await commit_buttons(event, post, ch, rows, new_msg=False)
# ------------------------------------------------------- preview / publish async def rich_refusal(event, post, e, typed: str, tail: str = "") -> None: """Telegram refused to make a rich message of the post: say why.
A rich message that was typed (HTML / Markdown) is Telegram's to read: `typed` tells the owner to check the syntax. One that was made in Telegram and sent to the bot is kept block by block, and Telegram does not say which block it dislikes - so the blocks are tried out, in the owner's chat and quietly, to tell which ones it won't take (see richmsg.refused_blocks). A draft can then go on without those: the βοΈ button. `tail` closes the message.""" rich = rich_of(post) head = "β " + explain_rpc(e) if rich is None or rich.fmt != "blocks": raise UserError(f"{head}\n{typed}") if not is_block_invalid(e): raise UserError(f"{head}\nTelegram could not make that rich message.\n{tail}".strip()) bad = await refused_blocks(client, await event.get_input_chat(), rich) if not bad: raise UserError( f"{head}\nI could not tell which block it is - /rich shows how to type the message as HTML / Markdown instead.\n{tail}".strip() ) if len(bad) >= block_count(rich): raise UserError( 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() ) lines = [ esc(head), f"It won't take these blocks (of {block_count(rich)}): {esc(block_labels(rich, bad))}. The others are fine.", ] if tail: lines.append(esc(tail)) buttons = [] if post.status == "draft": lines.append("βοΈ <b>Leave those out</b> keeps the rest of the message as the post.") buttons.append([Button.inline("βοΈ Leave those out", f"rx:{post.id}:{digest(rich)}:{pack_blocks(bad)}")]) buttons.append([Button.inline("β©οΈ Back", f"po:{post.id}")]) await say(event, "\n".join(lines), buttons)
@on_cb(ctx, "rx") async def cb_leave_out(event, parts): post, ch = await load_post(ctx, parts[0]) rich = rich_of(post) if post.status != "draft" or rich is None or rich.fmt != "blocks" or parts[1] != digest(rich): raise UserError("The post is not the one that was checked any more - press π Preview again.") total = block_count(rich) drop = [i for i in unpack_blocks(parts[2]) if i < total] if not drop: raise UserError("Those blocks are not in the post any more.") if len(drop) >= total: raise UserError("Nothing would be left of the message. Send it again in another form, or as HTML / Markdown (/rich).") kept = without_blocks(rich, drop) post = await apply_edit(ctx, post, ch, text=plain_of(kept), entities=[rich_entry(kept)]) await show_panel(ctx, event, post.id, note=f"βοΈ Left out: {esc(block_labels(rich, drop))}.\nπ Preview shows what is left.")
@on_cb(ctx, "pv") async def cb_preview(event, parts): post, _ = await load_post(ctx, parts[0]) if not (post.text or "").strip() and not post.media_file_id and not is_rich(post): raise UserError("The post is empty.") try: await send_post(client, await event.get_input_chat(), post) except errors.RPCError as e: if not is_rich(post): raise await rich_refusal(event, post, e, typed="Telegram could not make that rich message - see /rich for the syntax.") return miss = missing_links(post.buttons) if miss: await say(event, f"π Preview. β οΈ {miss} button(s) without a link are not shown.")
@on_cb(ctx, "pb") async def cb_publish(event, parts): post, ch = await load_post(ctx, parts[0]) if post.status != "draft": raise UserError("This post is already published.") if missing_links(post.buttons): raise UserError("Some buttons (β οΈ) have no link yet. Open them and add a link first.") if not (post.text or "").strip() and not post.media_file_id and not is_rich(post): raise UserError("The post is empty.") await show( event, f"Publish this post to <b>{esc(ch.title)}</b>?", [[Button.inline("π Yes, publish", f"pby:{post.id}"), Button.inline("β©οΈ Back", f"po:{post.id}")]], )
@on_cb(ctx, "pby") async def cb_publish_yes(event, parts): post, ch = await load_post(ctx, parts[0]) if post.status != "draft": raise UserError("This post is already published.") try: sent = await send_post(client, peer_of(ch), post) except errors.RPCError as e: if is_rich(post): await rich_refusal(event, post, e, typed="The post was NOT published.", tail="The post was NOT published.") return raise UserError("β " + explain_rpc(e) + "\nThe post was NOT published.") await db.release_slot(ch.id, sent.id, keep_pid=post.id) # the sync may have picked the message up a moment ago post = await db.update_post(post.id, status="sent", message_id=sent.id, sent_at=utcnow()) await show( event, f"β
<b>Published</b> in <b>{esc(ch.title)}</b>\n<a href=\"{post_link(ch, sent.id)}\">Open the post</a>", [ [Button.inline("π Manage this post", f"po:{post.id}")], [Button.inline("β New post", f"nc:{ch.id}")], ], )
# ----------------------------------------------------------------- delete @on_cb(ctx, "dl") async def cb_delete(event, parts): post, ch = await load_post(ctx, parts[0]) back = Button.inline("β©οΈ Back", f"po:{post.id}") if post.status == "draft": await show(event, "Discard this draft?", [[Button.inline("π Yes, discard", f"dly:{post.id}:b"), back]]) return await show( event, f"Delete this post from <b>{esc(ch.title)}</b>?\n\n" "π <b>Delete from channel</b> - deletes it in the channel and removes it, with its data, from My posts.\n" "π§Ή <b>Only forget it in the bot</b> - the post stays in the channel; only My posts forgets it.", [ [Button.inline("π Delete from channel", f"dly:{post.id}:a")], [Button.inline("π§Ή Only forget it in the bot", f"dly:{post.id}:b")], [back], ], )
@on_cb(ctx, "dly") async def cb_delete_yes(event, parts): post, ch = await load_post(ctx, parts[0]) note = "π Done." if post.status == "sent" and parts[1] == "a": # The bot deletes the post; where Telegram refuses it (an age limit on old posts, a missing right) the userbot # takes over at once - nothing is asked first. fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None) try: out = await delete_batch(client, peer_of(ch), [post.message_id], fallback) finally: if deleter is not None: await deleter.close() if post.message_id not in out.gone: why = delete_problem_text( ctx.userbot, bot_error=out.bot_error, fallback_error=out.fallback_error, tried=out.tried_userbot ) raise UserError( f"Telegram did not delete that message. {why}\n" "The post is still in My posts. Delete it by hand in the channel, then use βOnly forget it in the botβ." ) # gone from the channel: it goes from My posts too, with what hangs on it (a timed deletion ...) await db.forget_posts(post.channel_id, [post.message_id]) note = "π Done - deleted in the channel and removed from My posts." if out.by_userbot: note += "\nThe bot was not allowed to delete it, so the userbot did." if post.status == "sent" and post.message_id and parts[1] == "b": ctx.sync_ignore.add((post.channel_id, post.message_id)) # forgotten on purpose: the sync must not bring it back await db.ignore_post(post.channel_id, post.message_id) # ... not even after a restart await db.delete_post(post.id) await show(event, note, [[Button.inline("π My posts", "pl")]])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502"""/replace media, /swap links, /handleswap and /undo (owner only)."""from __future__ import annotations
import loggingimport reimport secretsimport timefrom dataclasses import dataclass, fieldfrom urllib.parse import urlparse
from telethon import Button, errors
from ..common import ( Ctx, UserError, apply_edit_reported, cmd, edit_callback_message, edit_report_text, guard, on_cb, purge_pending, require_owner, say, show,)from ..linkswap import normalize_usernamefrom ..replace_engine import ApplyResult, ChannelScan, ScanOptions, apply_channel, scan_channel, undo_batchfrom ..richmsg import is_richfrom ..richtext import message_textfrom ..sync_engine import SyncOptions, sync_idsfrom ..tgutil import classify_media, esc, explain_rpc, get_rights, pack_file_idfrom ..channelref import parse_channel_reffrom .panel import check_lengths, markup_note
log = logging.getLogger(__name__)
USAGE = ( "Usage: <code>/swap @old @new</code>\n" "Options: <code>--channel @name</code> (only that channel), <code>--last 200</code> (only the newest 200 " "post ids), <code>--posts</code> (also change t.me/old/123 post links), <code>--no-typed</code> (don't touch " "links typed in the text).")
USAGE_HANDLES = ( "Usage: <code>/handleswap @old @new</code>\n" "Finds the posts that mention the username <code>@old</code> (in their text or caption, and in button names) in all " "channels and changes it to <code>@new</code>. Only usernames change: links, hyperlinks and button links are left alone.\n" "Options: <code>--channel @name</code> (only that channel), <code>--last 200</code> (only the newest 200 post ids).")HANDLE_PREFIX = "hs" # ids of /handleswap runs start with this, so /undo can word its question right
@dataclassclass Job: user: int opts: ScanOptions scans: list running: bool = False created: float = field(default_factory=time.monotonic)
def parse_replace_args(raw: str, *, handles: bool = False) -> tuple: toks = (raw or "").split() flags = {"channel": None, "last": None, "posts": False, "typed": None} pos: list = [] i = 0 while i < len(toks): t = toks[i] if t == "--channel" and i + 1 < len(toks): flags["channel"] = toks[i + 1] i += 2 elif t == "--last" and i + 1 < len(toks): if not toks[i + 1].isdigit() or int(toks[i + 1]) < 1: raise ValueError("--last needs a number, for example --last 200") flags["last"] = int(toks[i + 1]) i += 2 elif t == "--posts" and not handles: flags["posts"] = True i += 1 elif t == "--no-typed" and not handles: flags["typed"] = False i += 1 elif t.startswith("--"): raise ValueError(f"Unknown option {t}") else: pos.append(t) i += 1 if len(pos) != 2: raise ValueError("Give the old and the new username.") old, new = normalize_username(pos[0]), normalize_username(pos[1]) if not old or not new: raise ValueError("Usernames look like @name (letters, digits and underscores).") if old.lower() == new.lower(): raise ValueError("The old and the new username are the same.") return old, new, flags
def pick_channels(chans: list, ref) -> list: if not ref: return chans r = parse_channel_ref(ref) 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())] if not out: raise ValueError("That channel isn't registered (see /channels).") return out
def parse_post_link(value: str): """Return (public username or private channel id, message id) for Telegram post links.""" try: u = urlparse(value if "://" in value else "https://" + value) bits = [x for x in u.path.strip("/").split("/") if x] if u.netloc.lower() not in {"t.me", "www.t.me", "telegram.me", "www.telegram.me"}: return None if bits and bits[0] == "c" and len(bits) == 3 and bits[1].isdigit() and bits[2].isdigit(): # Telegram's t.me/c URL uses the same positive channel ID stored by Telethon and in our database. return int(bits[1]), int(bits[2]) if bits and bits[0] == "s": bits = bits[1:] if len(bits) == 2 and bits[1].isdigit() and re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{3,}", bits[0]): return bits[0].lower(), int(bits[1]) except Exception: pass return None
def handles_summary(job: Job) -> str: o = job.opts lines = [f"π <b>Scan finished</b> - swap the username <code>@{esc(o.old)}</code> β <code>@{esc(o.new)}</code>"] total = 0 for s in job.scans: head = f"\n<b>{esc(s.channel.title)}</b>" if s.error: lines.append(f"{head}\nβ οΈ {esc(s.error)}") continue block = f"{head} - looked at post ids {s.first}-{s.scanned}" if s.total == 0: block += "\nNothing to change." else: t = sum(i.typed for i in s.infos.values()) b = sum(i.buttons for i in s.infos.values()) what = f"{t} mention(s) in the text" + (f", {b} in button names" if b else "") block += f"\n{s.total} post(s) to change: {what}" if s.foreign: block += f"\nβ’ {s.foreign} of them were not posted by this bot" cb = sum(1 for i in s.infos.values() if i.callbacks) if cb: block += f"\nβ’ {cb} carry other bots' buttons (e.g. reactions) - those stay as they are" if s.skipped_post_links: block += f"\nβ’ left {s.skipped_post_links} mention(s) that are part of a link alone" if s.not_editable: block += f"\nβ οΈ {s.not_editable} post(s) by others can't be edited: the bot lacks βEdit messages of othersβ here" total += s.total lines.append(block) lines.append(f"\n<b>Total: {total} post(s).</b>") if total: lines.append("Nothing has been changed yet. Every edit is logged, so /undo can restore the old versions.") return "\n".join(lines)
def summary_text(job: Job) -> str: if job.opts.mode == "handles": return handles_summary(job) o = job.opts lines = [f"π <b>Scan finished</b> - replace <code>@{esc(o.old)}</code> β <code>@{esc(o.new)}</code>"] total = 0 for s in job.scans: head = f"\n<b>{esc(s.channel.title)}</b>" if s.error: lines.append(f"{head}\nβ οΈ {esc(s.error)}") continue block = f"{head} - looked at post ids {s.first}-{s.scanned}" if s.total == 0: block += "\nNothing to change." else: b = sum(i.buttons for i in s.infos.values()) h = sum(i.links for i in s.infos.values()) t = sum(i.typed for i in s.infos.values()) block += f"\n{s.total} post(s) to change: {b} button link(s), {h} hyperlink(s), {t} typed link(s)" if s.foreign: block += f"\nβ’ {s.foreign} of them were not posted by this bot" fb = sum(1 for i in s.infos.values() if not i.mine and i.buttons) if fb: 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" cb = sum(1 for i in s.infos.values() if i.callbacks) if cb: block += f"\nβ’ {cb} carry other bots' buttons (e.g. reactions) - those stay as they are" if s.skipped_post_links: block += f"\nβ’ skipped {s.skipped_post_links} link(s) to channel posts (t.me/{o.old}/123) - use --posts to change them too" if s.not_editable: block += f"\nβ οΈ {s.not_editable} post(s) by others can't be edited: the bot lacks βEdit messages of othersβ here" total += s.total lines.append(block) lines.append(f"\n<b>Total: {total} post(s).</b>") if total: lines.append("Nothing has been changed yet. Every edit is logged, so /undo can restore the old versions.") return "\n".join(lines)
def register(ctx: Ctx) -> None: client, db, cfg = ctx.client, ctx.db, ctx.cfg lock = ctx.lock
def make_updater(event): last = [0.0]
async def upd(text: str, force: bool = False) -> None: now = time.monotonic() if not force and now - last[0] < 3: return last[0] = now try: await edit_callback_message(event, text) except errors.MessageNotModifiedError: pass except Exception: log.debug("progress update failed", exc_info=True)
return upd
# ------------------------------------------------------------------ /replace media @client.on(cmd("replace", args=True)) @guard(ctx, owner=True) async def h_replace(event): purge_pending(ctx) raw = (event.pattern_match.group(1) or "").strip() if not raw: await say(event, "Reply to a new photo, video, or file with <code>/replace <channel post link></code>.") return # File replacement mode: reply to a media message with /replace <link to the saved post>. link_bits = parse_post_link(raw) if len(raw.split()) == 1 else None if link_bits: reply = await event.get_reply_message() if reply is None: raise UserError("Reply to the new photo, video, or file, then send /replace <channel post link>.") kind = classify_media(reply) if not kind: raise UserError("The replied-to message must contain a photo, video, GIF, audio file, or document.") ref, message_id = link_bits channels = await db.list_channels() channel = next((c for c in channels if c.id == ref), None) if isinstance(ref, int) else next( (c for c in channels if (c.username or "").lower() == ref), None ) if channel is None: raise UserError("That post link is not from a registered channel. Check /channels.") post = await db.find_by_message(channel.id, message_id) if post is None: report = await sync_ids( ctx.client, db, channel, [message_id], SyncOptions(history=False, grace=0, delete_services=False, ignore=ctx.sync_ignore), adopt_ids={message_id}, ) post = await db.find_by_message(channel.id, message_id) if post is None: if report.error: raise UserError(f"I couldn't read that post: {report.error}") if report.restricted: raise UserError("Telegram is currently holding that post back, so I can't replace its media.") if report.unsupported: raise UserError("That post can't be saved in My posts, so its media can't be replaced here.") raise UserError("That post no longer exists in the channel, or I can't add it to My posts.") if post.status != "sent": raise UserError("That post is not published yet.") if is_rich(post): raise UserError("That post is a rich message - it has no media or caption to replace. Edit its text in My posts.") caption, entities, how = message_text(reply, cfg.markup_input) # Telegram's formatting, or HTML / Markdown check_lengths(caption, True)
async def notify(text: str) -> None: await say(event, text)
_, report = await apply_edit_reported( ctx, post, channel, replace_media=True, notify=notify, media_kind=kind, media_file_id=pack_file_id(reply), text=caption, entities=entities, ) extra = edit_report_text(report) await say( event, markup_note(how) + f"β
Replaced the media in <b>{esc(channel.title)}</b> and updated My posts." + (f"\n{extra}" if extra else ""), ) return raise UserError("Use /replace with a channel post link, replying to the new media. Username swaps use /swap.")
# ------------------------------------------------------------------ /swap usernames in links @client.on(cmd("swap", args=True)) @guard(ctx, owner=True) async def h_swap(event): purge_pending(ctx) raw = (event.pattern_match.group(1) or "").strip() if not raw: await say(event, USAGE) return try: old, new, flags = parse_replace_args(raw) chans = pick_channels(await db.list_channels(), flags["channel"]) except ValueError as e: raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE)) if not chans: raise UserError("No channels registered yet. Use /addchannel.") opts = ScanOptions( old=old, new=new, include_typed=cfg.replace_typed_links if flags["typed"] is None else flags["typed"], include_posts=flags["posts"], last=flags["last"], ) await begin_scan(event, opts, chans)
# ---------------------------------------------------------------- /handleswap @client.on(cmd("handleswap", args=True)) @guard(ctx, owner=True) async def h_handleswap(event): purge_pending(ctx) raw = (event.pattern_match.group(1) or "").strip() if not raw: await say(event, USAGE_HANDLES) return try: old, new, flags = parse_replace_args(raw, handles=True) chans = pick_channels(await db.list_channels(), flags["channel"]) except ValueError as e: raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE_HANDLES)) if not chans: raise UserError("No channels registered yet. Use /addchannel.") await begin_scan(event, ScanOptions(old=old, new=new, last=flags["last"], mode="handles"), chans)
async def begin_scan(event, opts, chans) -> None: """Read the channels, show what would change and wait for the owner's yes.""" if lock.locked(): raise UserError("Another /swap, /handleswap or /undo is still running - wait for it to finish.") async with lock: status = await say(event, f"π Scanning {len(chans)} channel(s)β¦") last_edit = [0.0] scans = [] for ch in chans: rights = await get_rights(client, ch) if rights is not None and not rights.admin: s = await _empty_scan(ch, "The bot is not an admin here any more.") scans.append(s) continue can_edit = True if rights is None else rights.edit
async def prog(scan, title=ch.title): now = time.monotonic() if now - last_edit[0] < 3: return last_edit[0] = now try: await status.edit(f"π Scanning <b>{esc(title)}</b>: post id {scan.scanned} of {scan.top or '?'}β¦") except Exception: pass
try: scan = await scan_channel( client, ch, opts, can_edit_others=can_edit, mine_ids=await db.mine_message_ids(ch.id), progress=prog ) except errors.RPCError as e: scan = await _empty_scan(ch, explain_rpc(e)) scan.rights = rights scans.append(scan) job = Job(user=event.sender_id, opts=opts, scans=scans) token = secrets.token_hex(4) ctx.pending[token] = job total = sum(s.total for s in scans) kb = None if total: kb = [[Button.inline(f"β
Apply to {total} post(s)", f"rp:{token}:y"), Button.inline("βοΈ Cancel", f"rp:{token}:n")]] try: await status.edit(summary_text(job), buttons=kb, link_preview=False) except Exception: await say(event, summary_text(job), kb)
async def _empty_scan(ch, error: str): return ChannelScan(channel=ch, error=error)
@on_cb(ctx, "rp") async def cb_replace(event, parts): require_owner(ctx, event) token, action = parts[0], parts[1] job = ctx.pending.get(token) if not isinstance(job, Job) or job.user != event.sender_id: raise UserError("That scan has expired. Run /swap again.") if action == "n": ctx.pending.pop(token, None) await show(event, "Cancelled - nothing was changed.") return if job.running or lock.locked(): raise UserError("It is already running.") job.running = True upd = make_updater(event) o = job.opts batch_id = (HANDLE_PREFIX if o.mode == "handles" else "") + secrets.token_hex(6) totals = ApplyResult() stopped: list = [] async with lock: await db.create_batch(batch_id, o.old, o.new, event.sender_id) todo = sum(s.total for s in job.scans) done_before = 0 for s in job.scans: if not s.infos: continue
async def prog(res, s=s, base=done_before): await upd(f"β³ <b>{esc(s.channel.title)}</b> - {base + res.edited}/{todo} editedβ¦")
try: res = await apply_channel( client, db, s, o, batch_id, event.sender_id, edit_delay=cfg.edit_delay, progress=prog ) except Exception as e: log.exception("apply failed in %s", s.channel.id) totals.failed.append((0, f"{s.channel.title}: {type(e).__name__}")) continue done_before += res.edited totals.edited += res.edited totals.unchanged += res.unchanged totals.missing += res.missing totals.no_perm += res.no_perm totals.failed += res.failed if res.aborted: stopped.append((s.channel.title, res.aborted)) ctx.pending.pop(token, None) what = "username swap " if o.mode == "handles" else "" lines = [f"β
<b>Done</b> - {what}<code>@{esc(o.old)}</code> β <code>@{esc(o.new)}</code>", f"β’ edited: <b>{totals.edited}</b>"] if totals.unchanged: lines.append(f"β’ already fine / changed meanwhile: {totals.unchanged}") if totals.missing: lines.append(f"β’ deleted meanwhile: {totals.missing}") if totals.no_perm: lines.append(f"β’ skipped (no permission): {totals.no_perm}") if totals.failed: sample = ", ".join(f"#{m} {esc(n)}" for m, n in totals.failed[:8]) lines.append(f"β’ <b>failed: {len(totals.failed)}</b> ({sample}{'β¦' if len(totals.failed) > 8 else ''})") names = {n for _, n in totals.failed} if names & {"MessageAuthorRequiredError", "InlineBotRequiredError", "ChatAdminRequiredError", "MessageIdInvalidError"}: lines.append( " Telegram doesn't let this bot edit those posts." + ("" if o.mode == "handles" else " Use /repost to post them again with the new links.") ) for title, name in stopped: lines.append(f"β οΈ Stopped early in <b>{esc(title)}</b>: Telegram refused 5 edits in a row ({esc(name)}).") undo_label = "β©οΈ Undo this swap" if o.mode == "handles" else "β©οΈ Undo this replace" kb = [[Button.inline(undo_label, f"ruc:{batch_id}")]] if totals.edited else None if kb: try: await edit_callback_message(event, "\n".join(lines), kb) except errors.MessageNotModifiedError: pass else: await upd("\n".join(lines), force=True)
# -------------------------------------------------------------------- /undo async def ask_undo(event, batch) -> None: n = await db.count_batch_changes(batch.id) what = "username swap" if batch.id.startswith(HANDLE_PREFIX) else "replace" await say( event, f"β©οΈ Undo the {what} <code>@{esc(batch.old_username)}</code> β <code>@{esc(batch.new_username)}</code>?\n" f"{n} post(s) will be put back exactly as they were before.", [[Button.inline("β
Yes, undo", f"ru:{batch.id}"), Button.inline("βοΈ No", "cx")]], )
@client.on(cmd("undo")) @guard(ctx, owner=True) async def h_undo(event): batch = await db.last_batch() if batch is None: raise UserError("There is nothing to undo - no /swap or /handleswap run yet.") await ask_undo(event, batch)
@on_cb(ctx, "ruc") async def cb_undo_ask(event, parts): require_owner(ctx, event) batch = await db.get_batch(parts[0]) if batch is None or batch.undone: raise UserError("That replace was already undone.") await ask_undo(event, batch)
@on_cb(ctx, "ru") async def cb_undo(event, parts): require_owner(ctx, event) if lock.locked(): raise UserError("Another /swap, /handleswap or /undo is still running.") upd = make_updater(event) async with lock: await upd("β³ Restoringβ¦", force=True)
async def prog(res): await upd(f"ⳠRestoring⦠{res.restored} done")
res = await undo_batch(client, db, parts[0], edit_delay=cfg.edit_delay, progress=prog) text = f"β©οΈ Restored <b>{res.restored}</b> post(s)." if res.failed: text += f"\nβ οΈ {len(res.failed)} could not be restored (" + ", ".join(f"#{m} {esc(n)}" for m, n in res.failed[:6]) + ")." await upd(text, force=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820"""/repost: copy a whole channel in order (links swapped on the way), then remove the old posts. Owner only."""from __future__ import annotations
import loggingimport reimport secretsimport timefrom dataclasses import dataclass, field
from telethon import Button, errors
from .. import pickerfrom ..common import Ctx, UserError, cmd, edit_callback_message, guard, on_cb, purge_pending, require_owner, say, showfrom ..crosslinks import CrossResult, progress_text, relink_after_repost, report_lines, restore_after_undofrom ..linkswap import normalize_usernamefrom ..profile_copy import profile_linesfrom ..repost_engine import RepostOptions, RepostPlan, delete_copies, plan_repost, run_repost, saved_lookupfrom ..tgutil import esc, get_rights, post_linkfrom ..userbot import delete_problem_text
log = logging.getLogger(__name__)
USAGE = ( "Usage: <code>/repost @old @new</code>\n" "Copies every post of a channel, in order, to the end of the channel and swaps the username inside " "t.me links on the way. Leave out the usernames to copy without changing links. " "You pick the channel with buttons afterwards.\n" "Options: <code>--last 5</code> (trial: only the newest 5 post ids), " "<code>--posts</code> (also change t.me/old/123 post links), <code>--no-typed</code>.\n\n" "Links to the old posts - in this channel and in all your other connected channels - are pointed at the copies " "afterwards.\n" "Nothing is deleted by /repost itself: you decide about the old posts after checking the copies.")
@dataclassclass RepostChoice: """/repost was typed; the owner still has to pick the channel."""
user: int opts: RepostOptions created: float = field(default_factory=time.monotonic)
@dataclassclass RepostJob: user: int ch: object opts: RepostOptions plan: object = None running: bool = False stop: bool = False mig_id: str = "" created: float = field(default_factory=time.monotonic)
def parse_repost_args(raw: str) -> tuple: toks = (raw or "").split() flags = {"last": None, "posts": False, "typed": None} pos: list = [] i = 0 while i < len(toks): t = toks[i] if t == "--channel": raise ValueError("/repost no longer takes --channel: send the command without it and pick the channel with the buttons.") elif t == "--last" and i + 1 < len(toks): if not toks[i + 1].isdigit() or int(toks[i + 1]) < 1: raise ValueError("--last needs a number, for example --last 5") flags["last"] = int(toks[i + 1]) i += 2 elif t == "--posts": flags["posts"] = True i += 1 elif t == "--no-typed": flags["typed"] = False i += 1 elif t.startswith("--"): raise ValueError(f"Unknown option {t}") else: pos.append(t) i += 1 old = new = None if pos: if len(pos) != 2: raise ValueError("Give both usernames (@old @new), or none to copy without changing links.") old, new = normalize_username(pos[0]), normalize_username(pos[1]) if not old or not new: raise ValueError("Usernames look like @name (letters, digits and underscores).") if old.lower() == new.lower(): raise ValueError("The old and the new username are the same.") return old, new, flags
def plan_text(p: RepostPlan, o: RepostOptions, title: str, delay: float) -> str: kinds = f"{p.text} text, {p.media} media" if p.polls: kinds += f", {p.polls} poll(s)" if p.other: kinds += f", {p.other} other" lines = [ f"π§± <b>Repost plan - {esc(title)}</b>", f"Post ids {p.first}-{p.last}: <b>{p.units} posts</b> to copy ({p.messages} messages, {p.albums} album(s)) - {kinds}", ] if p.service: lines.append(f"β’ {p.service} service message(s) (like βpinned a messageβ) can't be copied and are skipped") if p.polls: lines.append("β’ polls are copied without their votes") if o.swaps: lines.append( f"β’ <code>@{esc(o.old)}</code> β <code>@{esc(o.new)}</code> in {p.link_posts} post(s): " f"{p.n_buttons} button link(s), {p.n_links} hyperlink(s), {p.n_typed} typed link(s)" ) if p.dropped_posts: lines.append(f"β’ {p.dropped_posts} post(s) carry other bots' buttons (reactions...) - those are not copied") lines += held_plan_lines(p, title) if p.post_links: lines.append( f"β’ {p.post_links} link(s) in {p.post_link_posts} post(s) point at other posts of this channel: " "they are pointed at the new copies (a link to a post that doesn't exist stays as it is)" ) lines.append( "β’ afterwards every link to an old post - a hyperlink, a typed link or a button, in ANY of your connected " "channels - is pointed at the copy (the old posts themselves are not touched)" ) if p.replies: lines.append(f"β’ {p.replies} post(s) answer another post: each copy answers the copy of that post") if p.pinned: lines.append( f"β’ {p.pinned} pinned post(s): their copies are pinned at the end " "(the bot needs the βEdit messages of othersβ right for that)" ) minutes = max(1, round(p.eta_seconds(delay) / 60)) lines += [ "", "<b>How:</b> posts without buttons, replies or links to change are copied by Telegram itself, so they stay " "exactly as they are. Posts with buttons, links to change or a reply are posted again with their text, " "formatting, media and buttons in one go, and each one is read back to make sure its buttons are really " "there. Copies go to the end of the channel silently, in the original order, and are registered in My posts.", "", "<b>Not kept:</b> original dates, view counts, reactions, comments and poll votes.", f"Time: about {minutes} min. Please don't post in the channel meanwhile.", "<b>Nothing is deleted in this step.</b>", ] if p.partial: lines.append("Trial run: afterwards you can remove the copies again.") return "\n".join(lines)
def held_plan_lines(p: RepostPlan, title: str, *, shift: bool = False) -> list: """Plan lines about posts Telegram restricts (a copyright strike: the channel is "unavailable", or its posts are marked or shown as a notice).""" lines = [] name = esc(title) said = f" (β{esc(p.held_why)}β)" if p.held_why else "" if p.channel_restricted and shift: lines.append(f"β’ β οΈ Telegram restricts {name} itself: β{esc(p.channel_restricted)}β") elif p.channel_restricted: lines.append( f"β’ β οΈ Telegram restricts {name} itself: β{esc(p.channel_restricted)}β. Telegram may hide what is posted into " "such a channel as well, so a repost here may not bring the posts back. To save a struck channel use " "/shift: it copies the posts from My posts into another channel." ) if p.held_saved and p.no_media: lines.append( f"β’ π {p.held_saved} post(s) of {name} are restricted by Telegram{said}. They are copied from what My posts " "saved of them - text, formatting and buttons - not from what Telegram shows now." ) elif p.held_saved: lines.append( f"β’ π {p.held_saved} post(s) of {name} are restricted by Telegram{said}. They are copied from what My posts " "saved of them - text, formatting, buttons and media - not from what Telegram shows now (a file that " "Telegram refuses goes out without it)." ) if p.live_restricted and shift: lines.append( f"β’ β οΈ {p.live_restricted} restricted post(s) of {name} have no saved copy in My posts, but Telegram still " "hands out their content, so they are copied as they are now." ) elif p.live_restricted: lines.append( f"β’ β οΈ Telegram marks {p.live_restricted} post(s) of {name} as restricted but still hands out their content, " "so they are copied as they are now." ) if p.held_skipped and shift: lines.append( f"β’ β οΈ Telegram shows only its notice for {p.held_skipped} more post(s) of {name}{said} and My posts has no " "saved copy of them, so they are skipped and the shift will show as not complete. If you have a backup made " "before that, put it back with /import and run /shift again." ) elif p.held_skipped: lines.append( f"β’ β οΈ Telegram holds back {p.held_skipped} post(s) of {name}{said} - it shows a notice instead of them. " "Copying the notice would be wrong, so they are skipped, and the old posts can't be deleted afterwards " "(the repost will show as not complete)." ) if p.channel_restricted or p.held_saved or p.live_restricted: lines.append("β’ The new posts are read back: if Telegram itself hides them, the report says so.") return lines
def held_notes(res) -> list: """Lines about the posts Telegram restricts, for the end of a repost or shift.""" notes = []
def sample(ids, n=8): return ", ".join(f"#{i}" for i in ids[:n]) + ("β¦" if len(ids) > n else "")
what = "text, formatting and buttons" if getattr(res, "no_media", False) else "text, formatting, buttons and media" if res.from_db: if res.from_saved: notes.append( f"π The source can't be read, so {res.from_saved} post(s) were copied from what My posts saved of them: " f"{what} - without replies, pins and albums." ) elif res.from_saved: notes.append( f"π {res.from_saved} post(s) are restricted by Telegram. They were copied from what My posts saved of " f"them: {what}." ) if res.media_lost: notes.append( f"β οΈ {len(res.media_lost)} of them went out without their media, because Telegram refuses the saved file " f"({sample(res.media_lost)})." ) if res.live_restricted and res.used_saved: notes.append( f"β οΈ {res.live_restricted} restricted post(s) had no saved copy in My posts, so they were copied as Telegram " "hands them out (their content was intact)." ) elif res.live_restricted: notes.append( f"β οΈ Telegram marks {res.live_restricted} post(s) as restricted but still handed out their content, so they " "were copied as they are." ) if res.held_back and res.used_saved: notes.append( f"β οΈ {len(res.held_back)} post(s): Telegram shows only its notice and My posts has no saved copy of them, so " f"they were not copied ({sample(res.held_back)}). Put a backup made before that back with /import, then use " "βTry the rest againβ." ) elif res.held_back: notes.append( f"β οΈ {len(res.held_back)} post(s) are held back by Telegram - it shows a notice instead of them " f"({sample(res.held_back)}). Copying the notice would be wrong, so they were not copied and the old posts are " "not deleted." ) return notes
def no_media_notes(res) -> list: """Lines about the files that /shift --no-media left out.""" if not getattr(res, "no_media", False): return [] notes = [] if res.files_left_out: notes.append(f"π« {res.files_left_out} post(s) were copied as text only - their file was left out (--no-media).") if res.file_only: ids = ", ".join(f"#{i}" for i in res.file_only[:8]) + ("β¦" if len(res.file_only) > 8 else "") notes.append(f"π« {len(res.file_only)} post(s) are only a file, so there was nothing to copy of them ({ids}).") return notes
def hidden_notes(res, *, shift: bool = False) -> list: """Lines about new posts that TELEGRAM itself hides (they were read back after posting).""" if not getattr(res, "hidden", None): return [] k, n = len(res.hidden), res.checked with_file = sum(1 for _, has in res.hidden if has) plain = k - with_file why = f" (β{esc(res.hidden_why)}β)" if res.hidden_why else "" lines = [ f"β οΈ <b>Telegram itself hides {k} of the {n} new post(s) I read back</b>{why}: right after they were created they " "carry its restriction mark, so its apps show the notice instead of them. The bot did not copy a notice - it " "never posts one: Telegram marks these posts itself, because of something in them or because of the destination." ] if with_file: hint = ( " <code>/shift β¦ --no-media</code> copies the text and buttons without the files." if shift else "" ) lines.append( f"β’ {with_file} post(s) of these carry a file. Telegram may hide a message that carries a file it has " f"blocked for copyright, wherever it is posted.{hint}" ) if plain: lines.append( f"β’ {plain} post(s) of these have no file: Telegram hides them for their text or links, or because it " "restricts the new channel too." ) if getattr(res, "dst_restricted", None): lines.append(f"β’ Telegram restricts the destination channel itself: β{esc(res.dst_restricted)}β.") if getattr(res, "hidden_stop", False): lines.append( f"βΉ <b>I stopped after {res.copied_units} post(s)</b>: Telegram hides every new copy I read back, so going on " "would only add more posts nobody can see. Nothing else was posted. βΆοΈ <b>Continue anyway</b> copies the rest; " "β©οΈ <b>Undo</b> removes the copies." ) lines.append("The saved posts in My posts are intact. Undo removes the new copies again.") return lines
def hidden_progress(res) -> str: """One line for the running progress message when Telegram hides what was just posted.""" if not getattr(res, "hidden", None): return "" why = f" (β{esc(res.hidden_why)}β)" if res.hidden_why else "" return f"\nβ οΈ Telegram itself hides {len(res.hidden)} of the {res.checked} new posts checked so far{why}. βΉ Stop is below."
def finishing_notes(res, *, shift: bool = False) -> list: """Lines about answers, links and pins for the end of a repost or shift.""" notes = held_notes(res) + no_media_notes(res) + hidden_notes(res, shift=shift) if res.replies: notes.append(f"β©οΈ {res.replies} post(s) answer the copy of the post they answered.") if res.reply_lost: notes.append(f"{res.reply_lost} post(s) could only be copied without their reply (their media can't be rebuilt).") if res.reply_dropped: notes.append(f"{res.reply_dropped} post(s) answered a post that is not there any more, so they answer nothing.") fin = res.final if fin is not None: if fin.relinked: notes.append(f"π {fin.links} link(s) in {fin.relinked} post(s) now point at the new copies.") if fin.failed: sample = ", ".join(f"#{i} {esc(n)}" for i, n in fin.failed[:5]) notes.append(f"{len(fin.failed)} post(s) could not get their links updated ({sample}).") if fin.pinned: notes.append(f"π {fin.pinned} pinned post(s) are pinned again.") if fin.pin_error: notes.append( f"π {fin.pin_wanted - fin.pinned} copy/copies could not be pinned ({esc(fin.pin_error)}). Give the bot the " "βEdit messages of othersβ right, or pin them by hand." ) if res.final_error: notes.append(f"Links and pins could not be finished ({esc(res.final_error)}).") if res.profile is not None: notes += profile_lines(res.profile) if res.profile_error: notes.append(f"The name, description and photo could not be copied ({esc(res.profile_error)}).") if res.cross is not None: notes += report_lines(res.cross) if res.cross_error: notes.append( f"Links in your other channels could not be updated ({esc(res.cross_error)}). " "Press βπ Update links againβ to try once more." ) return notes
def register(ctx: Ctx) -> None: client, db, cfg = ctx.client, ctx.db, ctx.cfg
# ---------------------------------------------------------------- views async def view_for(mig): """Text and buttons describing where a repost stands.""" ch = await db.get_channel(mig.channel_id) c = await db.migration_counts(mig.id) name = esc(ch.title) if ch else str(mig.channel_id) swap = f" (<code>@{esc(mig.old_username)}</code> β <code>@{esc(mig.new_username)}</code>)" if mig.old_username else "" first_copy = "" if ch and c["first_new"]: first_copy = f'\n<a href="{post_link(ch, c["first_new"])}">First copy</a>' undo = [Button.inline("β©οΈ Undo - remove the copies", f"rpu:{mig.id}")] links = [Button.inline("π Update links again", f"rpl:{mig.id}")] if mig.status == "copied" and not mig.partial: text = ( f"β
<b>{name}: all posts copied in order</b>{swap}\n{c['copied']} messages are now at the end of the channel " f"and in My posts.{first_copy}\n\nLook at the end of the channel and check a few posts: formatting, " "buttons, media. If it looks right, delete the old posts. If not, undo: the copies are removed and the " "originals were never touched." ) kb = [[Button.inline("π Delete the old posts", f"rpd:{mig.id}")], links, undo] elif mig.status == "copied": text = ( f"β
<b>{name}: trial finished</b>{swap}\n{c['copied']} message(s) copied.{first_copy}\n" "Check them. Remove them again, or close this trial and keep them." ) kb = [links, undo, [Button.inline("β
Close, keep the copies", f"rpk:{mig.id}")]] elif mig.status == "stopped": text = f"βΉ <b>{name}: stopped</b>{swap}\n{c['copied']} message(s) copied so far.{first_copy}" kb = [[Button.inline("βΆοΈ Continue", f"rpc:{mig.id}")], undo] elif mig.status == "copying": text = f"β³ <b>{name}</b>: a repost was running when the bot stopped. {c['copied']} message(s) copied.{first_copy}" kb = [[Button.inline("βΆοΈ Continue", f"rpc:{mig.id}")], undo] else: # incomplete text = ( f"β οΈ <b>{name}: not everything was copied</b>{swap}\n{c['copied']} message(s) copied.{first_copy}\n" "Old posts are only deleted once everything is copied, so nothing is lost. Try the rest again, " "or undo." ) kb = [[Button.inline("π Try the rest again", f"rpc:{mig.id}")], undo] return text, kb
# --------------------------------------------------------------- /repost @client.on(cmd("repost", args=True)) @guard(ctx, owner=True) async def h_repost(event): purge_pending(ctx) raw = (event.pattern_match.group(1) or "").strip() if not raw: mig = await db.open_migration() if mig is not None: text, kb = await view_for(mig) await say(event, "Unfinished repost:\n\n" + text, kb) else: await say(event, USAGE) return try: old, new, flags = parse_repost_args(raw) except ValueError as e: raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE)) chans = await db.list_channels() if not chans: raise UserError("No channels registered yet. Use /addchannel.") opts = RepostOptions( old=old, new=new, include_typed=cfg.replace_typed_links if flags["typed"] is None else flags["typed"], include_posts=flags["posts"], last=flags["last"], ) token = secrets.token_hex(4) ctx.pending[token] = RepostChoice(user=event.sender_id, opts=opts) await show_picker(event, token, 0)
async def show_picker(event, token: str, page: int) -> None: require_owner(ctx, event) choice = ctx.pending.get(token) if not isinstance(choice, RepostChoice) or choice.user != event.sender_id: raise UserError("That list has expired. Run /repost again.") chans = await db.list_channels() if not chans: raise UserError("No channels registered yet. Use /addchannel.") opts = choice.opts what = ( f"swap <code>@{esc(opts.old)}</code> β <code>@{esc(opts.new)}</code> in the links" if opts.swaps else "copy without changing any link" ) if opts.last: what += f", trial: only the newest {opts.last} post ids" text, kb = picker.render( chans, page, head=f"π’ <b>Which channel should I repost?</b>\nPlan: {what}.", kind="rp", arg=token, choose=lambda c: f"rpch:{token}:{c.id}", extra_rows=[[Button.inline("βοΈ Cancel", f"rpn:{token}")]], ) await show(event, text, kb)
ctx.pickers["rp"] = show_picker
@on_cb(ctx, "rpch") async def cb_pick(event, parts): require_owner(ctx, event) token, cid = parts[0], int(parts[1]) choice = ctx.pending.get(token) if not isinstance(choice, RepostChoice) or choice.user != event.sender_id: raise UserError("That list has expired. Run /repost again.") ch = await db.get_channel(cid) if ch is None or not ch.active: raise UserError("That channel is not registered any more. Run /repost again.") mig = await db.open_migration(ch.id) if mig is not None: ctx.pending.pop(token, None) text, kb = await view_for(mig) await edit_callback_message( event, "There is an unfinished repost for this channel. Finish or undo it first.\n\n" + text, kb ) return rights = await get_rights(client, ch) if rights is not None and not (rights.admin and rights.post): raise UserError("The bot needs the βPost messagesβ admin right in that channel.") if ctx.lock.locked(): raise UserError("Another long job (replace / repost) is still running.") ctx.pending.pop(token, None) # a second press on the list can't start a second plan opts = choice.opts last = [0.0]
async def prog(p): if time.monotonic() - last[0] < 3: return last[0] = time.monotonic() try: await edit_callback_message(event, f"π Reading <b>{esc(ch.title)}</b>: post id {p.scanned}β¦") except Exception: pass
async with ctx.lock: await edit_callback_message(event, f"π Reading <b>{esc(ch.title)}</b>β¦") plan = await plan_repost(client, ch, opts, progress=prog, saved=saved_lookup(db, ch.id)) if plan.error: await edit_callback_message(event, f"β οΈ {esc(plan.error)}") return job = RepostJob(user=event.sender_id, ch=ch, opts=opts, plan=plan) ctx.pending[token] = job kb = [[Button.inline("βΆοΈ Start copying", f"rpa:{token}"), Button.inline("βοΈ Cancel", f"rpn:{token}")]] await edit_callback_message(event, plan_text(plan, opts, ch.title, cfg.edit_delay), kb)
@on_cb(ctx, "rpn") async def cb_cancel(event, parts): require_owner(ctx, event) ctx.pending.pop(parts[0], None) await edit_callback_message(event, "Cancelled - nothing was copied or deleted.")
# ------------------------------------------------------------------ copy async def run_copy(event, job: RepostJob) -> None: mig = await db.get_migration(job.mig_id) ch = job.ch job.running, job.stop = True, False ctx.pending[f"job:{mig.id}"] = job total = job.plan.units if job.plan else None last = [0.0]
async def prog(res): if res.phase in ("copy", "links") and time.monotonic() - last[0] < 4: return last[0] = time.monotonic() done = res.copied_units + res.skipped_done of = f"/{total}" if total else "" if res.phase == "links" and res.cross is not None: body = f"β
Copied {done}{of} posts.\n" + progress_text(res.cross) elif res.phase == "finish": body = f"π Copied {done}{of} posts. Now pointing links at the new copies and pinningβ¦" else: body = f"β³ Copying <b>{esc(ch.title)}</b>: {done}{of} postsβ¦\nThe old posts stay untouched." body += hidden_progress(res) try: await edit_callback_message(event, body, [[Button.inline("βΉ Stop", f"rps:{mig.id}")]]) except errors.MessageNotModifiedError: pass except Exception: log.debug("progress update failed", exc_info=True)
try: async with ctx.lock: await db.set_migration_status(mig.id, "copying") res = await run_repost( client, db, ch, mig, event.sender_id, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop ) finally: job.running = False status = "stopped" if res.stopped else ("incomplete" if (res.failed or res.aborted or res.held_back) else "copied") await db.set_migration_status(mig.id, status) mig = await db.get_migration(mig.id) text, kb = await view_for(mig) notes = [] if res.copied_units: notes.append( f"{res.forwarded} post(s) were copied by Telegram, {res.rebuilt} were posted again with their buttons." ) if res.repaired: notes.append(f"{res.repaired} post(s) needed their buttons set again after posting - they show them now.") if res.failed: sample = ", ".join(f"#{i} {esc(n)}" for i, n in res.failed[:6]) notes.append(f"<b>{len(res.failed)} post(s) failed</b> ({sample}{'β¦' if len(res.failed) > 6 else ''}).") if any(n == "ButtonsNotShown" for _, n in res.failed): notes.append( "ButtonsNotShown: Telegram did not show the buttons on the new post, so that copy was removed again. " "The original is untouched - use βTry the rest againβ." ) if res.aborted: notes.append(f"Stopped early because of {esc(res.aborted)}.") notes += finishing_notes(res) await edit_callback_message(event, text + ("\n\n" + "\n".join(notes) if notes else ""), kb)
@on_cb(ctx, "rpa") async def cb_start(event, parts): require_owner(ctx, event) job = ctx.pending.get(parts[0]) if not isinstance(job, RepostJob) or job.user != event.sender_id: raise UserError("That plan has expired. Run /repost again.") if job.running or ctx.lock.locked(): raise UserError("A long job is already running.") if await db.open_migration(job.ch.id) is not None: raise UserError("There is already an unfinished repost for this channel.") p, o = job.plan, job.opts job.mig_id = secrets.token_hex(6) await db.create_migration( job.mig_id, job.ch.id, old=o.old, new=o.new, include_typed=o.include_typed, include_posts=o.include_posts, first_id=p.first, last_id=p.last, partial=p.partial, user_id=event.sender_id, ) ctx.pending.pop(parts[0], None) await run_copy(event, job)
@on_cb(ctx, "rpc") async def cb_continue(event, parts): require_owner(ctx, event) mig = await db.get_migration(parts[0]) if mig is None or mig.status not in ("stopped", "incomplete", "copying"): raise UserError("There is nothing to continue.") if ctx.lock.locked(): raise UserError("A long job is already running.") ch = await db.get_channel(mig.channel_id) if ch is None: raise UserError("That channel is not registered any more.") opts = RepostOptions(old=mig.old_username, new=mig.new_username, include_typed=mig.include_typed, include_posts=mig.include_posts) await run_copy(event, RepostJob(user=event.sender_id, ch=ch, opts=opts, mig_id=mig.id))
@on_cb(ctx, "rps") async def cb_stop(event, parts): require_owner(ctx, event) job = ctx.pending.get(f"job:{parts[0]}") if isinstance(job, RepostJob) and job.running: job.stop = True await event.respond("βΉ Stopping after the post that is being worked onβ¦") else: await event.respond("Nothing is running.")
# ------------------------------------------------------------ links again @on_cb(ctx, "rpl") async def cb_links(event, parts): """Look through every connected channel once more for links to the old posts and point them at the copies.""" require_owner(ctx, event) mig, ch = await load(parts) if mig.status not in ("copied", "old_deleted"): raise UserError("Links can be updated once everything is copied.") if ctx.lock.locked(): raise UserError("A long job is already running.") job = RepostJob(user=event.sender_id, ch=ch, opts=RepostOptions(), mig_id=mig.id, running=True) ctx.pending[f"job:{mig.id}"] = job cross, last = CrossResult(), [0.0]
async def prog(c): if time.monotonic() - last[0] < 4: return last[0] = time.monotonic() try: await edit_callback_message(event, progress_text(c), [[Button.inline("βΉ Stop", f"rps:{mig.id}")]]) except errors.MessageNotModifiedError: pass except Exception: log.debug("progress update failed", exc_info=True)
error = None try: async with ctx.lock: await edit_callback_message(event, "π Looking for links to the old posts in your channelsβ¦") await relink_after_repost( client, db, ch, mig, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop, result=cross ) except Exception as e: # the posts are fine; only the links were not (all) updated log.exception("pointing the links at the copies failed") error = type(e).__name__ finally: job.running = False ctx.pending.pop(f"job:{mig.id}", None) notes = report_lines(cross) if error: notes.append(f"Links could not be updated ({esc(error)}).") if not notes: notes.append("π There is nothing to change.") again = [Button.inline("π Update links again", f"rpl:{mig.id}")] if mig.status == "copied": text, kb = await view_for(mig) await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb) else: await edit_callback_message(event, f"π <b>{esc(ch.title)}</b>\n" + "\n".join(notes), [again])
# ----------------------------------------------------- delete old / undo async def load(parts): mig = await db.get_migration(parts[0]) if mig is None: raise UserError("I don't know that repost any more.") ch = await db.get_channel(mig.channel_id) if ch is None: raise UserError("That channel is not registered any more.") return mig, ch
@on_cb(ctx, "rpb") async def cb_back(event, parts): mig, _ = await load(parts) text, kb = await view_for(mig) await edit_callback_message(event, text, kb)
@on_cb(ctx, "rpd") async def cb_delete_ask(event, parts): require_owner(ctx, event) mig, ch = await load(parts) if mig.status != "copied" or mig.partial: raise UserError("Old posts can only be deleted after a complete, successful copy.") c = await db.migration_counts(mig.id) await edit_callback_message( event, f"π <b>Delete {c['old_left']} old message(s) from {esc(ch.title)}?</b>\n" "Only originals that have a copy are deleted. This can't be undone. The copies stay and become the channel: " "nothing is lost, they are already there.", [[Button.inline(f"π Yes, delete {c['old_left']}", f"rpdy:{mig.id}"), Button.inline("β©οΈ Back", f"rpb:{mig.id}")]], )
def userbot_lines(deleter) -> str: notes = getattr(deleter, "notes", None) or [] return ("\n" + "\n".join(f"β’ {esc(n)}" for n in notes)) if notes else ""
@on_cb(ctx, "rpdy") async def cb_delete_old(event, parts): require_owner(ctx, event) mig, ch = await load(parts) if mig.status not in ("copied", "old_deleted") or mig.partial: raise UserError("Old posts can only be deleted after a complete, successful copy.") if ctx.lock.locked(): raise UserError("A long job is already running.") last = [0.0]
async def prog(r): if time.monotonic() - last[0] < 3: return last[0] = time.monotonic() try: await edit_callback_message(event, f"π Deleting old postsβ¦ {r.deleted} done") except Exception: pass
fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None) try: async with ctx.lock: res = await delete_copies(client, db, ch, mig, "old", delay=0.5, progress=prog, fallback=fallback) finally: if deleter is not None: await deleter.close() c = await db.migration_counts(mig.id) extra = userbot_lines(deleter) by = f" ({res.by_userbot} of them by the userbot)" if res.by_userbot else "" if res.remaining == 0 and not res.error: await db.set_migration_status(mig.id, "old_deleted") await edit_callback_message( event, f"β
<b>Done.</b> {res.deleted} old message(s) deleted{by}. The channel now consists of the copies " f"(from <a href=\"{post_link(ch, c['first_new'])}\">here</a>), and they are all in My posts.{extra}", [[Button.inline("π Update links again", f"rpl:{mig.id}")]], ) return why = esc( delete_problem_text( ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot ) ) await edit_callback_message( event, f"β οΈ Deleted {res.deleted}{by}, {res.remaining} old message(s) are still there. {why}{extra}\n" f"The copies are complete. You can delete the rest by hand: they are the messages with an id below " f"{c['first_new']}. Then close this repost.", [[Button.inline("π Try again", f"rpdy:{mig.id}")], [Button.inline("β
Close this repost", f"rpk:{mig.id}")]], )
@on_cb(ctx, "rpu") async def cb_undo_ask(event, parts): require_owner(ctx, event) mig, ch = await load(parts) c = await db.migration_counts(mig.id) if mig.status in ("old_deleted", "copies_deleted", "closed") or c["old_left"] < c["copied"]: raise UserError("Some originals are already deleted, so removing the copies would delete your content. Undo is not possible any more.") await edit_callback_message( event, f"β©οΈ <b>Remove the {c['new_left']} copied message(s) from {esc(ch.title)}?</b>\nThe original posts stay as they are.", [[Button.inline("β©οΈ Yes, remove the copies", f"rpuy:{mig.id}"), Button.inline("Back", f"rpb:{mig.id}")]], )
@on_cb(ctx, "rpuy") async def cb_undo(event, parts): require_owner(ctx, event) mig, ch = await load(parts) c = await db.migration_counts(mig.id) if mig.status in ("old_deleted", "copies_deleted", "closed") or c["old_left"] < c["copied"]: raise UserError("Undo is not possible any more.") if ctx.lock.locked(): raise UserError("A long job is already running.") fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None) back = CrossResult() last = [0.0]
async def prog(c): if time.monotonic() - last[0] < 4: return last[0] = time.monotonic() try: await edit_callback_message(event, progress_text(c, title="Pointing links back at the original posts")) except Exception: log.debug("progress update failed", exc_info=True)
try: async with ctx.lock: try: # links that were pointed at the copies would be left without a post: point them back first await restore_after_undo(client, db, ch, mig, delay=cfg.edit_delay, progress=prog, result=back) except Exception: log.exception("pointing the links back at the original posts failed") back.stopped = True res = await delete_copies(client, db, ch, mig, "new", delay=0.5, fallback=fallback) finally: if deleter is not None: await deleter.close() link_notes = report_lines(back, back=True) link_text = ("\n" + "\n".join(link_notes)) if link_notes else "" if res.remaining == 0 and not res.error: await db.set_migration_status(mig.id, "copies_deleted") await edit_callback_message( event, f"β©οΈ Done. {res.deleted} copied message(s) removed; the original posts were not touched." f"{userbot_lines(deleter)}{link_text}", ) else: why = esc( delete_problem_text( ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot ) ) await edit_callback_message( event, f"β οΈ Removed {res.deleted}, {res.remaining} copy/copies are still there. {why}{link_text}", [[Button.inline("π Try again", f"rpuy:{mig.id}")]], )
@on_cb(ctx, "rpk") async def cb_close(event, parts): require_owner(ctx, event) mig, _ = await load(parts) await db.set_migration_status(mig.id, "closed") await edit_callback_message(event, "β
Closed. Nothing else will be changed in that channel by this repost.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618"""/shift <source> <destination> [from_id] [to_id]: copy posts from one channel into another. Owner only."""from __future__ import annotations
import loggingimport reimport secretsimport timefrom dataclasses import dataclass, fieldfrom typing import Optional
from telethon import Button, errors
from ..channelref import ChannelRef, resolve_channelfrom ..common import Ctx, UserError, cmd, edit_callback_message, guard, on_cb, purge_pending, require_owner, sayfrom ..crosslinks import CrossResult, progress_text, relink_after_shift, report_lines, restore_after_shift_undofrom ..profile_copy import profile_linesfrom ..repost_engine import RepostOptions, RepostPlan, RepostResult, plan_repost, saved_lookupfrom ..shift_engine import delete_shift_copies, plan_from_my_posts, run_shift, shift_profile, source_offrom ..tgutil import esc, explain_rpc, get_rights, post_linkfrom ..userbot import delete_problem_textfrom .repost import finishing_notes, held_plan_lines, hidden_progress
log = logging.getLogger(__name__)
USAGE = ( "Usage: <code>/shift <source> <destination> [from_id] [to_id]</code>\n" "Copies posts from one channel into another - text, formatting, media, albums, buttons, replies - and registers " "the copies in My posts. The source is only read: nothing in it is changed or deleted.\n\n" "A channel can be given as <code>@username</code>, a t.me link, its id (<code>-100β¦</code>) or an invite link " "(the bot must be a member). The bot must be an admin of the destination (Post messages).\n\n" "<code>/shift @source @destination</code> - every post\n" "<code>/shift @source @destination 15 20</code> - only the posts with message ids 15 to 20\n" "<code>/shift @source @destination 15</code> - only post 15\n\n" "A channel that Telegram restricts (a copyright strike: βThis channel is unavailable due to copyright " "infringementβ, its posts shown as βThis message couldn't be displayed on your device due to copyright " "infringementβ) is copied from what My posts saved of it - every post that has a saved copy, however intact " "Telegram's version looks. Telegram's notice is never copied. A post without a saved copy is copied as Telegram " "hands it out if it is still the post itself, and skipped if only the notice is left.\n\n" "Three extras, each optional, in any order, with or without a range:\n" "<code>-c</code> - afterwards every link to a post of the source - in ANY of your connected channels - is pointed " "at the copy in the destination\n" "<code>-all</code> - afterwards the destination gets the source's name, description and profile photo\n" "<code>--no-media</code> - no file is copied: every post goes out as its text with its formatting and buttons " "(use it when Telegram hides the copies because of their files)\n" "<code>/shift @source @destination -c -all</code> does the first two.")
@dataclassclass ShiftFlags: """The optional extras of /shift."""
links: bool = False # -c: links to the source's posts, in all connected channels, follow the copies profile: bool = False # -all: the destination gets the source's name, description and profile photo no_media: bool = False # --no-media: the copies get no files (text, formatting and buttons only)
@dataclassclass ShiftJob: """A shift that was planned and is waiting for the owner's OK (or is running)."""
user: int src: ChannelRef dst: ChannelRef plan: RepostPlan already: int = 0 # posts of the range that an earlier shift copied into this destination flags: ShiftFlags = field(default_factory=ShiftFlags) running: bool = False stop: bool = False shift_id: str = "" created: float = field(default_factory=time.monotonic)
_OPTION = re.compile(r"^[-\u2013\u2014]{1,2}([A-Za-z][A-Za-z0-9_-]*)$") # phone keyboards turn "--" into a long dash
def parse_shift_args(raw: str) -> tuple: """-> (source text, destination text, first id or None, last id or None, ShiftFlags).
-c, -all and --no-media can stand anywhere, in any order ("- all" with a space is understood too, and so are -nomedia and a long dash in place of --); a channel id such as -1001234567890 is not an option.""" text = re.sub(r"(?<!\S)([-\u2013\u2014]{1,2})\s+(all|c|no[-_]?media)(?!\S)", r"\1\2", raw or "", flags=re.I) flags, toks = ShiftFlags(), [] for t in text.split(): m = _OPTION.match(t) if m is None: toks.append(t) continue name = re.sub(r"[-_]", "", m.group(1)).lower() if name == "c": flags.links = True elif name == "all": flags.profile = True elif name == "nomedia": flags.no_media = True else: raise ValueError(f"Unknown option {t}. The options are -c, -all and --no-media.") if len(toks) < 2 or len(toks) > 4: raise ValueError("Give the source and the destination channel, and optionally the first and the last message id.") nums: list = [] for t in toks[2:]: if not t.isdigit() or int(t) < 1: raise ValueError(f"β{t}β is not a message id. Message ids are positive numbers, for example 15 20.") nums.append(int(t)) first = last = None if len(nums) == 1: first = last = nums[0] elif len(nums) == 2: first, last = min(nums), max(nums) return toks[0], toks[1], first, last, flags
def plan_text( p: RepostPlan, src: ChannelRef, dst: ChannelRef, already: int, delay: float, flags: Optional[ShiftFlags] = None, others: int = 0, info_right: bool = True,) -> str: kinds = f"{p.text} text, {p.media} media" if p.polls: kinds += f", {p.polls} poll(s)" if p.other: kinds += f", {p.other} other" lines = [ "π¦ <b>Shift plan</b>", f"From <b>{esc(src.title)}</b> β <b>{esc(dst.title)}</b>", f"Post ids {p.first}-{p.last}: <b>{p.units} posts</b> to copy ({p.messages} messages, {p.albums} album(s)) - {kinds}", ] if p.service: lines.append(f"β’ {p.service} service message(s) (like βpinned a messageβ) can't be copied and are skipped") if p.polls: lines.append("β’ polls are copied without their votes") if p.dropped_posts: lines.append(f"β’ {p.dropped_posts} post(s) carry other bots' buttons (reactions...) - those are not copied") lines += held_plan_lines(p, src.title, shift=True) if p.no_media: note = "β’ π« <b>--no-media</b>: no file is copied - every post goes out as its text with its formatting and buttons" if p.files_left_out: note += f". {p.files_left_out} post(s) carry a file that stays out" if p.file_only: note += f"; {p.file_only} post(s) are only a file, so there is nothing to copy of them and they are skipped" lines.append(note + ".") if p.post_links: lines.append( f"β’ {p.post_links} link(s) in {p.post_link_posts} post(s) point at other posts of {esc(src.title)}: those that " "are shifted too will point at their copies" ) if p.replies: lines.append(f"β’ {p.replies} post(s) answer another post: the copy answers the copy (if that post is shifted too)") if already: lines.append( f"β’ β οΈ {already} of these posts were already shifted into {esc(dst.title)} before: they would be copied again" ) flags = flags or ShiftFlags() if p.from_db: lines.insert( 2, f"β οΈ <b>I can't read {esc(src.title)}</b>: {esc(p.unreadable or 'Telegram refuses')}. My posts has the saved " "posts of it, so they are copied from there.", ) if flags.links: where = f"your {others} other connected channel(s)" if others else "your connected channels" lines.append( f"β’ π <b>-c</b>: afterwards every link to a post of {esc(src.title)} - a hyperlink, a typed link or a " f"button - in {where} is pointed at the copy in {esc(dst.title)} (links to posts that are not shifted stay " f"as they are). {esc(src.title)} itself is not changed." ) if flags.profile: lines.append( f"β’ πΌ <b>-all</b>: afterwards {esc(dst.title)} gets the name, description and profile photo of " f"{esc(src.title)}. Its own are replaced - undo does not bring them back. A part the source does not have " "is left as it is." ) if not info_right: lines.append( f"β’ β οΈ The bot does not have the βChange channel infoβ admin right in {esc(dst.title)} yet - give it " "before the copying is finished, or use the βcopy againβ button afterwards." ) minutes = max(1, round(p.eta_seconds(delay) / 60)) if p.from_db: what = "its text, formatting and buttons" if p.no_media else ( "its text, formatting, buttons and media (a file that Telegram refuses goes out without it)" ) how = ( f"<b>How:</b> every post is posted again from what My posts saved of it - {what} - and every button is read " "back to make sure it is there. Copies go to the end of the destination silently, in the original order, and " "are registered in My posts." ) 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)." elif p.no_media: how = ( "<b>How:</b> every post is posted again as its text with its formatting and buttons - no file is copied - and " "every button is read back to make sure it is there. Copies go to the end of the destination silently, in the " "original order, and are registered in My posts." ) 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." elif p.channel_restricted: how = ( "<b>How:</b> Telegram copies nothing out of a restricted channel, so every post is posted again - from what " "My posts saved of it, or as Telegram hands it out when there is no saved copy - with its text, formatting, " "media and buttons in one go, and every button is read back to make sure it is there. Copies go to the end of " "the destination silently, in the original order, and are registered in My posts." ) kept = "<b>Not kept:</b> original dates, view counts, reactions, comments, poll votes and pins." else: how = ( "<b>How:</b> posts are copied by Telegram itself where possible (exactly as they are); posts with buttons or " "replies are posted again with their text, formatting, media and buttons in one go, and every button is read " "back to make sure it is there. Copies go to the end of the destination silently, in the original order, and " "are registered in My posts." ) if p.held_saved or p.live_restricted: how += " Posts that Telegram restricts are never copied by Telegram itself: they are posted again." kept = "<b>Not kept:</b> original dates, view counts, reactions, comments, poll votes and pins." lines += [ "", how, "", kept, f"Time: about {minutes} min. <b>Nothing is changed in {esc(src.title)}.</b>", ] return "\n".join(lines)
def register(ctx: Ctx) -> None: client, db, cfg = ctx.client, ctx.db, ctx.cfg
# ---------------------------------------------------------------- views async def view_for(sh): """Text and buttons describing where a shift stands.""" dst = await db.get_channel(sh.dst_channel_id) c = await db.shift_counts(sh.id) src_name = esc(sh.src_title or str(sh.src_channel_id)) dst_name = esc(dst.title) if dst else str(sh.dst_channel_id) route = f"<b>{src_name}</b> β <b>{dst_name}</b>" first_copy = "" if dst and c["first_new"]: first_copy = f'\n<a href="{post_link(dst, c["first_new"])}">First copy</a>' undo = [Button.inline("β©οΈ Undo - remove the copies", f"sfu:{sh.id}")] marks = await db.marks_of(sh.id) if "nomedia" in marks: route += " (without files)" extras = [] if "relink" in marks: extras.append([Button.inline("π Update links again", f"sfl:{sh.id}")]) if "profile" in marks and "profile_done" not in marks: extras.append([Button.inline("πΌ Copy name, description, photo again", f"sfp:{sh.id}")]) if sh.status == "copied": text = ( f"β
{route}: <b>{c['copied']} message(s) copied</b> (source ids {sh.first_id}-{sh.last_id}) and " f"registered in My posts.{first_copy}\nThe source was not changed. Look at the end of the destination; " "if something is wrong, undo removes just these copies." ) kb = extras + [undo] elif sh.status == "copies_deleted": text = f"β©οΈ {route}: the copies were removed again." kb = [] elif sh.status == "stopped": text = f"βΉ {route}: <b>stopped</b>. {c['copied']} message(s) copied so far.{first_copy}" go = "βΆοΈ Continue anyway" if "hiddenok" in marks else "βΆοΈ Continue" kb = [[Button.inline(go, f"sfc:{sh.id}")], undo] elif sh.status == "copying": text = f"β³ {route}: a shift was running when the bot stopped. {c['copied']} message(s) copied.{first_copy}" kb = [[Button.inline("βΆοΈ Continue", f"sfc:{sh.id}")], undo] else: # incomplete text = ( f"β οΈ {route}: <b>not everything was copied</b>. {c['copied']} message(s) copied.{first_copy}\n" "Nothing was changed in the source." ) kb = [[Button.inline("π Try the rest again", f"sfc:{sh.id}")], undo] return text, kb
# --------------------------------------------------------------- /shift @client.on(cmd("shift", args=True)) @guard(ctx, owner=True) async def h_shift(event): purge_pending(ctx) raw = (event.pattern_match.group(1) or "").strip() if not raw: sh = await db.open_shift() if sh is not None: text, kb = await view_for(sh) await say(event, "Unfinished shift:\n\n" + text, kb) return await say(event, USAGE) # a finished shift keeps its Undo: offer it again, so it can be found without scrolling up to its old message last = await db.last_finished_shift() if last is not None: text, kb = await view_for(last) await say(event, "Latest finished shift - you can still undo it:\n\n" + text, kb) return try: src_text, dst_text, first, last, flags = parse_shift_args(raw) except ValueError as e: raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE).replace("<", "<").replace(">", ">")) src = await resolve_channel(ctx, src_text) dst = await resolve_channel(ctx, dst_text) if src.id == dst.id: raise UserError("The source and the destination are the same channel. To rebuild one channel in order, use /repost.") sh = await db.open_shift(src.id, dst.id) if sh is not None: text, kb = await view_for(sh) await say(event, "There is an unfinished shift between these two channels. Finish or undo it first.\n\n" + text, kb) return rights = await get_rights(client, dst) if rights is not None and not (rights.admin and rights.post): raise UserError(f"The bot needs the βPost messagesβ admin right in {dst.title}.") if ctx.lock.locked(): raise UserError("Another long job (replace / repost / shift) is still running.") note = await say(event, f"π Reading <b>{esc(src.title)}</b>β¦") last_edit = [0.0]
async def prog(p): if time.monotonic() - last_edit[0] < 3: return last_edit[0] = time.monotonic() try: await note.edit(f"π Reading <b>{esc(src.title)}</b>: post id {p.scanned}β¦") except Exception: pass
try: async with ctx.lock: plan = await plan_repost( client, src, RepostOptions(), progress=prog, first_id=first, last_id=last, saved=saved_lookup(db, src.id), use_saved=True, no_media=flags.no_media, ) except errors.RPCError as e: why = explain_rpc(e) # a channel that can't be read any more (banned, private ...) may still be in My posts: copy it from there plan = await plan_from_my_posts(db, src, first, last, unreadable=why, no_media=flags.no_media) if plan is None: raise UserError( f"I can't read {src.title}: {why}\nThe bot has to be a member of the source channel " "(an admin is best; it only reads). My posts has no saved posts of it to copy from instead." ) if plan.error: await note.edit(f"β οΈ {esc(plan.error)}") return already = len(await db.shifted_ids(src.id, dst.id, plan.first, plan.last)) others = 0 if flags.links: # the channels the links are looked for in: all connected ones, the source itself excluded known = {c.id for c in await db.list_channels()} | {dst.id} others = len(known - {src.id}) info_right = rights is None or bool(getattr(rights, "change_info", True)) token = secrets.token_hex(4) ctx.pending[token] = ShiftJob(user=event.sender_id, src=src, dst=dst, plan=plan, already=already, flags=flags) kb = [[Button.inline("βΆοΈ Start copying", f"sfa:{token}"), Button.inline("βοΈ Cancel", f"sfn:{token}")]] await note.edit(plan_text(plan, src, dst, already, cfg.edit_delay, flags, others, info_right), buttons=kb)
@on_cb(ctx, "sfn") async def cb_cancel(event, parts): require_owner(ctx, event) ctx.pending.pop(parts[0], None) await edit_callback_message(event, "Cancelled - nothing was copied.")
# ------------------------------------------------------------------ copy async def run_copy(event, sid: str, job: Optional[ShiftJob] = None) -> None: sh = await db.get_shift(sid) dst = await db.get_channel(sh.dst_channel_id) if dst is None: raise UserError("The destination channel is not registered any more.") job = job or ShiftJob(user=event.sender_id, src=None, dst=None, plan=None) # type: ignore[arg-type] job.running, job.stop, job.shift_id = True, False, sid ctx.pending[f"job:{sid}"] = job total = job.plan.units if job.plan else None last = [0.0] names = f"<b>{esc(sh.src_title)}</b> β <b>{esc(dst.title)}</b>"
async def prog(res): if res.phase in ("copy", "links") and time.monotonic() - last[0] < 4: return last[0] = time.monotonic() done = res.copied_units + res.skipped_done of = f"/{total}" if total else "" if res.phase == "links" and res.cross is not None: body = f"β
Copied {done}{of} posts.\n" + progress_text(res.cross, title="Pointing links of your channels at the copies") elif res.phase == "profile": body = f"πΌ Copied {done}{of} posts. Now copying the name, description and photo of {esc(sh.src_title)}β¦" elif res.phase == "finish": body = f"π Copied {done}{of} posts. Now pointing links at the new copiesβ¦" else: body = f"β³ Shifting {names}: {done}{of} postsβ¦\nThe source stays untouched." body += hidden_progress(res) try: await edit_callback_message(event, body, [[Button.inline("βΉ Stop", f"sfs:{sid}")]]) except errors.MessageNotModifiedError: pass except Exception: log.debug("progress update failed", exc_info=True)
try: async with ctx.lock: await db.set_shift_status(sid, "copying") res = await run_shift( client, db, sh, dst, event.sender_id, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop ) finally: job.running = False status = "stopped" if res.stopped else ("incomplete" if (res.failed or res.aborted or res.held_back) else "copied") await db.set_shift_status(sid, status) if res.hidden_stop: # stopped because Telegram hides the copies: pressing Continue means "go on anyway" await db.set_mark(sid, "hiddenok") sh = await db.get_shift(sid) text, kb = await view_for(sh) notes = [] if res.copied_units: notes.append(f"{res.forwarded} post(s) were copied by Telegram, {res.rebuilt} were posted again with their buttons.") if res.repaired: notes.append(f"{res.repaired} post(s) needed their buttons set again after posting - they show them now.") if res.failed: sample = ", ".join(f"#{i} {esc(n)}" for i, n in res.failed[:6]) notes.append(f"<b>{len(res.failed)} post(s) failed</b> ({sample}{'β¦' if len(res.failed) > 6 else ''}).") if any(n == "ButtonsNotShown" for _, n in res.failed): notes.append( "ButtonsNotShown: Telegram did not show the buttons on the new post, so that copy was removed again. " "The original is untouched - use βTry the rest againβ." ) if any(n == "ReplyParentMissing" for _, n in res.failed): notes.append("ReplyParentMissing: that post answers a post whose copy failed; it follows when you try again.") if res.aborted: notes.append(f"Stopped early because of {esc(res.aborted)}.") notes += finishing_notes(res, shift=True) await edit_callback_message(event, text + ("\n\n" + "\n".join(notes) if notes else ""), kb)
@on_cb(ctx, "sfa") async def cb_start(event, parts): require_owner(ctx, event) job = ctx.pending.get(parts[0]) if not isinstance(job, ShiftJob) or job.user != event.sender_id: raise UserError("That plan has expired. Run /shift again.") if job.running or ctx.lock.locked(): raise UserError("A long job is already running.") if await db.open_shift(job.src.id, job.dst.id) is not None: raise UserError("There is already an unfinished shift between these two channels.") rights = await get_rights(client, job.dst) if rights is not None and not (rights.admin and rights.post): raise UserError(f"The bot needs the βPost messagesβ admin right in {job.dst.title}.") # the copies are registered in My posts, so the destination has to be one of the bot's channels await db.save_channel(job.dst.id, job.dst.access_hash, job.dst.title, job.dst.username, event.sender_id) sid = secrets.token_hex(6) p = job.plan 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) if job.flags.links: await db.set_mark(sid, "relink") if job.flags.profile: await db.set_mark(sid, "profile") if job.flags.no_media: # continuing the shift later goes on without files as well await db.set_mark(sid, "nomedia") if p.from_db: # the source can't be read: continuing the shift goes on from My posts as well await db.set_mark(sid, "fromdb") ctx.pending.pop(parts[0], None) await run_copy(event, sid, job)
@on_cb(ctx, "sfc") async def cb_continue(event, parts): require_owner(ctx, event) sh = await db.get_shift(parts[0]) if sh is None or sh.status not in ("stopped", "incomplete", "copying"): raise UserError("There is nothing to continue.") if ctx.lock.locked(): raise UserError("A long job is already running.") await run_copy(event, sh.id)
@on_cb(ctx, "sfs") async def cb_stop(event, parts): require_owner(ctx, event) job = ctx.pending.get(f"job:{parts[0]}") if isinstance(job, ShiftJob) and job.running: job.stop = True await event.respond("βΉ Stopping after the post that is being worked onβ¦") else: await event.respond("Nothing is running.")
# ------------------------------------------------------------ the extras again @on_cb(ctx, "sfl") async def cb_links(event, parts): """-c once more: look through every connected channel for links to the source's posts.""" require_owner(ctx, event) sh, dst = await load(parts) if sh.status != "copied": raise UserError("Links can be updated once everything is copied.") if ctx.lock.locked(): raise UserError("A long job is already running.") job = ShiftJob(user=event.sender_id, src=None, dst=None, plan=None, running=True, shift_id=sh.id) # type: ignore[arg-type] ctx.pending[f"job:{sh.id}"] = job cross, last = CrossResult(), [0.0]
async def prog(c): if time.monotonic() - last[0] < 4: return last[0] = time.monotonic() try: await edit_callback_message( event, progress_text(c, title="Pointing links at the copies"), [[Button.inline("βΉ Stop", f"sfs:{sh.id}")]] ) except errors.MessageNotModifiedError: pass except Exception: log.debug("progress update failed", exc_info=True)
error = None try: async with ctx.lock: await edit_callback_message(event, "π Looking for links to the source's posts in your channelsβ¦") await relink_after_shift( client, db, sh, source_of(sh), dst, delay=cfg.edit_delay, progress=prog, should_stop=lambda: job.stop, result=cross, ) except Exception as e: # the copies are fine; only the links were not (all) updated log.exception("pointing the links at the shifted posts failed") error = type(e).__name__ finally: job.running = False ctx.pending.pop(f"job:{sh.id}", None) notes = report_lines(cross, what=f"the copies in {esc(dst.title)}") if error: notes.append(f"Links could not be updated ({esc(error)}).") if not notes: notes.append("π There is nothing to change.") text, kb = await view_for(sh) await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb)
@on_cb(ctx, "sfp") async def cb_profile(event, parts): """-all once more: the name, description and photo of the source.""" require_owner(ctx, event) sh, dst = await load(parts) if "profile" not in await db.marks_of(sh.id): raise UserError("This shift was not started with -all.") if sh.status not in ("copied", "stopped", "incomplete"): raise UserError("There is nothing to copy it to any more.") if ctx.lock.locked(): raise UserError("A long job is already running.") holder = RepostResult() async with ctx.lock: await edit_callback_message(event, f"πΌ Copying the name, description and photo of {esc(sh.src_title)}β¦") await shift_profile(client, db, sh, dst, event.sender_id, holder) dst = await db.get_channel(sh.dst_channel_id) or dst # it may have a new name now notes = profile_lines(holder.profile, dst.title) if holder.profile is not None else [] if holder.profile_error: notes.append(f"The name, description and photo could not be copied ({esc(holder.profile_error)}).") text, kb = await view_for(sh) await edit_callback_message(event, text + "\n\n" + "\n".join(notes), kb)
# ------------------------------------------------------------------ undo async def load(parts): sh = await db.get_shift(parts[0]) if sh is None: raise UserError("I don't know that shift any more.") dst = await db.get_channel(sh.dst_channel_id) if dst is None: raise UserError("The destination channel is not registered any more.") return sh, dst
@on_cb(ctx, "sfb") async def cb_back(event, parts): sh, _ = await load(parts) text, kb = await view_for(sh) await edit_callback_message(event, text, kb)
@on_cb(ctx, "sfu") async def cb_undo_ask(event, parts): require_owner(ctx, event) sh, dst = await load(parts) c = await db.shift_counts(sh.id) if not c["new_left"]: raise UserError("There is nothing to remove.") await edit_callback_message( event, f"β©οΈ <b>Remove the {c['new_left']} copied message(s) from {esc(dst.title)}?</b>\n" f"The posts in {esc(sh.src_title)} are not touched.", [[Button.inline("β©οΈ Yes, remove the copies", f"sfuy:{sh.id}"), Button.inline("Back", f"sfb:{sh.id}")]], )
@on_cb(ctx, "sfuy") async def cb_undo(event, parts): require_owner(ctx, event) sh, dst = await load(parts) if ctx.lock.locked(): raise UserError("A long job is already running.") fallback, deleter = await ctx.userbot.fallback_for(dst) if ctx.userbot is not None else (None, None) back, last = CrossResult(), [0.0]
async def prog(c): if time.monotonic() - last[0] < 4: return last[0] = time.monotonic() try: await edit_callback_message(event, progress_text(c, title="Pointing links back at the source's posts")) except Exception: log.debug("progress update failed", exc_info=True)
try: async with ctx.lock: try: # links that were pointed at the copies would be left without a post: point them back first await restore_after_shift_undo(client, db, sh, source_of(sh), dst, delay=cfg.edit_delay, progress=prog, result=back) except Exception: log.exception("pointing the links back at the source's posts failed") back.stopped = True res = await delete_shift_copies(client, db, dst, sh, delay=0.5, fallback=fallback) finally: if deleter is not None: await deleter.close() link_notes = report_lines(back, back=True) link_text = ("\n" + "\n".join(link_notes)) if link_notes else "" if res.remaining == 0 and not res.error: await db.set_shift_status(sh.id, "copies_deleted") await edit_callback_message( event, f"β©οΈ Done. {res.deleted} copied message(s) removed from {esc(dst.title)}; the source was not touched.{link_text}", ) else: why = esc(delete_problem_text(ctx.userbot, bot_error=res.error, fallback_error=res.fallback_error, tried=res.tried_userbot)) await edit_callback_message( event, f"β οΈ Removed {res.deleted}, {res.remaining} copy/copies are still there. {why}{link_text}", [[Button.inline("π Try again", f"sfuy:{sh.id}")]], )
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""/sync (owner only) and the live watch over the channels.
The live part listens to Telegram's updates: a post deleted, edited or added in a connected channel is recorded in Myposts a few seconds later, and service messages ("pinned a message", "channel photo changed" ...) are deleted at once.The same comparison runs on a timer for everything the bot was not there to see (SYNC_INTERVAL_MINUTES)."""from __future__ import annotations
import loggingimport reimport timefrom typing import Optional
from telethon import events, types
from ..common import Ctx, UserError, cmd, guard, sayfrom ..sync_engine import SyncReportfrom ..syncer import Syncerfrom ..tgutil import escfrom .replace import pick_channels
log = logging.getLogger(__name__)
USAGE = ( "Usage: <code>/sync</code>\n" "Compares every channel with My posts right now: posts that were deleted or edited in the channel by someone else " "are updated here (a post deleted in the channel leaves My posts), new posts that were not made with this bot are " "added, and service messages (βpinned a messageβ, βchannel photo changedβ ...) that appeared meanwhile are deleted. " "The posts that were in a channel before the bot was added are read into My posts too (a long channel takes a few " "checks; <code>/sync</code> goes on where the last one stopped).\n" "Options: <code>--channel @name</code> (only that channel), <code>--history</code> (read the channel's older posts " "again and add the ones that are missing; posts you made the bot forget stay forgotten).")
def parse_sync_args(raw: str) -> tuple: """(channel reference or None for every channel, read the older posts again) - ValueError for anything else.""" toks = (raw or "").split() ref: Optional[str] = None history = False i = 0 while i < len(toks): t = toks[i] if t == "--channel" and i + 1 < len(toks): ref = toks[i + 1] i += 2 elif t == "--history": history = True i += 1 else: raise ValueError(f"I don't know β{t}β.") return ref, history
def ids_text(ids, limit: int = 8) -> str: ids = sorted(ids) shown = ", ".join(str(i) for i in ids[:limit]) return shown + (f" and {len(ids) - limit} more" if len(ids) > limit else "")
def channel_block(rep: SyncReport) -> str: lines = [f"<b>{esc(rep.channel.title)}</b>"] if rep.error: return "\n".join(lines + [f"β οΈ {esc(rep.error)}"]) if rep.restricted_channel: return "\n".join( lines + [ f"π« Telegram has restricted this channel ({esc(rep.restricted_channel)}). Nothing was changed in My posts - " "the saved posts stay exactly as they are, whatever the channel shows now." ] ) nothing = True if rep.first_look: lines.append("π First look at this channel. From now on, posts made, edited or deleted outside this bot are recorded here.") if rep.checked: lines.append(f"β {rep.checked} saved post(s) compared with the channel") if rep.deleted: nothing = False lines.append(f"π {len(rep.deleted)} deleted in the channel β removed from My posts (message {ids_text(rep.deleted)})") if rep.edited: nothing = False lines.append(f"βοΈ {len(rep.edited)} edited in the channel β updated in My posts (message {ids_text(rep.edited)})") if rep.adopted: nothing = False lines.append(f"β {len(rep.adopted)} new post(s) made outside the bot β added to My posts (message {ids_text(rep.adopted)})") if rep.history_top: if rep.imported: nothing = False skipped = f" ({rep.history_unsupported} of a kind My posts can't hold - poll, sticker ... - skipped)" if rep.history_unsupported else "" if rep.history_done: if rep.imported: lines.append(f"π₯ {rep.imported} older post(s), sent before the bot was added β added to My posts{skipped}") else: lines.append(f"π₯ The older posts were looked through: nothing to add{skipped}") else: lines.append( f"π₯ Older posts: {rep.imported} added so far, read up to message {rep.history_to} of {rep.history_top}{skipped} - " "the next check goes on, or send /sync again to go on right away" ) if rep.restricted: nothing = False lines.append( f"π« {len(rep.restricted)} post(s) are held back by Telegram ({esc(rep.restricted_why or 'restricted')}) - " f"left exactly as saved in My posts (message {ids_text(rep.restricted)})" ) if rep.refreshed: lines.append(f"β’ {rep.refreshed} saved post(s) tidied up (spaces at the ends of the text)") if rep.services_deleted: nothing = False lines.append(f"π§Ή {rep.services_deleted} service message(s) deleted") if rep.services_failed: nothing = False lines.append( f"β οΈ {rep.services_failed} service message(s) could not be deleted ({esc(rep.services_error or 'refused')}) - " "the bot needs the βDelete messagesβ right, and Telegram lets bots delete only recent messages" ) if rep.buttons_missing: nothing = False lines.append( f"β οΈ {len(rep.buttons_missing)} saved post(s) show no buttons in the channel (message {ids_text(rep.buttons_missing)}). " "The saved buttons were kept: /posts β the channel β π§ Check buttons puts them back" ) if rep.unsupported: lines.append(f"β’ {rep.unsupported} new message(s) of a kind My posts can't hold (poll, sticker ...) were left alone") fresh = len(rep.young) + len(rep.young_new) if fresh: lines.append(f"β³ {fresh} too fresh to judge - the next check will see them") if rep.changed_meanwhile: lines.append(f"β’ {rep.changed_meanwhile} saved post(s) were changed through the bot meanwhile - left as they are") if rep.anomaly: nothing = False lines.append(f"β οΈ {esc(rep.anomaly)}") if rep.busy: lines.append("βΈ A long job started, so this check stopped early.") if nothing and not rep.busy and not rep.first_look: lines.append("Everything matches.") return "\n".join(lines)
def report_text(reports: list) -> str: head = "π <b>Sync finished</b>" if not reports: return head + "\nNothing to look at." return head + "\n\n" + "\n\n".join(channel_block(r) for r in reports)
def channel_id_of(msg) -> Optional[int]: peer = getattr(msg, "peer_id", None) return peer.channel_id if isinstance(peer, types.PeerChannel) else None
def register(ctx: Ctx) -> None: client, db = ctx.client, ctx.db if ctx.syncer is None: ctx.syncer = Syncer(ctx) sy = ctx.syncer
# ----------------------------------------------------------------------------------------- /sync @client.on(cmd("sync", args=True)) @guard(ctx, owner=True) async def h_sync(event): raw = (event.pattern_match.group(1) or "").strip() try: ref, history = parse_sync_args(raw) chans = pick_channels(await db.list_channels(), ref) except ValueError as e: raise UserError(f"{e}\n\n" + re.sub(r"<[^>]+>", "", USAGE)) if not chans: raise UserError("No channels registered yet. Use /addchannel.") if ctx.lock.locked(): raise UserError("Another long job (replace, repost, shift ...) is still running - try again when it has finished.") async with ctx.lock: if history: for ch in chans: await db.reset_history(ch.id) status = await say(event, f"π Looking at {len(chans)} channel(s)β¦") last = [0.0]
async def prog(ch, rep) -> None: now = time.monotonic() if now - last[0] < 3: return last[0] = now try: await status.edit(f"π <b>{esc(ch.title)}</b>: {rep.phase} (message {rep.scanned_to})β¦") except Exception: pass
reports = await sy.run_all(chans, explicit=True, history=True if history else None, progress=prog) await say(event, report_text(reports))
# ------------------------------------------------------------------- what Telegram tells while we run @client.on(events.Raw(types.UpdateNewChannelMessage)) async def on_channel_message(update): try: m = update.message cid = channel_id_of(m) if cid is None: return if isinstance(m, types.MessageService): await sy.on_service(cid, m) elif not isinstance(m, types.MessageEmpty): sy.note_new(cid, m) except Exception: log.warning("could not handle a new channel message", exc_info=True)
@client.on(events.Raw(types.UpdateEditChannelMessage)) async def on_channel_edit(update): try: m = update.message cid = channel_id_of(m) if cid is not None and not isinstance(m, (types.MessageService, types.MessageEmpty)): sy.note_edit(cid, m) except Exception: log.warning("could not handle an edited channel message", exc_info=True)
@client.on(events.Raw(types.UpdateDeleteChannelMessages)) async def on_channel_delete(update): try: await sy.note_deleted(update.channel_id, list(update.messages)) except Exception: log.warning("could not handle deleted channel messages", exc_info=True)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""/handleswap: change a username written in a post - "@bro" -> "@sis" - and nothing else.
Only usernames are touched: the words "@bro" in the text or caption (and in button names). Links, hyperlinks and thelinks behind buttons are left exactly as they are, and so is "@bro" when it is part of a link or an e-mail address."""from __future__ import annotations
import copyimport refrom typing import Optional
from telethon import typesfrom telethon.helpers import add_surrogate, del_surrogate
from .linkswap import MsgChange, apply_span_replacementsfrom .richmsg import is_rich_messagefrom .tgutil import button_url, is_callback_button, with_text
# 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) ..._NOT_BEFORE = r"\w@./=?&#%"_PROTECTED = tuple( getattr(types, n) for n in ("MessageEntityUrl", "MessageEntityTextUrl", "MessageEntityEmail") if hasattr(types, n))
def mention_regex(name: str): """'@name' as a whole word (case does not matter): not '@name_bot', not 'x@name'.""" return re.compile(rf"(?<![{_NOT_BEFORE}])@{re.escape(name)}(?![A-Za-z0-9_])", re.I)
def find_mention_spans(sur: str, entities, name: str) -> tuple: """([(start, end)], skipped) - where '@name' stands in `sur` (UTF-16 units). Mentions that sit inside a link or a hyperlink are not changed; `skipped` counts them.""" guarded = [(e.offset, e.offset + e.length) for e in entities or [] if isinstance(e, _PROTECTED)] spans, skipped = [], 0 for m in mention_regex(name).finditer(sur): s, e = m.span() if any(gs < e and s < ge for gs, ge in guarded): skipped += 1 continue spans.append((s, e)) return spans, skipped
def compute_handle_changes(msg, old: str, new: str) -> tuple: """(MsgChange or None, number of mentions skipped because they are part of a link) - same shape as linkswap.compute_message_changes, so the /swap engine can apply it.""" rich = is_rich_message(msg) # the text of a rich message is blocks: only its buttons are changed text = "" if rich else (msg.message or "") ents = [] if rich else list(msg.entities or []) sur = add_surrogate(text) spans, skipped = find_mention_spans(sur, ents, old) if text else ([], 0) new_sur, new_ents = sur, [copy.copy(e) for e in ents] if spans: new_sur, new_ents = apply_span_replacements(sur, ents, [(s, e, "@" + new) for s, e in spans])
# the names on link buttons (their links stay) new_markup: Optional[types.ReplyInlineMarkup] = None n_btn, has_cb = 0, False mk = msg.reply_markup if isinstance(mk, types.ReplyInlineMarkup): rx = mention_regex(old) rows = [] for row in mk.rows: btns = [] for b in row.buttons: if button_url(b) is not None: label, n = rx.subn("@" + new, getattr(b, "text", "") or "") if n: btns.append(with_text(b, label)) n_btn += n continue elif is_callback_button(b): has_cb = True btns.append(b) rows.append(types.KeyboardButtonRow(btns)) if n_btn: new_markup = types.ReplyInlineMarkup(rows)
if not (spans or n_btn): return None, skipped return ( MsgChange( message_id=msg.id, new_text=del_surrogate(new_sur), new_entities=new_ents, new_markup=new_markup, text_changed=bool(spans), entities_changed=bool(spans), n_buttons=n_btn, n_links=0, n_typed=len(spans), mine=bool(getattr(msg, "out", False)), callbacks=has_cb, ), skipped, )1234567891011121314151617181920212223242526"""Optional tiny HTTP endpoint for hosts that insist on an open port (set PORT)."""import asyncioimport logging
log = logging.getLogger(__name__)
async def start_health_server(port: int): async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: try: await asyncio.wait_for(reader.read(1024), timeout=5) except Exception: pass try: writer.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") await writer.drain() finally: writer.close()
try: server = await asyncio.start_server(handle, "0.0.0.0", port) except OSError as e: # e.g. something else (python -m http.server) already uses the port log.warning("could not open the health endpoint on :%s (%s) - continuing without it", port, e) return None log.info("health endpoint listening on :%s", port) return server123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Swap a username inside t.me links: button links, hyperlinks and typed links in message text.
Only the username part of a link changes; everything after it (?start=...) is left untouched.Offsets of message entities are UTF-16 based, so text is handled in Telethon's 'surrogate' form."""from __future__ import annotations
import copyimport refrom dataclasses import dataclassfrom typing import Optional
from telethon import typesfrom telethon.helpers import add_surrogate, del_surrogate
from .richmsg import is_rich_messagefrom .tgutil import button_url, is_callback_button, with_url
USERNAME_RX = re.compile(r"^[A-Za-z0-9_]{1,32}$")
def normalize_username(s: str) -> Optional[str]: s = (s or "").strip() m = re.match(r"(?i)^(?:https?://)?(?:t\.me|telegram\.me)/([A-Za-z0-9_]+)/?$", s) if m: s = m.group(1) s = s.lstrip("@") return s if USERNAME_RX.match(s) else None
# ------------------------------------------------------------------------------- urls_HTTP_RX = re.compile( r"^(?P<pre>(?:https?://)?(?:www\.)?(?:t\.me|telegram\.me|telegram\.dog)/)(?P<name>[A-Za-z0-9_]+)(?P<rest>[/?#].*)?$", re.I | re.S,)_TG_RX = re.compile(r"^(?P<pre>tg://resolve\?(?:[^#]*&)?domain=)(?P<name>[A-Za-z0-9_]+)(?P<rest>[&#].*)?$", re.I | re.S)
def _split(url: str): for rx in (_HTTP_RX, _TG_RX): m = rx.match(url) if m: return m return None
def _is_post_tail(tail: str) -> bool: return bool(re.match(r"/\d", tail)) or bool(re.match(r"&post=\d", tail))
def classify_url(url: str, old: str) -> Optional[str]: """'link' (t.me/old?start=..), 'post' (t.me/old/123 - a channel post) or None.""" m = _split(url or "") if not m or m.group("name").lower() != old.lower(): return None return "post" if _is_post_tail(m.group("rest") or "") else "link"
def swap_url(url: str, old: str, new: str) -> str: m = _split(url or "") if not m or m.group("name").lower() != old.lower(): return url return url[: m.start("name")] + new + url[m.end("name"):]
# ------------------------------------------------------------------- typed links in textdef _typed_regexes(old: str) -> list: n = re.escape(old) return [ re.compile( r"(?<![\w@./-])(?:https?://)?(?:www\.)?(?:t\.me|telegram\.me|telegram\.dog)/(?P<name>" + n + r")(?![A-Za-z0-9_])", re.I, ), re.compile(r"(?<![\w@./-])tg://resolve\?(?:[^\s&#]*&)?domain=(?P<name>" + n + r")(?![A-Za-z0-9_])", re.I), ]
def find_typed_spans(sur: str, old: str, include_posts: bool) -> tuple: spans: list = [] skipped = 0 for rx in _typed_regexes(old): for m in rx.finditer(sur): s, e = m.span("name") if _is_post_tail(sur[e:e + 8]) and not include_posts: skipped += 1 continue spans.append((s, e)) spans.sort() return spans, skipped
def apply_span_replacements(sur: str, entities: list, repls: list) -> tuple: """repls: sorted, non-overlapping (start, end, new_text) in UTF-16 units. Returns (new_text, new_entities) with every entity offset/length kept consistent.""" parts: list = [] last = 0 for s, e, nt in repls: parts.append(sur[last:s]) parts.append(nt) last = e parts.append(sur[last:]) new_text = "".join(parts)
def mp(x: int) -> int: acc = 0 for s, e, nt in repls: if x >= e: acc += len(nt) - (e - s) elif x > s: return s + acc + min(x - s, len(nt)) else: break return x + acc
out = [] for ent in entities: cp = copy.copy(ent) o = mp(ent.offset) end = mp(ent.offset + ent.length) cp.offset = o cp.length = max(0, end - o) out.append(cp) return new_text, out
# --------------------------------------------------------------------- whole message@dataclassclass MsgChange: message_id: int new_text: str new_entities: list new_markup: Optional[types.ReplyInlineMarkup] text_changed: bool entities_changed: bool n_buttons: int n_links: int n_typed: int mine: bool callbacks: bool
def compute_message_changes(msg, old: str, new: str, *, include_typed: bool = True, include_posts: bool = False) -> tuple: """Returns (MsgChange or None, number_of_skipped_post_links).""" rich = is_rich_message(msg) # the text of a rich message is blocks: only its buttons are changed text = "" if rich else (msg.message or "") ents = [] if rich else list(msg.entities or []) skipped = 0 n_typed = n_links = n_btn = 0
# 1) links typed as plain text (this changes the text itself) sur = add_surrogate(text) new_sur = sur new_ents = [copy.copy(e) for e in ents] if include_typed and text: spans, sk = find_typed_spans(sur, old, include_posts) skipped += sk if spans: new_sur, new_ents = apply_span_replacements(sur, ents, [(s, e, new) for s, e in spans]) n_typed = len(spans)
# 2) hyperlinks (text with a link behind it) for e in new_ents: if isinstance(e, types.MessageEntityTextUrl): kind = classify_url(e.url, old) if kind == "link" or (kind == "post" and include_posts): e.url = swap_url(e.url, old, new) n_links += 1 elif kind == "post": skipped += 1
# 3) buttons new_markup = None has_cb = False mk = msg.reply_markup if isinstance(mk, types.ReplyInlineMarkup): rows = [] for row in mk.rows: btns = [] for b in row.buttons: url = button_url(b) if url is not None: kind = classify_url(url, old) if kind == "link" or (kind == "post" and include_posts): btns.append(with_url(b, swap_url(url, old, new))) n_btn += 1 continue if kind == "post": skipped += 1 elif is_callback_button(b): has_cb = True btns.append(b) rows.append(types.KeyboardButtonRow(btns)) if n_btn: new_markup = types.ReplyInlineMarkup(rows)
if not (n_typed or n_links or n_btn): return None, skipped return ( MsgChange( message_id=msg.id, new_text=del_surrogate(new_sur), new_entities=new_ents, new_markup=new_markup, text_changed=bool(n_typed), entities_changed=bool(n_typed or n_links), n_buttons=n_btn, n_links=n_links, n_typed=n_typed, mine=bool(getattr(msg, "out", False)), callbacks=has_cb, ), skipped, )
def url_only_markup(markup, old: Optional[str] = None, new: Optional[str] = None, include_posts: bool = False): """Buttons for a copy of a post: link buttons only (other bots' buttons would be dead), with the username swapped when `old`/`new` are given. Returns (markup or None, number_of_buttons_not_copied).""" if not isinstance(markup, types.ReplyInlineMarkup): return None, 0 rows, dropped = [], 0 for row in markup.rows: btns = [] for b in row.buttons: url = button_url(b) if url is None: dropped += 1 continue if old and new: kind = classify_url(url, old) if kind == "link" or (kind == "post" and include_posts): b = with_url(b, swap_url(url, old, new)) btns.append(b) if btns: rows.append(types.KeyboardButtonRow(btns)) return (types.ReplyInlineMarkup(rows) if rows else None), dropped123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""The channel chooser used by every command that needs one of the connected channels.
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(5 to a row), and β βΆ underneath move to the previous / next 20. Pressing "3" means the third name of the list.Each button carries the channel's id, never its position, so a list that changed meanwhile can't pick the wrong one."""from __future__ import annotations
import refrom collections import Counterfrom typing import Callable, Optional, Sequence
from telethon import Button
from .tgutil import esc, short
PER_PAGE = 20 # channel names in one messagePER_ROW = 5 # number buttons in one rowNAME_MAX = 60 # a longer name is cut in the listPAGE_CB = "cpg" # callback prefix of the β βΆ buttons: cpg:<screen>:<argument>:<page>
_DIGITS = re.compile(r"(\d+)")
def natural_key(title: Optional[str]) -> tuple: """A to Z, numbers by value ("Anime 2" before "Anime 10"), upper and lower case alike.""" parts = _DIGITS.split(" ".join((title or "").split()).casefold()) return tuple((0, int(p), "") if p.isdigit() else (1, 0, p) for p in parts if p != "")
def ordered(chans: Sequence) -> list: """The channels in the order they are listed: by name, ascending (the id breaks ties).""" return sorted(chans, key=lambda c: (natural_key(c.title), c.id))
def page_count(total: int) -> int: return max(1, -(-total // PER_PAGE))
def clamp(page: int, total: int) -> int: return max(0, min(int(page), page_count(total) - 1))
def names_of(chans: Sequence, *, with_username: bool = False) -> list: """Display names (not yet escaped). Two channels with the same name get their @username (or id) added.""" keys = [" ".join((c.title or "").split()).casefold() for c in chans] twins = Counter(keys) out = [] for c, key in zip(chans, keys): name = short(c.title or "", NAME_MAX) or "Channel" if with_username and c.username: name += f" (@{c.username})" elif twins[key] > 1: name += f" (@{c.username})" if c.username else f" ({c.id})" out.append(name) return out
def render( chans: Sequence, page: int, *, head: str, kind: str, arg: str = "", choose: Optional[Callable] = None, extra_rows: Sequence = (), with_username: bool = False, hint: Optional[str] = "Tap the number of the channel.",) -> tuple: """(text, button rows) of one page.
head the question, already HTML kind, arg which screen this is - the β βΆ buttons carry them so the same screen can be drawn again choose channel -> callback data of its number button (None: a list to read, no number buttons) extra_rows buttons under the arrows (Cancel ...) hint the line under the list that says what the number buttons do (None: leave it out) """ chans = ordered(chans) total = len(chans) pages = page_count(total) page = clamp(page, total) first = page * PER_PAGE shown = chans[first : first + PER_PAGE] names = names_of(chans, with_username=with_username)[first : first + PER_PAGE] lines = [f"{first + i}. {esc(name)}" for i, name in enumerate(names, 1)] text = f"{head}\n\n" + "\n".join(lines) if pages > 1: text += f"\n\nPage {page + 1} of {pages} - channels {first + 1} to {first + len(shown)} of {total}" if choose is not None and hint: text += f"\n\n{hint}" rows: list = [] if choose is not None: nums = [Button.inline(str(first + i), choose(c)) for i, c in enumerate(shown, 1)] rows += [nums[i : i + PER_ROW] for i in range(0, len(nums), PER_ROW)] if pages > 1: # always both arrows: on the first page β goes to the last page, on the last page βΆ to the first rows.append( [ Button.inline("β", f"{PAGE_CB}:{kind}:{arg}:{(page - 1) % pages}"), Button.inline("βΆ", f"{PAGE_CB}:{kind}:{arg}:{(page + 1) % pages}"), ] ) rows += [list(r) for r in extra_rows] return text, rows123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226"""Links that point at other posts of the same channel (t.me/name/115, t.me/c/123456/115, tg://...&post=115).
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.Only the digits of the message id change; everything around them (?single, ?comment=3, the visible text) stays.Links can sit in three places: a hyperlink behind text, a link typed into the text, and a button."""from __future__ import annotations
import copyimport refrom dataclasses import dataclass, fieldfrom typing import Optional
from telethon import typesfrom telethon.helpers import add_surrogate, del_surrogate
from .linkswap import apply_span_replacementsfrom .richmsg import is_rich_messagefrom .tgutil import button_url, with_url
_HOST = r"(?:t\.me|telegram\.me|telegram\.dog)"_NAME = r"[A-Za-z][A-Za-z0-9_]{2,31}"# https://t.me/name/115 https://t.me/c/123456/115 (also t.me/s/name/115, the web preview)_WEB = re.compile( rf"^(?:https?://)?(?:www\.)?{_HOST}/(?:s/)?(?P<seg>c/(?P<cid>\d+)|(?P<name>{_NAME}))/(?P<id>\d+)(?![A-Za-z0-9_])", re.I)_TYPED = re.compile( rf"(?<![\w@./=?&#-])(?:https?://)?(?:www\.)?{_HOST}/(?:s/)?(?:c/\d+|{_NAME})/\d+(?![A-Za-z0-9_])", re.I)# tg://resolve?domain=name&post=115 tg://privatepost?channel=123456&post=115_TG = re.compile(r"^tg://(?P<kind>resolve|privatepost)\?(?P<query>[^#]*)", re.I)_POST_PARAM = re.compile(r"(?<=[?&])post=(\d+)")
@dataclass(frozen=True)class Ref: """A link to a post: which channel (username in lower case, or the numeric id) and where the id's digits sit."""
name: Optional[str] cid: Optional[int] msg_id: int start: int # the digits of the message id ... end: int seg_start: Optional[int] = None # ... and the channel part in front of them ("name" or "c/123"); web links only
def parse_ref(url: str) -> Optional[Ref]: """What `url` points at, if it is a link to a post of some channel; None for every other link.""" url = url or "" m = _WEB.match(url) if m: return Ref( name=m.group("name").lower() if m.group("name") else None, cid=int(m.group("cid")) if m.group("cid") else None, msg_id=int(m.group("id")), start=m.start("id"), end=m.end("id"), seg_start=m.start("seg"), ) m = _TG.match(url) if m: params = dict(p.split("=", 1) for p in m.group("query").split("&") if "=" in p) post = _POST_PARAM.search(url) if post is None: return None if m.group("kind").lower() == "resolve" and re.fullmatch(r"[A-Za-z0-9_]+", params.get("domain", "")): return Ref(params["domain"].lower(), None, int(post.group(1)), post.start(1), post.end(1)) if m.group("kind").lower() == "privatepost" and params.get("channel", "").isdigit(): return Ref(None, int(params["channel"]), int(post.group(1)), post.start(1), post.end(1)) return None
@dataclassclass PostLinks: """The links that point into one channel, and where its posts went: `ids` maps old message id -> new one.
By default the copies are in the same channel (/repost): only the message id changes. With `target_id` the copies are in another channel (/shift): the channel part of the link changes too."""
username: Optional[str] channel_id: int ids: dict = field(default_factory=dict) target_username: Optional[str] = None target_id: Optional[int] = None
@classmethod def for_channel(cls, ch, ids: Optional[dict] = None) -> "PostLinks": return cls(username=(ch.username or None), channel_id=int(ch.id), ids=ids if ids is not None else {})
# -------------------------------------------------------------------------------------- one url def ref_of(self, url: str) -> Optional[Ref]: """The reference in `url` if it points at a post of THIS channel.""" r = parse_ref(url) if r is None: return None if r.name is not None and self.username and r.name == self.username.lower(): return r if r.cid is not None and r.cid == self.channel_id: return r return None
def edit_of(self, url: str) -> Optional[tuple]: """(start, end, new text) to apply to `url` so it points at the copy of its post; None if it stays as it is.""" r = self.ref_of(url) if r is None or r.msg_id not in self.ids: return None new_id = str(self.ids[r.msg_id]) if self.target_id is None: return r.start, r.end, new_id if r.seg_start is None: # tg:// links are not moved to another channel return None channel = self.target_username or f"c/{self.target_id}" return r.seg_start, r.end, f"{channel}/{new_id}"
def remap_url(self, url: str) -> str: e = self.edit_of(url) return url if e is None else url[: e[0]] + e[2] + url[e[1] :]
# --------------------------------------------------------------------------------- whole message def count(self, text: str, entities, markup) -> int: """How many links in a message point at a post of this channel (whether or not the post has a new id).""" n = 0 sur = add_surrogate(text or "") for m in _TYPED.finditer(sur): if self.ref_of(m.group(0)): n += 1 for e in entities or []: if isinstance(e, types.MessageEntityTextUrl) and self.ref_of(e.url): n += 1 if isinstance(markup, types.ReplyInlineMarkup): for row in markup.rows: for b in row.buttons: u = button_url(b) if u is not None and self.ref_of(u): n += 1 return n
def remap_text(self, text: str, entities) -> tuple: """-> (text, entities, typed_links_changed, hyperlinks_changed). Offsets of all entities stay right.""" ents = list(entities or []) sur = add_surrogate(text or "") repls = [] for m in _TYPED.finditer(sur): e = self.edit_of(m.group(0)) if e is not None: repls.append((m.start() + e[0], m.start() + e[1], e[2])) if repls: new_sur, new_ents = apply_span_replacements(sur, ents, repls) else: new_sur, new_ents = sur, [copy.copy(e) for e in ents] hyper = 0 for e in new_ents: if isinstance(e, types.MessageEntityTextUrl): new_url = self.remap_url(e.url) if new_url != e.url: e.url = new_url hyper += 1 return del_surrogate(new_sur), new_ents, len(repls), hyper
def remap_markup(self, markup) -> tuple: """-> (markup, buttons_changed); the keyboard object is only rebuilt when a button changes.""" if not isinstance(markup, types.ReplyInlineMarkup): return markup, 0 rows, changed = [], 0 for row in markup.rows: btns = [] for b in row.buttons: u = button_url(b) new = self.remap_url(u) if u is not None else None if new is not None and new != u: btns.append(with_url(b, new)) changed += 1 else: btns.append(b) rows.append(types.KeyboardButtonRow(btns)) return (types.ReplyInlineMarkup(rows) if changed else markup), changed
@dataclassclass Relinked: """A message whose links to other posts of the channel were pointed at the copies."""
text: str entities: list markup: Optional[types.ReplyInlineMarkup] text_changed: bool # the text or its entities differ markup_changed: bool n_typed: int n_hyper: int n_buttons: int
@property def links(self) -> int: return self.n_typed + self.n_hyper + self.n_buttons
def relink_message(msg, links: PostLinks) -> Optional[Relinked]: """The new text / entities / buttons of `msg` once its links are remapped; None when nothing changes.""" if is_rich_message(msg): # the text of a rich message is blocks: only its buttons are changed text, entities, n_typed, n_hyper = "", [], 0, 0 else: text, entities, n_typed, n_hyper = links.remap_text(msg.message or "", msg.entities) markup, n_buttons = links.remap_markup(msg.reply_markup) if not (n_typed or n_hyper or n_buttons): return None return Relinked( text=text, entities=entities, markup=markup, text_changed=bool(n_typed or n_hyper), markup_changed=bool(n_buttons), n_typed=n_typed, n_hyper=n_hyper, n_buttons=n_buttons, )
def resolve_chain(step: dict) -> dict: """Several reposts in a row: {1: 5, 5: 9} -> {1: 9, 5: 9} (a post that moved twice points at its latest copy).""" out = {} for old in step: cur, seen = old, 0 while cur in step and seen < 100: cur, seen = step[cur], seen + 1 out[old] = cur return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""/shift -all: the destination channel gets the name, description and profile photo of the source channel.
Each part is done on its own, so one that fails (a missing admin right, a photo Telegram refuses) does not stop theothers. A part the source does not have (no description, no photo) is left as it is in the destination: nothing is everwiped. The notices Telegram adds to a channel when its name or photo changes are deleted again right away."""from __future__ import annotations
import loggingfrom dataclasses import dataclass, fieldfrom types import SimpleNamespacefrom typing import Optional
from telethon import errors, functions, types
from .repost_engine import delete_ids, new_messages_fromfrom .tgutil import esc, flood_retry, peer_of
log = logging.getLogger(__name__)
PARTS = ("name", "description", "photo")LABELS = {"name": "Name", "description": "Description", "photo": "Profile photo"}NEEDS_RIGHT = "the bot needs the βChange channel infoβ admin right in the destination"
@dataclassclass ProfileResult: """What happened to each part: part -> (status, detail). Status: done | same | none | failed."""
outcome: dict = field(default_factory=dict) title: Optional[str] = None # the destination's name after the run (None: it did not change)
@property def ok(self) -> bool: return all(s != "failed" for s, _ in self.outcome.values())
@property def done(self) -> list: return [p for p in PARTS if self.outcome.get(p, ("", ""))[0] == "done"]
@property def failed(self) -> list: return [(p, d) for p in PARTS for s, d in [self.outcome.get(p, ("", ""))] if s == "failed"]
def _real(photo): return None if photo is None or isinstance(photo, types.PhotoEmpty) else photo
async def read_profile(client, ch) -> SimpleNamespace: """The name, the description and the profile photo a channel shows right now.""" full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer_of(ch)))) chat = next((c for c in getattr(full, "chats", None) or [] if getattr(c, "id", None) == ch.id), None) fc = full.full_chat return SimpleNamespace( title=getattr(chat, "title", None), about=getattr(fc, "about", None) or "", photo=_real(getattr(fc, "chat_photo", None)) )
def _failure(e: BaseException) -> str: name = type(e).__name__ if name == "ChatAdminRequiredError": return NEEDS_RIGHT return name
async def _set_name(client, dst, title: str) -> tuple: try: out = await flood_retry(lambda: client(functions.channels.EditTitleRequest(channel=peer_of(dst), title=title))) except errors.ChatNotModifiedError: return "same", "" except errors.RPCError as e: return "failed", _failure(e) await _drop_notices(client, dst, out) return "done", title
async def _set_description(client, dst, about: str) -> tuple: try: await flood_retry(lambda: client(functions.messages.EditChatAboutRequest(peer=peer_of(dst), about=about))) except (errors.ChatAboutNotModifiedError, errors.ChatNotModifiedError): return "same", "" except errors.RPCError as e: return "failed", _failure(e) return "done", ""
async def _set_photo(client, dst, photo) -> tuple: try: data = await client.download_media(photo, file=bytes) if not data: return "failed", "the photo could not be downloaded" uploaded = await client.upload_file(data, file_name="channel_photo.jpg") out = await flood_retry( lambda: client( functions.channels.EditPhotoRequest(channel=peer_of(dst), photo=types.InputChatUploadedPhoto(file=uploaded)) ) ) except errors.ChatNotModifiedError: return "same", "" except errors.RPCError as e: return "failed", _failure(e) except Exception as e: # a download or upload problem is not a reason to stop the shift log.warning("copying the profile photo failed: %s %s", type(e).__name__, e) return "failed", type(e).__name__ await _drop_notices(client, dst, out) return "done", ""
async def _drop_notices(client, ch, result) -> None: """Remove the "channel name / photo changed" notices Telegram put into the channel.""" ids = [m.id for m in new_messages_from(result) if isinstance(m, types.MessageService)] if ids: await delete_ids(client, peer_of(ch), ids)
async def copy_profile(client, src, dst) -> ProfileResult: """Give `dst` the name, the description and the profile photo of `src`. Nothing is wiped: a part that the source does not have stays as the destination has it. Both arguments need `id` and `access_hash`.""" res = ProfileResult() try: s = await read_profile(client, src) except errors.RPCError as e: for p in PARTS: res.outcome[p] = ("failed", f"the source can't be read ({type(e).__name__})") return res try: d = await read_profile(client, dst) except errors.RPCError: d = SimpleNamespace(title=None, about=None, photo=None) # unknown: every part is simply tried
if not s.title: res.outcome["name"] = ("none", "") elif s.title == d.title: res.outcome["name"] = ("same", "") else: res.outcome["name"] = await _set_name(client, dst, s.title) if res.outcome["name"][0] == "done": res.title = s.title
if not s.about: res.outcome["description"] = ("none", "") elif s.about == d.about: res.outcome["description"] = ("same", "") else: res.outcome["description"] = await _set_description(client, dst, s.about)
if s.photo is None: res.outcome["photo"] = ("none", "") else: res.outcome["photo"] = await _set_photo(client, dst, s.photo) return res
def profile_lines(res: ProfileResult, dst_title: str = "") -> list: """Lines (HTML) about what was copied, for the end of a shift.""" shown = {"done": "copied", "same": "already the same", "none": "the source has none - left as it is"} parts, bad = [], [] for p in PARTS: status, detail = res.outcome.get(p, ("", "")) if status == "failed": bad.append(f"{LABELS[p]}: {esc(detail)}") elif status: parts.append(f"{LABELS[p].lower()} {shown[status]}") out = [] if parts: out.append("πΌ " + ("<b>" + esc(dst_title) + "</b>: " if dst_title else "") + ", ".join(parts) + ".") if bad: out.append("β οΈ Not copied - " + "; ".join(bad) + ".") return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343"""/swap engine: scan channels message by message, rewrite links, log every change, undo."""from __future__ import annotations
import asyncioimport loggingfrom dataclasses import dataclass, fieldfrom typing import Any, Awaitable, Callable, Optional
from telethon import errors, functions, types
from .handleswap import compute_handle_changesfrom .linkswap import compute_message_changesfrom .richmsg import entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_offrom .tgutil import ( build_markup, de_entities, edit_raw, flood_retry, media_info, peer_of, ser_entities, ser_markup, state_of,)
log = logging.getLogger(__name__)
CHUNK = 100 # Telegram returns at most 100 messages per requestFALLBACK_EMPTY_BATCHES = 15 # used only when the newest message id can't be determinedABORT_AFTER = 5 # stop a channel after this many identical Telegram refusals in a row
@dataclassclass ScanOptions: old: str new: str include_typed: bool = True include_posts: bool = False last: Optional[int] = None mode: str = "links" # "links": the username inside t.me links (/swap); "handles": '@name' written in a post (/handleswap)
def compute_changes(m, opts: ScanOptions) -> tuple: """What this run would change in message `m`: (MsgChange or None, skipped).""" if opts.mode == "handles": return compute_handle_changes(m, opts.old, opts.new) return compute_message_changes( m, opts.old, opts.new, include_typed=opts.include_typed, include_posts=opts.include_posts )
@dataclassclass ChangeInfo: message_id: int buttons: int = 0 links: int = 0 typed: int = 0 mine: bool = False callbacks: bool = False
@dataclassclass ChannelScan: channel: Any can_edit_others: bool = True top: int = 0 first: int = 1 scanned: int = 0 infos: dict = field(default_factory=dict) skipped_post_links: int = 0 not_editable: int = 0 error: Optional[str] = None rights: Any = None
@property def total(self) -> int: return len(self.infos)
@property def foreign(self) -> int: return sum(1 for i in self.infos.values() if not i.mine)
@dataclassclass ApplyResult: edited: int = 0 unchanged: int = 0 missing: int = 0 no_perm: int = 0 failed: list = field(default_factory=list) aborted: Optional[str] = None # error name that made us stop early
@dataclassclass UndoResult: restored: int = 0 failed: list = field(default_factory=list)
async def fetch_messages(client, peer, ids: list) -> list: res = await flood_retry(lambda: client.get_messages(peer, ids=ids)) return list(res)
async def get_top_id(client, peer) -> Optional[int]: """Upper bound for the newest message id: the channel's event counter (pts) is never lower.""" try: full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer))) pts = getattr(full.full_chat, "pts", None) if pts: return int(pts) except Exception as e: log.info("could not read channel counter: %s", e) return None
def is_skippable(m) -> bool: return m is None or isinstance(m, (types.MessageEmpty, types.MessageService))
async def scan_channel( client, ch, opts: ScanOptions, *, can_edit_others: bool = True, mine_ids: Optional[set] = None, progress: Optional[Callable[[ChannelScan], Awaitable[None]]] = None,) -> ChannelScan: scan = ChannelScan(channel=ch, can_edit_others=can_edit_others) peer = peer_of(ch) mine_ids = mine_ids or set() top = await get_top_id(client, peer) first = 1 if opts.last and top: first = max(1, top - opts.last + 1) scan.first, scan.top = first, top or 0 a, empty_run = first, 0 while True: if top is not None and a > top: break hi = a + CHUNK - 1 if top is None else min(a + CHUNK - 1, top) msgs = await fetch_messages(client, peer, list(range(a, hi + 1))) found = False for m in msgs: if m is None or isinstance(m, types.MessageEmpty): continue found = True if isinstance(m, types.MessageService): continue change, skipped = compute_changes(m, opts) scan.skipped_post_links += skipped if not change: continue mine = change.mine or m.id in mine_ids if not mine and not can_edit_others: scan.not_editable += 1 continue scan.infos[m.id] = ChangeInfo( m.id, change.n_buttons, change.n_links, change.n_typed, mine, change.callbacks ) scan.scanned = hi if top is None: empty_run = 0 if found else empty_run + 1 if empty_run >= FALLBACK_EMPTY_BATCHES: break if progress: await progress(scan) a = hi + 1 if top is None: scan.top = scan.scanned return scan
def preview_flag(m): if isinstance(m.media, types.MessageMediaWebPage): return True return False if m.media is None else None
async def _do_edit(client, peer, m, change, markup, preview) -> None: if change.text_changed or change.entities_changed: await edit_raw( client, peer, m.id, text=change.new_text, entities=change.new_entities, markup=markup, preview=preview ) else: # only button links changed: leave the text untouched await edit_raw(client, peer, m.id, markup=markup)
async def apply_channel( client, db, scan: ChannelScan, opts: ScanOptions, batch_id: str, user_id: int, *, edit_delay: float = 1.2, progress: Optional[Callable[[ApplyResult], Awaitable[None]]] = None,) -> ApplyResult: ch = scan.channel peer = peer_of(ch) mine_ids = await db.mine_message_ids(ch.id) res = ApplyResult() ids = sorted(scan.infos) buf: list = [] streak, last_name = 0, None
async def flush() -> None: nonlocal buf if buf: batch, buf = buf, [] await db.record_changes(batch_id, ch.id, batch, user_id)
try: for i in range(0, len(ids), CHUNK): chunk = ids[i:i + CHUNK] msgs = await fetch_messages(client, peer, chunk) for mid, m in zip(chunk, msgs): if is_skippable(m): res.missing += 1 continue # re-check against the live message: it may have been edited since the scan change, _ = compute_changes(m, opts) if not change: res.unchanged += 1 continue if not (change.mine or m.id in mine_ids) and not scan.can_edit_others: res.no_perm += 1 continue preview = preview_flag(m) markup = change.new_markup if change.new_markup is not None else m.reply_markup old_state = state_of(m.message, m.entities, m.reply_markup, preview) rich = is_rich_message(m) if rich: # its text is blocks this run never touches: undo puts the buttons back and nothing else old_state["rich"] = True try: await flood_retry(lambda: _do_edit(client, peer, m, change, markup, preview)) except errors.MessageNotModifiedError: res.unchanged += 1 continue except errors.RPCError as e: name = type(e).__name__ log.warning("edit of %s/%s failed: %s", ch.id, m.id, name) res.failed.append((m.id, name)) streak = streak + 1 if name == last_name else 1 last_name = name if streak >= ABORT_AFTER: res.aborted = name break continue streak, last_name = 0, None res.edited += 1 kind, fid = media_info(m) adopt = { "text": change.new_text, "entities": ser_entities(change.new_entities), "buttons": ser_markup(markup), "link_preview": bool(preview), } if kind: adopt["media_kind"], adopt["media_file_id"] = kind, fid new_state = state_of(change.new_text, change.new_entities, markup, preview) if rich: new_state["rich"] = True saved = await db.find_by_message(ch.id, m.id) if saved is not None and rich_of(saved) is not None: del adopt["text"], adopt["entities"] # the saved copy keeps what it was sent from else: # a rich message nobody saved yet: it is taken over as its blocks adopt["text"] = plain_of_message(m) adopt["entities"] = [rich_entry(rich_from_received(m.rich_message))] buf.append( { "message_id": m.id, "old_state": old_state, "new_state": new_state, "adopt": adopt, } ) if len(buf) >= 10: await flush() if progress: await progress(res) await asyncio.sleep(edit_delay) if res.aborted: break finally: await flush() return res
async def undo_batch( client, db, batch_id: str, *, edit_delay: float = 1.2, progress: Optional[Callable[[UndoResult], Awaitable[None]]] = None,) -> UndoResult: """Put every post touched by a /swap run back exactly as it was.""" res = UndoResult() channels: dict = {} done_ids: list = [] restored: list = [] for c in await db.batch_changes(batch_id): if c.channel_id not in channels: channels[c.channel_id] = await db.get_channel(c.channel_id) ch = channels[c.channel_id] if ch is None: res.failed.append((c.message_id, "ChannelRemoved")) continue old = c.old_state or {} try: if old.get("rich"): # a rich message: only its buttons were changed, so only they are put back markup = build_markup(old.get("buttons")) if markup is not None: await flood_retry(lambda: edit_raw(client, peer_of(ch), c.message_id, markup=markup)) else: await flood_retry( lambda: edit_raw( client, peer_of(ch), c.message_id, text=old.get("text", ""), entities=de_entities(old.get("entities")), markup=build_markup(old.get("buttons")), preview=old.get("preview"), ) ) except errors.MessageNotModifiedError: pass except errors.RPCError as e: log.warning("undo of %s/%s failed: %s", c.channel_id, c.message_id, e) res.failed.append((c.message_id, type(e).__name__)) continue res.restored += 1 done_ids.append(c.id) restored.append((c.channel_id, c.message_id, old)) if progress: await progress(res) await asyncio.sleep(edit_delay) await db.finish_undo(batch_id, done_ids, restored, all_done=not res.failed) return res1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372"""Repost a whole channel in order.
Every post is copied to the end of the channel (silently), in the same order as the original: 1. a post that needs no change (no buttons, no link to swap) is copied by Telegram itself (messages.forwardMessages with drop_author): text, formatting, quotes, media and albums stay exact; 2. a post with buttons, or with links to swap, is created again in ONE request that carries its final text, formatting and buttons - exactly how the bot publishes a post of its own - and is then read back to make sure the buttons really are there (a copy that is edited afterwards can end up without them); 3. if the channel forbids forwarding, every post is created like in 2.Links can be swapped on the way, the new posts are registered in the database, and the old posts are removedlater in a separate step. Nothing here deletes anything unless asked to (delete_copies).
What a plain copy would lose is put back as well: * a post that answers another post is posted as an answer to the COPY of that post (a reply can only be set when a post is created, so such a post is always created again instead of copied); * a link to another post of the channel (t.me/name/115) is pointed at the copy of that post - at once when the copy already exists, afterwards (finalize_repost) for posts that are copied later; * a post that was pinned has its copy pinned at the end.
A post that TELEGRAM restricts (a copyright strike: the whole channel is "unavailable due to copyright infringement",or the post carries a restriction mark, or Telegram's apps show "This message couldn't be displayed on your device dueto copyright infringement" instead of the post) is not copied as Telegram hands it out now. /shift rebuilds such a postfrom what My posts saved of it (text, formatting, buttons, media) - for a restricted CHANNEL every post that has a savedcopy, however intact Telegram's version looks. A post without a saved copy is copied as Telegram hands it out when thatis the post itself, and skipped (and reported) when it is only Telegram's notice. Telegram's notice is never posted, fromwhichever source. /repost leaves a post whose content Telegram holds back alone.Every copy of a restricted source is read back: if Telegram itself hides the new post, that is reported (copy_loop)."""from __future__ import annotations
import asyncioimport copyimport loggingfrom dataclasses import dataclass, fieldfrom typing import Any, AsyncIterator, Awaitable, Callable, Optional
from telethon import errors, functions, types, utils
from .buttons_sync import ButtonsNotShown, ensure_markup, link_urlsfrom .crosslinks import CrossResult, relink_after_repostfrom .linkswap import compute_message_changes, url_only_markupfrom .postlinks import PostLinks, relink_messagefrom .replace_engine import CHUNK, FALLBACK_EMPTY_BATCHES, fetch_messages, is_skippable, preview_flagfrom .restrictions import PLACEHOLDER_NOTE, is_placeholder_text, message_restriction, probe_channelfrom .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of, rich_from_received, rich_of, with_richfrom .tgutil import ( FATAL, build_markup, classify_media, de_entities, edit_raw, flood_retry, media_from_ref, media_ref, peer_of, ser_entities, ser_markup,)
log = logging.getLogger(__name__)
ABORT_AFTER = 8 # consecutive posts that could not be copied -> stop
@dataclassclass RepostOptions: old: Optional[str] = None new: Optional[str] = None include_typed: bool = True include_posts: bool = False last: Optional[int] = None # trial run: only the newest N post ids
@property def swaps(self) -> bool: return bool(self.old and self.new)
@dataclassclass Final: """What a copy of a post should look like."""
text: str entities: list markup: Optional[types.ReplyInlineMarkup] preview: Optional[bool] text_changed: bool n_buttons: int = 0 n_links: int = 0 n_typed: int = 0 dropped: int = 0 # other bots' buttons that are not copied n_post_links: int = 0 # links to other posts of the same channel (whatever their new id will be) n_relinked: int = 0 # of those, how many were already pointed at a copy rich: Optional[Rich] = None # the post is a rich message: this is what the copy is made from (text / entities are empty)
def rich_for(src) -> Optional[Rich]: """The rich message that `src` is - a live post, or a stand-in made from a saved post - or None for an ordinary post.""" saved = getattr(src, "rich_saved", None) if saved is not None: return saved rm = getattr(src, "rich_message", None) return rich_from_received(rm) if rm is not None else None
def final_state(src, opts: RepostOptions, links: Optional[PostLinks] = None) -> Final: """What the copy of `src` should look like. `links` (optional) points links to other posts of the channel at the copies that exist so far (links.ids: old message id -> new one).""" change = None if opts.swaps: change, _ = compute_message_changes( src, opts.old, opts.new, include_typed=opts.include_typed, include_posts=opts.include_posts ) rich = rich_for(src) text = change.new_text if change else (src.message or "") entities = list(change.new_entities) if change else list(src.entities or []) if rich is not None: # a rich message's text is blocks: nothing of it is changed here, only its buttons text, entities = "", [] # text mentions need an access hash to be re-sent; they are rare in channel posts entities = [e for e in entities if not isinstance(e, types.MessageEntityMentionName)] markup, dropped = url_only_markup( src.reply_markup, opts.old if opts.swaps else None, opts.new if opts.swaps else None, opts.include_posts ) n_post_links = n_relinked = 0 text_changed = bool(change and change.entities_changed) if links is not None: n_post_links = links.count(text, entities, markup) if n_post_links and links.ids: text, entities, n_typed, n_hyper = links.remap_text(text, entities) markup, n_buttons = links.remap_markup(markup) n_relinked = n_typed + n_hyper + n_buttons text_changed = text_changed or bool(n_typed or n_hyper) # Send exactly what is saved: go through the stored form that "My posts" also uses to build its edits. markup = build_markup(ser_markup(markup)) if markup is not None else None entities = de_entities(ser_entities(entities)) return Final( text=text, entities=entities, markup=markup, preview=preview_flag(src), text_changed=text_changed, n_buttons=change.n_buttons if change else 0, n_links=change.n_links if change else 0, n_typed=change.n_typed if change else 0, dropped=dropped, n_post_links=n_post_links, n_relinked=n_relinked, rich=rich, )
# ---------------------------------------------------------------------------- replies and pinsclass ReplyParentMissing(RuntimeError): """A post answers another post whose copy does not exist (yet): copying it now would lose the answer."""
def reply_parent(msg) -> Optional[int]: """The message id a post answers (in the same channel), or None.""" h = getattr(msg, "reply_to", None) if h is None or getattr(h, "reply_to_peer_id", None) is not None or getattr(h, "forum_topic", None): return None return getattr(h, "reply_to_msg_id", None) or None
def new_parent(msg, idmap: dict, seen: set) -> Optional[int]: """The copy of the post `msg` answers. None when it answers nothing, or the post it answered is gone / outside the range being copied. Raises ReplyParentMissing when that post was read in this run but has no copy.""" pid = reply_parent(msg) if pid is None: return None if pid in idmap: return idmap[pid] if pid in seen: raise ReplyParentMissing(f"post {msg.id} answers post {pid}, which has not been copied") return None
def new_messages_from(result) -> list: """The messages created by a send / forward request, oldest first.""" out = [] for u in getattr(result, "updates", None) or []: if isinstance(u, (types.UpdateNewChannelMessage, types.UpdateNewMessage)): out.append(u.message) out.sort(key=lambda m: m.id) return out
# ------------------------------------------------------ posts Telegram holds back (copyright strike ...)SavedLookup = Callable[[list], Awaitable[dict]] # message ids -> {message id: the saved post of My posts}
def saved_lookup(db, channel_id: int) -> SavedLookup: """How the copy loop and the plan look up what My posts saved of the posts of one channel."""
async def lookup(ids: list) -> dict: return {p.message_id: p for p in await db.posts_at(channel_id, ids)}
return lookup
def usable_row(row) -> bool: """A saved post that can take the place of a restricted post: it has something to post, and what it says is not Telegram's notice (a saved copy that an older version made from a restricted post can hold the notice).""" if row is None: return False text = row.text or "" if is_placeholder_text(text): return False return bool(text.strip() or row.media_file_id)
def copy_source(unit: list, rows: dict, *, restricted: Optional[str] = None, use_saved: bool = False) -> tuple: """Where the copy of this post (or album) comes from -> (source, why).
"live" - as Telegram hands the post out: nothing restricts it, or Telegram restricts it but still hands out the post itself and there is no saved copy to use instead; "saved" - from what My posts saved of it: Telegram restricts the channel (`restricted`) or the post (a copyright strike) and My posts has every part of it. Only when `use_saved` (/shift) - the saved copy wins even when Telegram's version still looks intact, because that is the owner's rule for a struck channel; "skip" - not copied: what Telegram hands out is its notice - or nothing - and My posts can't take over.
`why` is Telegram's own wording about the restriction, None when nothing restricts the post.""" marked = next((w for w in (message_restriction(m) for m in unit) if w), None) why = marked or restricted if why is None: return "live", None if use_saved and all(usable_row(rows.get(m.id)) for m in unit): return "saved", why for m in unit: live = m.message or "" if is_placeholder_text(live) or ( not live.strip() and getattr(m, "media", None) is None and rich_for(m) is None ): return "skip", why return "live", why
def stand_in(m, row): """A copy of the live message `m` that shows what My posts saved for it - text, formatting, buttons, media. It takes the place of a post Telegram holds back (the live message keeps what Telegram still tells: id, album, reply).""" s = copy.copy(m) s.message = row.text or "" s.entities = de_entities(row.entities) s.rich_message = None # what it shows is what My posts saved ... s.rich_saved = rich_of(row) # ... which is a rich message when the saved post is one s.reply_markup = build_markup(row.buttons) s.media = None s.saved_ref = None # the saved media reference (resend_saved may need it again without its file reference) if row.media_file_id: try: s.media = media_from_ref(row.media_file_id) s.saved_ref = row.media_file_id except ValueError: # a reference that can't be read: the post goes out without media log.warning("the saved media of post %s can't be read", m.id) if s.media is None and row.link_preview: s.media = types.MessageMediaWebPage(webpage=types.WebPageEmpty(id=0)) return s
def stand_ins(unit: list, rows: dict) -> Optional[list]: """The saved copies that stand in for a restricted post, or None when My posts does not have all of them (or one of them has nothing to post, or holds only Telegram's notice).""" out = [] for m in unit: row = rows.get(m.id) if not usable_row(row): return None out.append(stand_in(m, row)) return out
FILE_MEDIA = (types.MessageMediaPhoto, types.MessageMediaDocument) # a photo, video, document, voice, sticker ...
def has_file(m) -> bool: """The post carries a file. A link preview, a poll, a location or a contact is not a file.""" return isinstance(getattr(m, "media", None), FILE_MEDIA)
def without_files(unit: list) -> tuple: """/shift --no-media: the posts of `unit` as they look without their files -> (those that still have a text, the number of files left out). A post that was only a file has nothing left to post and is dropped.""" out, lost = [], 0 for m in unit: c = m if has_file(m): c = copy.copy(m) c.media, c.saved_ref, c.invert_media = None, None, None lost += 1 if (c.message or "").strip() or rich_for(c) is not None: out.append(c) return out, lost
async def single_posts(units: AsyncIterator[list]) -> AsyncIterator[list]: """/shift --no-media: an album can't be rebuilt without its pictures, so every message of it is a post of its own.""" async for unit in units: for m in unit: yield [m]
def saved_message(row, channel_id: int): """A post built from its saved copy alone, for a channel that can't be read at all. Only the saved parts exist: no album, no reply, no pin.""" base = types.Message( id=row.message_id, peer_id=types.PeerChannel(channel_id), date=row.sent_at or row.created_at, message="" ) return stand_in(base, row)
def saved_rows_between(rows: list, first: Optional[int], last: Optional[int]) -> list: """The saved posts (oldest first, one per message id) that can be posted - they have something to post that is not Telegram's notice - between two message ids.""" out, seen = [], set() for row in sorted(rows, key=lambda r: (r.message_id or 0, r.id)): mid = row.message_id if mid is None or mid in seen or (first and mid < first) or (last and mid > last): continue if usable_row(row): seen.add(mid) out.append(row) return out
async def saved_units(db, channel_id: int, first: int, last: int) -> AsyncIterator[list]: """The saved posts of a channel between two message ids, oldest first - each one a unit of its own.""" for row in saved_rows_between(await db.sent_posts_from(channel_id, first), first, last): yield [saved_message(row, channel_id)]
# ------------------------------------------------------------------------------- planning@dataclassclass RepostPlan: channel: Any first: int = 1 last: int = 0 # newest existing message id when the plan was made scanned: int = 0 units: int = 0 # posts (an album counts once) messages: int = 0 albums: int = 0 text: int = 0 media: int = 0 polls: int = 0 other: int = 0 service: int = 0 link_posts: int = 0 n_buttons: int = 0 n_links: int = 0 n_typed: int = 0 dropped_posts: int = 0 post_link_posts: int = 0 # posts with a link to another post of this channel post_links: int = 0 pinned: int = 0 # pinned posts (their copies get pinned) replies: int = 0 # posts that answer another post held_saved: int = 0 # restricted posts that are copied from what My posts saved of them (counted in units) held_skipped: int = 0 # restricted posts that can't be copied: only Telegram's notice is left (not counted in units) live_restricted: int = 0 # restricted posts without a saved copy that are copied as Telegram hands them out no_media: bool = False # /shift --no-media: the files are left out files_left_out: int = 0 # ... posts that are copied as text without their file (counted in units) file_only: int = 0 # ... posts that are only a file: nothing to copy (not counted in units) held_why: Optional[str] = None # what Telegram says about them channel_restricted: Optional[str] = None # what Telegram says when it restricts the whole channel from_db: bool = False # the channel can't be read: the plan (and the copy) is made from My posts alone unreadable: Optional[str] = None # ... because of this partial: bool = False error: Optional[str] = None
def eta_seconds(self, delay: float) -> int: return int(self.units * (delay + 1.0))
def tally(plan: RepostPlan, m, opts: RepostOptions, links: PostLinks) -> None: """Count one message (as it will be copied) into the plan.""" plan.messages += 1 media = m.media if media is None or isinstance(media, types.MessageMediaWebPage): plan.text += 1 elif isinstance(media, (types.MessageMediaPhoto, types.MessageMediaDocument)): plan.media += 1 elif isinstance(media, types.MessageMediaPoll): plan.polls += 1 else: plan.other += 1 f = final_state(m, opts, links) if f.n_buttons or f.n_links or f.n_typed: plan.link_posts += 1 plan.n_buttons += f.n_buttons plan.n_links += f.n_links plan.n_typed += f.n_typed if f.dropped: plan.dropped_posts += 1 if f.n_post_links: plan.post_link_posts += 1 plan.post_links += f.n_post_links if getattr(m, "pinned", False): plan.pinned += 1 if reply_parent(m) is not None: plan.replies += 1
def plan_from_saved( ch, rows: list, opts: RepostOptions, *, first_id=None, last_id=None, unreadable=None, no_media: bool = False) -> RepostPlan: """The plan of a copy made from My posts alone (the channel can't be read): one post per saved message.""" plan = RepostPlan( channel=ch, partial=bool(first_id or last_id), from_db=True, unreadable=unreadable, no_media=no_media ) links = PostLinks.for_channel(ch) chosen = saved_rows_between(rows, first_id, last_id) for row in chosen: m = saved_message(row, ch.id) if no_media: kept, lost = without_files([m]) if not kept: plan.file_only += 1 continue m, plan.files_left_out = kept[0], plan.files_left_out + lost plan.units += 1 tally(plan, m, opts, links) if chosen: plan.first, plan.last = chosen[0].message_id, chosen[-1].message_id plan.scanned = plan.last else: plan.first, plan.last = first_id or 1, last_id or 0 if not plan.units: plan.error = "There is nothing to copy." if plan.file_only: plan.error = "Every saved post in this range is only a file, so without files there is nothing to copy." return plan
async def find_last_id(client, peer, top: int) -> Optional[int]: """Newest existing message id, searching backwards from the channel counter.""" a = top for _ in range(300): lo = max(1, a - CHUNK + 1) msgs = await fetch_messages(client, peer, list(range(lo, a + 1))) ids = [m.id for m in msgs if m is not None and not isinstance(m, types.MessageEmpty)] if ids: return max(ids) if lo == 1: return None a = lo - 1 return None
async def plan_repost( client, ch, opts: RepostOptions, *, progress: Optional[Callable[[RepostPlan], Awaitable[None]]] = None, first_id: Optional[int] = None, last_id: Optional[int] = None, saved: Optional[SavedLookup] = None, use_saved: bool = False, no_media: bool = False,) -> RepostPlan: """Read the channel and count what a copy would do. first_id / last_id limit the range (used by /shift). `saved` looks up My posts' copies of the channel's posts; with `use_saved` a post Telegram holds back is counted as the saved post it will be copied from (/shift), without it such a post is left out (/repost). With `no_media` the files are left out of the copies (/shift --no-media): a post that is only a file has nothing left to copy.""" peer = peer_of(ch) plan = RepostPlan(channel=ch, partial=bool(opts.last), no_media=no_media) try: top, plan.channel_restricted, _ = await probe_channel(client, peer) except Exception as e: # the counter is only a help: without it the ids are read until nothing more turns up log.info("could not read channel counter: %s", e) top = None first = 1 if opts.last: if top is None: plan.error = "I can't tell which post is the newest, so --last can't be used here." return plan newest = await find_last_id(client, peer, top) if newest is None: plan.error = "The channel has no posts." return plan first, top = max(1, newest - opts.last + 1), newest if first_id: first = max(first, first_id) plan.partial = True if last_id: top = last_id if top is None else min(top, last_id) plan.partial = True plan.first = first links = PostLinks.for_channel(ch) a, empty_run, prev_gid, max_seen = first, 0, None, 0 while True: if top is not None and a > top: break hi = a + CHUNK - 1 if top is None else min(a + CHUNK - 1, top) found = False rows = await saved(list(range(a, hi + 1))) if saved else {} for m in await fetch_messages(client, peer, list(range(a, hi + 1))): if m is None or isinstance(m, types.MessageEmpty): continue found = True max_seen = max(max_seen, m.id) if isinstance(m, types.MessageService): plan.service += 1 continue gid = getattr(m, "grouped_id", None) new_unit = no_media or gid is None or gid != prev_gid # without files an album is a post per message row = rows.get(m.id) # a struck channel changes how /shift copies (My posts first); /repost copies as before, post by post source, why = copy_source( [m], rows, restricted=plan.channel_restricted if use_saved else None, use_saved=use_saved ) if why: plan.held_why = plan.held_why or why if source == "skip": plan.held_skipped += 1 if new_unit else 0 # nothing to copy it from prev_gid = gid continue if source == "saved": m = stand_in(m, row) # counted as the saved post it will be copied from if no_media: kept, lost = without_files([m]) if not kept: # nothing but a file: nothing to copy without it plan.file_only += 1 prev_gid = gid continue m, plan.files_left_out = kept[0], plan.files_left_out + lost if source == "saved": plan.held_saved += 1 if new_unit else 0 elif why: plan.live_restricted += 1 if new_unit else 0 if new_unit: plan.units += 1 if gid is not None and not no_media: plan.albums += 1 prev_gid = gid tally(plan, m, opts, links) plan.scanned = hi if top is None: empty_run = 0 if found else empty_run + 1 if empty_run >= FALLBACK_EMPTY_BATCHES: break if progress: await progress(plan) a = hi + 1 plan.last = max_seen if not plan.units: plan.error = "There is nothing to copy." if plan.held_skipped: plan.error = ( "Telegram holds back every post in this range (it shows a notice instead of the post) and My posts has " "no saved copy of them, so there is nothing to copy." ) elif plan.file_only: plan.error = "Every post in this range is only a file, so without files there is nothing to copy." return plan
# ---------------------------------------------------------------------------------- copyingasync def iter_units(client, peer, first: int, last: int) -> AsyncIterator[list]: """The posts between two ids, oldest first. An album is one unit (a list of messages).""" group: list = [] a = first while a <= last: hi = min(a + CHUNK - 1, last) for m in await fetch_messages(client, peer, list(range(a, hi + 1))): if is_skippable(m): continue gid = getattr(m, "grouped_id", None) if group and gid != group[0].grouped_id: yield group group = [] group.append(m) if gid is None: yield group group = [] a = hi + 1 if group: yield group
async def delete_ids(client, peer, ids: list) -> None: if not ids: return try: await flood_retry(lambda: client(functions.channels.DeleteMessagesRequest(channel=peer, id=list(ids)))) except errors.RPCError as e: log.warning("could not remove messages %s: %s", ids, type(e).__name__)
async def forward_unit(client, src_peer, unit: list, dst_peer=None) -> list: """Let Telegram copy the posts (no "forwarded from" header). `dst_peer` defaults to the same channel.""" ids = [m.id for m in unit] to_peer = dst_peer if dst_peer is not None else src_peer result = await flood_retry( lambda: client( functions.messages.ForwardMessagesRequest( from_peer=src_peer, id=ids, to_peer=to_peer, silent=True, drop_author=True ) ) ) return new_messages_from(result)
def _inverted(m) -> Optional[bool]: return True if getattr(m, "invert_media", False) else None
def reply_header(reply_to: Optional[int]): """The `reply_to` argument of the send requests: answer message `reply_to` of the same channel.""" return types.InputReplyToMessage(reply_to_msg_id=reply_to) if reply_to else None
async def resend_unit(client, peer, unit: list, finals: list, reply_to: Optional[int] = None) -> list: """Rebuild a post from its parts (used when copying is not allowed, or the copy must differ from the original). `reply_to`: message id (in the channel `peer`) the new post answers.""" reply = reply_header(reply_to) sender = None if len(unit) == 1 and getattr(finals[0], "rich", None) is not None: rich_final = finals[0] # a rich message: Telegram builds it again from its blocks (or its HTML / Markdown)
async def send_rich_final(): return await with_rich( rich_final.rich, lambda inp: client( functions.messages.SendMessageRequest( peer=peer, message="", rich_message=inp, reply_markup=rich_final.markup, silent=True, reply_to=reply ) ), )
sender = send_rich_final elif len(unit) > 1: singles = [ types.InputSingleMedia(media=utils.get_input_media(m.media), message=f.text, entities=f.entities or None) for m, f in zip(unit, finals) ]
def make(): return functions.messages.SendMultiMediaRequest( peer=peer, multi_media=singles, silent=True, invert_media=_inverted(unit[0]), reply_to=reply )
else: m, f = unit[0], finals[0] if m.media is None or isinstance(m.media, types.MessageMediaWebPage):
def make(): return functions.messages.SendMessageRequest( peer=peer, message=f.text, entities=f.entities or None, reply_markup=f.markup, no_webpage=True if f.preview is False else None, invert_media=_inverted(m), silent=True, reply_to=reply, )
else: media = utils.get_input_media(m.media)
def make(): return functions.messages.SendMediaRequest( peer=peer, media=media, message=f.text, entities=f.entities or None, reply_markup=f.markup, invert_media=_inverted(m), silent=True, reply_to=reply, )
result = await flood_retry(sender if sender is not None else (lambda: client(make()))) news = new_messages_from(result) if len(news) != len(unit): await delete_ids(client, peer, [n.id for n in news]) raise RuntimeError(f"Telegram created {len(news)} messages instead of {len(unit)}") return news
@dataclassclass _State: mode: str = "forward" # becomes "resend" when the channel forbids forwarding forwarded: int = 0 rebuilt: int = 0 repaired: int = 0 # new posts whose buttons had to be set again after posting replies: int = 0 # new posts created as an answer to the copy of the post the original answered reply_lost: int = 0 # answers that could only be copied without the reply from_saved: int = 0 # posts Telegram holds back that were rebuilt from their saved copy in My posts media_lost: list = field(default_factory=list) # old ids of those that had to go out without their media
def is_pure(src, f: Final, reply_to: Optional[int] = None) -> bool: """True when a server-side copy is already the final post: nothing to swap, no keyboard to rebuild and no reply to set (a reply can only be given when a post is created).""" return not f.text_changed and src.reply_markup is None and not reply_to
def _has_media(unit: list) -> bool: return any(m.media is not None and not isinstance(m.media, types.MessageMediaWebPage) for m in unit)
def _without_reference(unit: list) -> list: """The same saved posts with the file reference of their media left out (it may have expired).""" out = [] for m in unit: b = copy.copy(m) if getattr(m, "saved_ref", None): b.media = media_from_ref(m.saved_ref, blank_reference=True) out.append(b) return out
async def resend_saved(client, dst_peer, unit: list, finals: list, st: _State, reply_to: Optional[int] = None) -> list: """Create the copies of posts that Telegram holds back, from the saved posts that stand in for them (stand_in). Their media is sent from the saved reference: when Telegram says the reference is out of date it is tried without it, and a single post whose text is saved goes out without its media when Telegram still refuses the file (a file taken down for copyright is refused) - counted in st.media_lost.""" failure: Optional[BaseException] = None for attempt in (unit, None): if attempt is None: if failure is None or not _has_media(unit): break attempt = _without_reference(unit) try: return await resend_unit(client, dst_peer, attempt, finals, reply_to) except (TypeError, ValueError, errors.RPCError) as e: if isinstance(e, errors.RPCError) and type(e).__name__ in FATAL: raise failure = failure or e if not _has_media(unit): raise if len(unit) == 1 and (finals[0].text or "").strip(): unit[0].media = None # what goes out now has no media, and neither has its entry in My posts news = await resend_unit(client, dst_peer, unit, finals, reply_to) st.media_lost.append(unit[0].id) return news raise failure # type: ignore[misc]
async def copy_unit( client, peer, unit: list, finals: list, st: _State, reply_to: Optional[int] = None, dst_peer=None, *, from_saved: bool = False, no_forward: bool = False,) -> list: """Create the copy of one post (or album) at the end of `dst_peer` (default: the same channel `peer`). `from_saved`: the posts in `unit` are saved copies standing in for posts Telegram restricts - never forwarded. `no_forward`: Telegram restricts these posts and refuses to copy them itself: they are rebuilt from their parts.""" dst = dst_peer if dst_peer is not None else peer if from_saved: news = await resend_saved(client, dst, unit, finals, st, reply_to) st.rebuilt += 1 st.from_saved += 1 if reply_to: st.replies += 1 return news pure = all(is_pure(m, f, reply_to) for m, f in zip(unit, finals)) if st.mode == "forward" and pure and not no_forward: try: news = await forward_unit(client, peer, unit, dst) if len(news) == len(unit): st.forwarded += 1 return news await delete_ids(client, dst, [n.id for n in news]) except errors.ChatForwardsRestrictedError: st.mode = "resend" log.info("this channel restricts forwarding - rebuilding posts from their parts instead") except errors.RPCError as e: if type(e).__name__ in FATAL: raise log.info("copy failed (%s) - rebuilding the post", type(e).__name__) try: news = await resend_unit(client, dst, unit, finals, reply_to) except (TypeError, ValueError, errors.RPCError) as e: # A kind of media a post cannot be rebuilt from (or a reply Telegram refuses). If only the reply made a # rebuild necessary, a plain copy by Telegram still works - without the reply. if isinstance(e, errors.RPCError) and type(e).__name__ in FATAL: raise if reply_to and st.mode == "forward" and not no_forward and all(is_pure(m, f) for m, f in zip(unit, finals)): news = await forward_unit(client, peer, unit, dst) if len(news) != len(unit): await delete_ids(client, dst, [n.id for n in news]) raise st.reply_lost += 1 st.forwarded += 1 return news raise st.rebuilt += 1 if reply_to: st.replies += 1 return news
async def settle_buttons(client, peer, finals: list, news: list, st: _State, *, pause: float) -> None: """Read the new posts back: each must show the link buttons it should. Repairs it, or removes the copies.""" for f, new in zip(finals, news): if not link_urls(f.markup): continue try: how = await ensure_markup(client, peer, new.id, f.markup, pause=pause) except errors.RPCError as e: await delete_ids(client, peer, [n.id for n in news]) if type(e).__name__ in FATAL: raise raise ButtonsNotShown(f"could not set the buttons ({type(e).__name__})") from e except (ButtonsNotShown, LookupError) as e: await delete_ids(client, peer, [n.id for n in news]) raise ButtonsNotShown(str(e)) from e if how != "fine": st.repaired += 1
@dataclassclass FinalizeResult: """The finishing touches after the copies exist: links to other posts, pins."""
checked: int = 0 # copies read back relinked: int = 0 # copies whose links to other posts now point at the new copies links: int = 0 # links changed in total missing: int = 0 # copies that do not exist any more failed: list = field(default_factory=list) # [(message id, error name)] pin_wanted: int = 0 # copies of pinned posts that still had to be pinned pinned: int = 0 pin_error: Optional[str] = None aborted: Optional[str] = None stopped: bool = False
@dataclassclass RepostResult: copied_units: int = 0 copied_messages: int = 0 skipped_done: int = 0 failed: list = field(default_factory=list) # [(first old id, error name)] forwarded: int = 0 rebuilt: int = 0 repaired: int = 0 replies: int = 0 # copies created as an answer to the copy of the post the original answered reply_lost: int = 0 # answers that could only be copied without the reply reply_dropped: int = 0 # answers to a post that no longer exists (nothing to answer) from_saved: int = 0 # restricted posts that were copied from their saved copy in My posts media_lost: list = field(default_factory=list) # ... of which these (old ids) went out without their media held_back: list = field(default_factory=list) # posts that were not copied: only Telegram's notice was left (old id) held_why: Optional[str] = None # what Telegram says about the restricted posts live_restricted: int = 0 # restricted posts without a saved copy, copied as Telegram hands them out no_media: bool = False # /shift --no-media: no file was copied files_left_out: int = 0 # ... posts that were copied as text, without their file file_only: list = field(default_factory=list) # ... posts that are only a file: nothing to copy (old id) used_saved: bool = False # the run could take restricted posts from My posts (/shift) from_db: bool = False # the channel can't be read: every post was copied from My posts alone checked: int = 0 # new posts that were read back to see whether Telegram itself hides them hidden: list = field(default_factory=list) # [(old id, had media)] new posts Telegram itself hides (restriction mark) hidden_why: Optional[str] = None # what Telegram says about them dst_restricted: Optional[str] = None # what Telegram says about the destination channel (when copies were hidden) hidden_stop: bool = False # the run stopped by itself: Telegram hides every copy it read back aborted: Optional[str] = None stopped: bool = False first_new: Optional[int] = None last_new: Optional[int] = None phase: str = "copy" # copy | finish | profile | links final: Optional[FinalizeResult] = None final_error: Optional[str] = None cross: Optional[CrossResult] = None # links to the old posts in ALL connected channels, pointed at the copies cross_error: Optional[str] = None profile: Any = None # /shift -all: what happened to the name, description and photo (profile_copy.ProfileResult) profile_error: Optional[str] = None
def _rows(unit: list, finals: list, news: list) -> list: rows = [] for src, f, new in zip(unit, finals, news): kind = classify_media(src) ref = (media_ref(new) or media_ref(src)) if kind else None rows.append( { "old_id": src.id, "new_id": new.id, "post": { "text": plain_of(f.rich) if f.rich is not None else f.text, "entities": [rich_entry(f.rich)] if f.rich is not None else ser_entities(f.entities), "buttons": ser_markup(f.markup), "media_kind": kind, "media_file_id": ref, "link_preview": bool(f.preview), }, } ) return rows
CHECK_FIRST = 3 # the first copies of any run are read back ...CHECK_EVERY = 10 # ... then every tenth (all of them when Telegram restricts the source)STOP_IF_HIDDEN = 3 # /shift stops when Telegram hides this many new copies and not one of those read back is shown
async def check_copies(client, dst_peer, unit: list, news: list, res: RepostResult) -> None: """Read the new posts back: does TELEGRAM itself hide them (a restriction mark, or its notice as the text)? That is not the bot copying a notice - Telegram restricts the new post as well, usually because of a file or a link in it. What is found goes into `res` (checked, hidden, hidden_why). Never fails the copy: it is only a look.""" try: got = await fetch_messages(client, dst_peer, [n.id for n in news]) except Exception as e: # a look that fails is not a failed copy (the post exists and is registered already) log.info("could not read the new posts back: %s", type(e).__name__) return for old, new in zip(unit, got): if is_skippable(new): continue res.checked += 1 why = message_restriction(new) if why: res.hidden.append((old.id, _has_media([old]))) res.hidden_why = res.hidden_why or why
@dataclassclass CopyJob: """Everything the copy loop needs to know; /repost and /shift each fill it in their own way."""
src_peer: Any dst_peer: Any # the same as src_peer for /repost opts: RepostOptions links: PostLinks # links.ids is `idmap`: old message id -> id of its copy, grows as we go first_id: int last_id: int done: set # old ids that already have a copy idmap: dict record: Callable[[list], Awaitable[None]] # saves [{old_id, new_id, post}] (and registers the posts) saved: Optional[SavedLookup] = None # what My posts saved of the source's posts use_saved: bool = False # a post Telegram holds back is rebuilt from its saved copy (otherwise it is left out) units: Optional[Callable[[], AsyncIterator[list]]] = None # where the posts come from (default: read the channel) from_db: bool = False # `units` are saved posts: they are all rebuilt, none is read from Telegram restricted: Optional[str] = None # what Telegram says about the source channel itself (a copyright strike), if anything no_media: bool = False # the copies get no files: text, formatting and buttons only (/shift --no-media) stop_if_hidden: int = 0 # stop when this many copies were read back and Telegram hides every one (0: never)
async def copy_loop( client, job: CopyJob, *, delay: float = 1.2, progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None, should_stop: Optional[Callable[[], bool]] = None, settle_pause: float = 0.7,) -> RepostResult: """Copy the posts first_id..last_id of `job.src_peer` to the end of `job.dst_peer`, in order. Safe to run again to continue: posts in `job.done` are skipped.""" src, dst = job.src_peer, job.dst_peer seen: set = set() # old ids read in this run (a reply to one of them needs its copy) res, st, streak = RepostResult(used_saved=job.use_saved or job.from_db, from_db=job.from_db), _State(), 0 res.no_media = job.no_media units = job.units() if job.units is not None else iter_units(client, src, job.first_id, job.last_id) if job.no_media: units = single_posts(units) async for unit in units: if should_stop and should_stop(): res.stopped = True break ids = [m.id for m in unit] seen.update(ids) if all(i in job.done for i in ids): res.skipped_done += 1 continue rows = await job.saved(ids) if (job.saved and not job.from_db) else {} if job.from_db: source, why = "saved", None else: source, why = copy_source(unit, rows, restricted=job.restricted, use_saved=job.use_saved) if why: # Telegram restricts this post (or the whole channel): what it hands out now is not trusted res.held_why = res.held_why or why from_saved = job.from_db # saved posts already standing = None if source == "saved" and not job.from_db: standing = stand_ins(unit, rows) if standing is None: source = "skip" if source == "skip": log.info("post %s: Telegram shows only its notice (%s) and My posts has no saved copy to use", ids[0], why) res.held_back.append(ids[0]) continue if standing is not None: unit, from_saved = standing, True no_forward, left_out = bool(why), 0 if job.no_media: # the copy is the text with its formatting and buttons; its file stays where it is unit, left_out = without_files(unit) if not unit: # nothing but a file: there is nothing to post without it, and nothing waits for it res.file_only.append(ids[0]) seen.difference_update(ids) continue no_forward = no_forward or bool(left_out) # a copy by Telegram would carry the file finals = [final_state(m, job.opts, job.links) for m in unit] if any(is_placeholder_text(f.text) for f in finals): # Telegram's notice is never posted, whatever it came from log.info("post %s: its text is Telegram's notice - not copied", ids[0]) res.held_back.append(ids[0]) res.held_why = res.held_why or PLACEHOLDER_NOTE continue try: reply_to = new_parent(unit[0], job.idmap, seen) news = await copy_unit( client, src, unit, finals, st, reply_to, dst, from_saved=from_saved, no_forward=no_forward ) await settle_buttons(client, dst, finals, news, st, pause=settle_pause) except Exception as e: # one bad post must not stop the others name = type(e).__name__ log.warning("copying %s failed: %s %s", ids, name, e) res.failed.append((ids[0], name)) streak += 1 if name in FATAL or streak >= ABORT_AFTER: res.aborted = name break await asyncio.sleep(delay) continue try: await job.record(_rows(unit, finals, news)) except Exception as e: # keep the channel and the database consistent log.exception("could not save the copy of %s", ids) await delete_ids(client, dst, [n.id for n in news]) res.failed.append((ids[0], type(e).__name__)) res.aborted = type(e).__name__ break streak = 0 job.done.update(ids) for old, new in zip(unit, news): job.idmap[old.id] = new.id if reply_parent(unit[0]) is not None and reply_to is None: res.reply_dropped += 1 if why and not from_saved: res.live_restricted += 1 res.files_left_out += left_out if why or res.copied_units < CHECK_FIRST or res.copied_units % CHECK_EVERY == 0: await check_copies(client, dst, unit, news, res) res.copied_units += 1 res.copied_messages += len(unit) res.first_new = res.first_new or news[0].id res.last_new = news[-1].id if progress: await progress(res) if job.stop_if_hidden and res.checked >= job.stop_if_hidden and len(res.hidden) == res.checked: log.info("Telegram hides every copy read back (%s): stopping", res.checked) res.stopped = res.hidden_stop = True # more copies would only be more posts that nobody can see break await asyncio.sleep(delay) if res.hidden: # Telegram hides copies: is the destination itself restricted too? try: _top, res.dst_restricted, _err = await probe_channel(client, dst) except Exception: # only an extra for the report log.debug("could not ask Telegram about the destination channel", exc_info=True) res.forwarded, res.rebuilt, res.repaired = st.forwarded, st.rebuilt, st.repaired res.replies, res.reply_lost = st.replies, st.reply_lost res.from_saved, res.media_lost = st.from_saved, st.media_lost return res
async def run_repost( client, db, ch, mig, user_id: int, *, delay: float = 1.2, progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None, should_stop: Optional[Callable[[], bool]] = None, settle_pause: float = 0.7,) -> RepostResult: """Copy the posts of migration `mig` (ids first_id..last_id) in order; safe to run again to continue.
When every post is copied (not stopped, no fatal error) the finishing touches follow: links to posts that were copied later are pointed at their copies, the copies of pinned posts are pinned, and then every connected channel is searched for links to the old posts (crosslinks.relink_after_repost).""" opts = RepostOptions( old=mig.old_username, new=mig.new_username, include_typed=mig.include_typed, include_posts=mig.include_posts ) peer = peer_of(ch) idmap = dict(await db.migration_pairs(mid=mig.id, alive_only=False)) job = CopyJob( src_peer=peer, dst_peer=peer, opts=opts, links=PostLinks.for_channel(ch, idmap), first_id=mig.first_id, last_id=mig.last_id, done=await db.migration_done_old_ids(mig.id), idmap=idmap, record=lambda rows: db.record_repost(mig.id, ch.id, rows, user_id), saved=saved_lookup(db, ch.id), # a post Telegram holds back is left alone (and so is not deleted) ) res = await copy_loop(client, job, delay=delay, progress=progress, should_stop=should_stop, settle_pause=settle_pause) if not res.stopped and not res.aborted: res.phase = "finish" if progress: await progress(res) try: res.final = await finalize_repost( client, db, ch, mig, delay=delay, settle_pause=settle_pause, should_stop=should_stop ) except Exception as e: # the copies are fine; only the finishing touches failed log.exception("finishing the repost (links, pins) failed") res.final_error = type(e).__name__ if not (res.final is not None and res.final.stopped): res.phase = "links" res.cross = CrossResult()
async def watch(_cross) -> None: if progress: await progress(res)
if progress: await progress(res) try: await relink_after_repost( client, db, ch, mig, delay=delay, settle_pause=settle_pause, progress=watch, should_stop=should_stop, result=res.cross, ) except Exception as e: # the copies are fine; only the links in the other channels were not updated log.exception("pointing the links of the other channels at the copies failed") res.cross_error = type(e).__name__ return res
# --------------------------------------------------------------------- links to copies, pinsasync def relink_copies( client, db, ch, ids: dict, targets: list, *, delay: float = 1.2, settle_pause: float = 0.7, dry_run: bool = False, progress: Optional[Callable[[FinalizeResult], Awaitable[None]]] = None, should_stop: Optional[Callable[[], bool]] = None, links: Optional[PostLinks] = None,) -> FinalizeResult: """Point every link to a post of this channel at the copy of that post (`ids`: old message id -> new one).
`targets` are the message ids of `ch` to look at (the copies). Idempotent: a link that already points at a copy is left alone, because only OLD ids are replaced. With dry_run nothing is edited, the result only counts. `links` (optional) says which links to follow; the default is "links to posts of `ch` itself" (/repost).""" res = FinalizeResult() peer = peer_of(ch) links = links if links is not None else PostLinks.for_channel(ch, ids) targets = sorted(set(targets)) streak, last_name = 0, None for i in range(0, len(targets), CHUNK): chunk = targets[i : i + CHUNK] for mid, m in zip(chunk, await fetch_messages(client, peer, chunk)): if is_skippable(m): res.missing += 1 continue res.checked += 1 rl = relink_message(m, links) if rl is None: continue if dry_run: res.relinked += 1 res.links += rl.links continue if should_stop and should_stop(): res.stopped = True return res rich = is_rich_message(m) # a rich message's text is blocks: only its buttons change, the text is not sent again try: if rich: await flood_retry(lambda: edit_raw(client, peer, m.id, markup=rl.markup)) else: await flood_retry( lambda: edit_raw( client, peer, m.id, text=rl.text, entities=rl.entities, markup=rl.markup, preview=preview_flag(m) ) ) if link_urls(rl.markup): await ensure_markup(client, peer, m.id, rl.markup, pause=settle_pause) except errors.MessageNotModifiedError: continue except Exception as e: # one bad post must not stop the others name = type(e).__name__ log.warning("could not update the links of %s: %s %s", m.id, name, e) res.failed.append((m.id, name)) streak = streak + 1 if name == last_name else 1 last_name = name if name in FATAL or streak >= ABORT_AFTER: res.aborted = name return res continue streak, last_name = 0, None res.relinked += 1 res.links += rl.links try: saved = dict(buttons=ser_markup(rl.markup)) if not rich: saved.update(text=rl.text, entities=ser_entities(rl.entities)) await db.update_post_by_message(ch.id, m.id, **saved) except Exception: # the channel is right; the saved copy will be corrected by the next sync log.warning("could not save the new links of %s", m.id, exc_info=True) if progress: await progress(res) await asyncio.sleep(delay) return res
async def pin_copies(client, ch, pairs: list, res: FinalizeResult, *, delay: float = 1.2) -> None: """Pin the copy of every post that is pinned among the originals (oldest first, so the newest pin is on top).
The "pinned a message" notices Telegram adds to the channel are deleted again right away.""" peer = peer_of(ch) pairs = sorted(pairs) todo: list = [] for i in range(0, len(pairs), CHUNK): chunk = pairs[i : i + CHUNK] olds = await fetch_messages(client, peer, [o for o, _ in chunk]) news = await fetch_messages(client, peer, [n for _, n in chunk]) for (_, new_id), src, cur in zip(chunk, olds, news): if is_skippable(src) or is_skippable(cur): continue if getattr(src, "pinned", False) and not getattr(cur, "pinned", False): todo.append(new_id) res.pin_wanted = len(todo) for new_id in todo: try: out = await flood_retry( lambda: client(functions.messages.UpdatePinnedMessageRequest(peer=peer, id=new_id, silent=True)) ) except errors.MessageNotModifiedError: continue # already pinned except errors.RPCError as e: res.pin_error = type(e).__name__ return res.pinned += 1 await delete_ids(client, peer, [m.id for m in new_messages_from(out) if isinstance(m, types.MessageService)]) await asyncio.sleep(delay)
async def finalize_repost( client, db, ch, mig, *, delay: float = 1.2, settle_pause: float = 0.7, progress: Optional[Callable[[FinalizeResult], Awaitable[None]]] = None, should_stop: Optional[Callable[[], bool]] = None,) -> FinalizeResult: """After the copies exist: links that point at old posts get the copies' ids, copies of pinned posts get pinned.""" pairs = sorted(await db.migration_pairs(mid=mig.id)) res = await relink_copies( client, db, ch, dict(pairs), [n for _, n in pairs], delay=delay, settle_pause=settle_pause, progress=progress, should_stop=should_stop, ) if not res.stopped and not res.aborted: await pin_copies(client, ch, pairs, res, delay=delay) return res
# ----------------------------------------------------------------------------- deleting@dataclassclass DeleteResult: deleted: int = 0 by_userbot: int = 0 # of those, how many only the userbot could delete remaining: int = 0 blocked: bool = False # some messages are still there although Telegram did not report an error error: Optional[str] = None # the bot's Telegram error that stopped the run fallback_error: Optional[str] = None # why the userbot could not help tried_userbot: bool = False
async def gone_ids(client, peer, ids: list) -> set: """Which of `ids` no longer exist in the channel.""" msgs = await fetch_messages(client, peer, ids) return {i for i, m in zip(ids, msgs) if m is None or isinstance(m, types.MessageEmpty)}
@dataclassclass BatchOutcome: gone: set = field(default_factory=set) # message ids that no longer exist afterwards bot_error: Optional[str] = None by_userbot: int = 0 fallback_error: Optional[str] = None tried_userbot: bool = False
async def delete_batch(client, peer, ids: list, fallback: Optional[Callable[[list], Awaitable[Any]]] = None) -> BatchOutcome: """Delete up to 100 messages: the bot tries first, the result is checked by reading the messages back, and whatever is still there goes to `fallback(ids)` (the userbot), followed by a second check.""" out = BatchOutcome() try: await flood_retry(lambda: client(functions.channels.DeleteMessagesRequest(channel=peer, id=list(ids)))) except errors.RPCError as e: out.bot_error = type(e).__name__ out.gone = await gone_ids(client, peer, ids) left = [x for x in ids if x not in out.gone] if left and fallback is not None: out.tried_userbot = True try: await fallback(left) except Exception as e: # a userbot problem must not hide what the bot already did log.warning("the userbot could not delete %s message(s): %s", len(left), e) out.fallback_error = str(e) or type(e).__name__ again = await gone_ids(client, peer, left) out.by_userbot = len(again) out.gone |= again return out
async def delete_pending( client, peer, todo: list, mark: Callable[[list], Awaitable[None]], *, delay: float = 0.5, progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None, fallback: Optional[Callable[[list], Awaitable[Any]]] = None,) -> DeleteResult: """Delete the messages `todo` (oldest first, 100 per request). `mark(ids)` records the ones that are gone.
The bot tries first and the result is always checked by reading the messages back. Whatever the bot could not delete (Telegram may refuse old posts) goes to `fallback(ids)` - the userbot - if there is one, and is checked again. A batch the bot cannot delete does not stop the run: newer posts may still be deletable.""" res = DeleteResult() use_fallback = fallback for i in range(0, len(todo), 100): ids = todo[i : i + 100] out = await delete_batch(client, peer, ids, use_fallback) res.tried_userbot = res.tried_userbot or out.tried_userbot res.by_userbot += out.by_userbot if out.fallback_error: res.fallback_error = out.fallback_error use_fallback = None # it will not work for the next batches either left = [x for x in ids if x not in out.gone] if out.gone: await mark(sorted(out.gone)) res.deleted += len(out.gone) if left and out.bot_error: res.error = res.error or out.bot_error # remembered for the report if out.bot_error in FATAL and use_fallback is None: break # e.g. no "Delete messages" right: the next batch would fail the same way if progress: await progress(res) await asyncio.sleep(delay) return res
async def delete_copies( client, db, ch, mig, which: str, *, delay: float = 0.5, progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None, fallback: Optional[Callable[[list], Awaitable[Any]]] = None,) -> DeleteResult: """which='old': remove the original posts; which='new': remove the copies (undo). Oldest first, 100 per request.""" todo = await db.migration_pending_ids(mig.id, which, 1_000_000)
async def mark(ids: list) -> None: await db.mark_migration_deleted(mig.id, ch.id, which, ids)
res = await delete_pending(client, peer_of(ch), todo, mark, delay=delay, progress=progress, fallback=fallback) counts = await db.migration_counts(mig.id) res.remaining = counts["old_left"] if which == "old" else counts["new_left"] res.blocked = res.remaining > 0 and not res.error return res1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""What TELEGRAM does to a channel (not what an admin does): the copyright notice and its relatives.
A channel that gets a copyright strike shows "This message couldn't be displayed on your device due to copyrightinfringement." in place of its posts. That is not an edit by an admin, so nothing here ever treats it as one: the syncleaves My posts as saved, and the link fixer does not edit such posts."""from __future__ import annotations
import refrom typing import Optional
from telethon import errors, functions
from .tgutil import explain_rpc, flood_retry
PLACEHOLDER_NOTE = "Telegram shows a notice instead of the post"
# "This message couldn't be displayed on your device due to copyright infringement." and its relatives_NOTICE = re.compile( r"^this (?:message|post|channel|media|content|file|video)\b.{0,80}?" r"\b(?:can.?t|cannot|can not|couldn.?t|could not|isn.?t|is not|won.?t|will not)\b.{0,40}?" r"\b(?:displayed|shown|viewed|available|accessible)\b.{0,160}$", re.I,)_NOTICE_WHY = re.compile(r"copyright|infring|device|country|region|terms of service|violat|restrict|\blaw\b", re.I)
def norm_text(text: Optional[str]) -> str: return " ".join((text or "").split())
def is_placeholder_text(text: Optional[str]) -> bool: """The notice Telegram's apps show in place of a post it holds back (copyright, terms of service, region ...).""" t = norm_text(text) return 0 < len(t) <= 260 and bool(_NOTICE.match(t)) and bool(_NOTICE_WHY.search(t))
def restriction_of(obj) -> Optional[str]: """What Telegram says about a restricted channel or message (its own words), or None when nothing is restricted.""" reasons = getattr(obj, "restriction_reason", None) if reasons: texts = [norm_text(str(getattr(r, "text", "") or getattr(r, "reason", "") or "")) for r in reasons] return "; ".join(dict.fromkeys(t for t in texts if t))[:240] or "restricted by Telegram" if getattr(obj, "restricted", None): return "restricted by Telegram" return None
def message_restriction(m, saved_text: Optional[str] = None) -> Optional[str]: """Why this message must not be taken over as it looks now, or None. Telegram marks a message it holds back (restriction_reason); some places hand out its notice as the text instead. `saved_text` is the saved copy's text: a text that the saved copy already has is the owner's own wording, not a notice.""" why = restriction_of(m) if why: return why live = m.message or "" if is_placeholder_text(live) and (saved_text is None or norm_text(live) != norm_text(saved_text)): return PLACEHOLDER_NOTE return None
async def probe_channel(client, peer) -> tuple: """(the channel's event counter, why Telegram restricts the channel or None, None) - or (None, None, why not). The counter is never lower than the newest message id.""" try: full = await flood_retry(lambda: client(functions.channels.GetFullChannelRequest(peer))) except errors.RPCError as e: return None, None, explain_rpc(e) pts = getattr(getattr(full, "full_chat", None), "pts", None) if pts is None: return None, None, "Telegram did not say how far the channel has come." cid = getattr(peer, "channel_id", None) why = None for chat in getattr(full, "chats", None) or []: if getattr(chat, "id", None) == cid: why = restriction_of(chat) return int(pts), why, None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698"""Telegram rich messages: headings, lists, tables, details, math, maps, media blocks, buttons ...
A rich message is not text plus entities: it is a tree of blocks. Telegram builds that tree itself from HTML or Markdown(InputRichMessageHTML / InputRichMessageMarkdown), so text typed in those languages is handed over unchanged - every blockand every formatting Telegram knows is supported without this bot having to know it. A rich message that is sent to thebot natively (or forwarded to it) is kept block for block (InputRichMessage).
How the bot keeps one: as a single entry in the post's `entities` list - ``{"k": "rich", "f": "html" | "markdown" |"blocks", "s": source, ...}`` - next to a plain-text version in `text` (for lists, panels and the like). Whatever sends oredits a post looks for that entry with `rich_of`. No database change is needed, and exports, backups and the undo log carryit like any other formatting."""from __future__ import annotations
import asyncioimport copyimport hashlibimport loggingimport refrom dataclasses import dataclass, replacefrom html.parser import HTMLParserfrom types import SimpleNamespacefrom typing import List, Optional
from telethon import errors, functions, types, utilsfrom telethon.tl.tlobject import TLObject
from .tgutil import _b64, _unb64, flood_retry
log = logging.getLogger(__name__)
KIND = "rich" # the "k" of the entry in a post's entitiesMAX_SOURCE = 32768 # characters Telegram allows in a rich message (500 blocks, 16 levels and 50 media as well)
class RichError(ValueError): """A rich message that can't be used; the text is safe to show to the owner."""
@dataclass(frozen=True)class Rich: """A rich message as the bot keeps it."""
fmt: str # "html" | "markdown" (typed: Telegram reads it) | "blocks" (received: base64 of an InputRichMessage) source: str rtl: bool = False noautolink: bool = False # links, @mentions, #tags ... in the text are not made clickable by Telegram fp: Optional[str] = None # fingerprint of the blocks Telegram showed last time (what the sync compares)
def entry(r: Rich) -> dict: """The entry that stands for `r` in a post's entities.""" e: dict = {"k": KIND, "f": r.fmt, "s": r.source} if r.rtl: e["r"] = 1 if r.noautolink: e["n"] = 1 if r.fp: e["p"] = r.fp return e
def rich_of(obj) -> Optional[Rich]: """The rich message a post (or anything with a post's `entities`) holds, or None.""" for d in getattr(obj, "entities", None) or []: if isinstance(d, dict) and d.get("k") == KIND and d.get("f") in ("html", "markdown", "blocks") and d.get("s"): return Rich(d["f"], d["s"], bool(d.get("r")), bool(d.get("n")), d.get("p") or None) return None
def is_rich(obj) -> bool: return rich_of(obj) is not None
def real_entities(entities) -> list: """The formatting entries of a stored entities list, without the rich message's.""" return [d for d in entities or [] if not (isinstance(d, dict) and d.get("k") == KIND)]
# ------------------------------------------------------------------------------------ what Telegram takesdef to_input(r: Rich): """The InputRichMessage* object to send for `r`.""" flags = dict(rtl=True if r.rtl else None, noautolink=True if r.noautolink else None) if r.fmt == "html": return types.InputRichMessageHTML(html=r.source, **flags) if r.fmt == "markdown": return types.InputRichMessageMarkdown(markdown=r.source, **flags) inp = copy.copy(_unb64(r.source)) # (a message saved by an older version may still hold blocks in Telegram's own form) inp.blocks = inputify(inp.blocks, _user_ids(inp.users)) return inp
def _input_geo(geo): if isinstance(geo, types.GeoPoint): return types.InputGeoPoint(lat=geo.lat, long=geo.long, accuracy_radius=geo.accuracy_radius) if isinstance(geo, types.InputGeoPoint): return geo return types.InputGeoPointEmpty()
def _user_ids(users) -> set: return {u.user_id for u in users or [] if isinstance(getattr(u, "user_id", None), int)}
def inputify(o, users: Optional[set] = None): """Blocks the way Telegram wants them SENT. What it hands out and what it takes are the same blocks except where a block holds something only Telegram can make: a map holds a stored point (with an access hash) when it comes in, and must hold an input point (latitude and longitude) when it goes out.
`users`: the ids of the accounts that the message may mention (it carries their access data). A text mention of anybody else would be refused, so it stays as the plain name; None leaves all mentions alone.
A thinking block (the "thinking ..." part of a message that is being streamed) is for drafts only - the Bot API says so of <tg-thinking> - and a message that is sent can't hold one: it goes out as an expandable section called "Thinking".""" if isinstance(o, types.PageBlockMap): return types.InputPageBlockMap( geo=_input_geo(o.geo), zoom=o.zoom, w=o.w, h=o.h, caption=inputify(o.caption, users) ) if isinstance(o, types.PageBlockThinking): return types.PageBlockDetails( blocks=[types.PageBlockParagraph(inputify(o.text, users))], title=types.TextPlain("Thinking") ) if users is not None and isinstance(o, types.TextMentionName) and o.user_id not in users: return inputify(o.text, users) if isinstance(o, list): return [inputify(x, users) for x in o] if isinstance(o, TLObject): new = copy.copy(o) for key, value in vars(o).items(): if isinstance(value, (list, TLObject)): setattr(new, key, inputify(value, users)) return new return o
def blank_references(inp): """The same InputRichMessage with the file references of its photos and files left out (they may have expired).""" if not isinstance(inp, types.InputRichMessage): return inp out = copy.copy(inp) out.photos = [types.InputPhoto(p.id, p.access_hash, b"") for p in inp.photos or []] or None out.documents = [types.InputDocument(d.id, d.access_hash, b"") for d in inp.documents or []] or None return out
async def with_rich(r: Rich, call): """call(InputRichMessage*): first as saved, then (if Telegram says a saved file reference expired) without them.""" try: return await call(to_input(r)) except errors.RPCError as e: if r.fmt != "blocks" or "FileReference" not in type(e).__name__: raise log.info("stored file reference of a rich message rejected (%s) - retrying without it", type(e).__name__) return await call(blank_references(to_input(r)))
def sent_message(result): """The message a send request created (something with an `id`).""" for u in getattr(result, "updates", None) or []: if isinstance(u, (types.UpdateNewChannelMessage, types.UpdateNewMessage)): return u.message if getattr(result, "id", None) is not None and not isinstance(result, (list, tuple)): return SimpleNamespace(id=result.id) # UpdateShortSentMessage raise RuntimeError("Telegram did not say which message it created")
async def send_rich(client, peer, r: Rich, *, markup=None, silent=None): """Send `r` as a new message to `peer`; the message that was created comes back.""" result = await with_rich( r, lambda inp: client( functions.messages.SendMessageRequest( peer=peer, message="", rich_message=inp, reply_markup=markup, silent=True if silent else None ) ), ) return sent_message(result)
# --------------------------------------------------------------------------------- rich messages that are receiveddef is_rich_message(m) -> bool: """The message carries a rich message (blocks) instead of plain text.""" return getattr(m, "rich_message", None) is not None
def fingerprint(rm) -> str: """Identifies what a rich message shows (its blocks; the file references of its pictures change from fetch to fetch).""" h = hashlib.sha1() for b in getattr(rm, "blocks", None) or []: h.update(bytes(inputify(b))) # (a map's access hash is not part of what it shows) h.update(b"r" if getattr(rm, "rtl", None) else b"-") return h.hexdigest()[:20]
def _input_files(items, getter, empty) -> list: out = [] for item in items or []: try: inp = getter(item) except (TypeError, ValueError): continue if not isinstance(inp, empty): out.append(inp) return out
def input_of(rm, users: Optional[list] = None): """The InputRichMessage that sends a received RichMessage again: same blocks, same pictures and files.""" photos = _input_files(getattr(rm, "photos", None), utils.get_input_photo, types.InputPhotoEmpty) docs = _input_files(getattr(rm, "documents", None), utils.get_input_document, types.InputDocumentEmpty) return types.InputRichMessage( blocks=inputify(list(rm.blocks), _user_ids(users)), rtl=True if getattr(rm, "rtl", None) else None, photos=photos or None, documents=docs or None, users=users or None, )
def rich_from_received(rm, users: Optional[list] = None) -> Rich: return Rich("blocks", _b64(input_of(rm, users)), bool(getattr(rm, "rtl", None)), False, fingerprint(rm))
def mention_ids(blocks) -> list: """User ids that the blocks mention by link (a text mention needs the account's access data to be sent again).""" found: list = []
def walk(o) -> None: if isinstance(o, dict): if o.get("_") == "TextMentionName" and isinstance(o.get("user_id"), int): found.append(o["user_id"]) for v in o.values(): walk(v) elif isinstance(o, list): for v in o: walk(v)
for b in blocks or []: walk(b.to_dict()) return list(dict.fromkeys(found))
async def input_users(client, ids: list) -> list: out = [] for uid in ids: try: peer = await client.get_input_entity(uid) except Exception as e: # noqa: BLE001 - a mention that can't be resolved is sent as the plain name log.info("could not resolve the mentioned user %s: %s", uid, type(e).__name__) continue if isinstance(peer, types.InputPeerUser): out.append(types.InputUser(peer.user_id, peer.access_hash)) return out
async def received(client, event) -> Optional[Rich]: """The rich message that `event`'s message is (sent natively or forwarded to the bot), or None for an ordinary message.""" m = event.message rm = getattr(m, "rich_message", None) if rm is None: return None if getattr(rm, "part", None): # Telegram sent a part of it; the rest has to be asked for full = None try: got = await client(functions.messages.GetRichMessageRequest(peer=await event.get_input_chat(), id=m.id)) full = got if isinstance(got, types.RichMessage) else getattr(got, "rich_message", None) except errors.RPCError as e: log.info("could not read the whole rich message: %s", type(e).__name__) if full is None or getattr(full, "part", None): raise RichError("Telegram only handed me a part of that rich message. Send it again, or type it as HTML / Markdown.") rm = full if not getattr(rm, "blocks", None): raise RichError("That rich message has no content.") return rich_from_received(rm, await input_users(client, mention_ids(rm.blocks)))
# --------------------------------------------------------------- when Telegram refuses a block of a received message_BLOCK_NAMES = { "Heading1": "heading", "Heading2": "heading", "Heading3": "heading", "Heading4": "heading", "Heading5": "heading", "Heading6": "heading", "Title": "heading", "Subtitle": "heading", "Header": "heading", "Subheader": "heading", "Paragraph": "paragraph", "Preformatted": "code", "Blockquote": "quote", "BlockquoteBlocks": "quote", "Pullquote": "pull quote", "List": "list", "OrderedList": "numbered list", "Details": "expandable section", "Math": "math", "Map": "map", "ButtonRow": "buttons", "Photo": "picture", "Video": "video", "Audio": "audio", "Document": "file", "Collage": "collage", "Slideshow": "slideshow", "Table": "table", "Divider": "rule", "Anchor": "anchor", "Footer": "footer", "Unsupported": "a block this version does not know", "Thinking": "thinking block", "Embed": "embedded page", "EmbedPost": "embedded post", "Channel": "channel card", "RelatedArticles": "related articles", "AuthorDate": "author line", "Kicker": "kicker", "Cover": "cover",}MAX_PROBES = 60 # blocks that are looked through one by one (at most) when Telegram refuses a message
def block_name(b) -> str: """What a block is called to the owner: "map", "table" ...""" raw = re.sub(r"^(?:Input)?PageBlock", "", type(b).__name__) return _BLOCK_NAMES.get(raw, raw.lower() or "block")
def is_block_invalid(e: BaseException) -> bool: """Telegram says one of the blocks it was given is not acceptable (RICH_MESSAGE_BLOCK_INVALID).""" return "RICH_MESSAGE_BLOCK_INVALID" in (getattr(e, "message", None) or str(e))
async def refused_blocks(client, peer, r: Rich, *, pause: float = 0.4) -> Optional[List[int]]: """The numbers (0, 1, 2 ...) of the top-level blocks of a received rich message that Telegram will not take back.
Called once the whole message has been refused. Found by sending groups of the blocks to `peer` - a chat with the owner - quietly, and deleting them again straight away. None when it can't be told: the message is typed (Telegram reads that itself), it has too many blocks to look through, no single block is at fault (every part is taken), or something else than a refused block went wrong.""" if r.fmt != "blocks": return None whole = to_input(r) blocks = list(whole.blocks) if not blocks or len(blocks) > MAX_PROBES: return None
async def accepted(idx: List[int]) -> bool: part = copy.copy(whole) part.blocks = [blocks[i] for i in idx] try: made = await flood_retry( lambda: client( functions.messages.SendMessageRequest(peer=peer, message="", rich_message=part, silent=True) ) ) except errors.RPCError as e: if is_block_invalid(e): return False raise try: await client(functions.messages.DeleteMessagesRequest(id=[sent_message(made).id], revoke=True)) except Exception: # noqa: BLE001 - a test message that stays is only clutter log.info("could not delete a test message of the rich-message check") await asyncio.sleep(pause) return True
async def find(idx: List[int], known: bool = False) -> List[int]: if not known and await accepted(idx): return [] if len(idx) == 1: return list(idx) mid = len(idx) // 2 return await find(idx[:mid]) + await find(idx[mid:])
try: bad = await find(list(range(len(blocks))), known=True) # (the whole message was refused: no need to ask again) except Exception as e: # noqa: BLE001 - this is only a help for the owner log.info("could not find the refused blocks: %s", type(e).__name__) return None return bad or None
def block_labels(r: Rich, idx: List[int]) -> str: """"4 (map), 9 (table)": the blocks numbered `idx` (from 0), counted from 1 and named.""" blocks = to_input(r).blocks return ", ".join(f"{i + 1} ({block_name(blocks[i])})" for i in sorted(set(idx)) if 0 <= i < len(blocks))
def block_count(r: Rich) -> int: return len(to_input(r).blocks) if r.fmt == "blocks" else 0
def digest(r: Rich) -> str: """Short mark of what `r` holds (so a button made for one message is not used on another).""" return hashlib.sha1(f"{r.fmt}:{r.source}".encode()).hexdigest()[:6]
def pack_blocks(idx: List[int]) -> str: """Block numbers as one short word (the bits of a number, in base 36) - small enough for a button.""" n, out = sum(1 << i for i in set(idx)), "" while n: n, d = divmod(n, 36) out = "0123456789abcdefghijklmnopqrstuvwxyz"[d] + out return out or "0"
def unpack_blocks(word: str) -> List[int]: n = int(word, 36) return [i for i in range(n.bit_length()) if n >> i & 1]
def without_blocks(r: Rich, drop: List[int]) -> Rich: """The received rich message `r` without the top-level blocks numbered `drop` (what Telegram saw of it changes, so the fingerprint is forgotten).""" inp = to_input(r) inp.blocks = [b for i, b in enumerate(inp.blocks) if i not in set(drop)] return Rich("blocks", _b64(inp), r.rtl, r.noautolink, None)
# ------------------------------------------------------------------------- plain text (lists, panels, previews)_BLOCKY = ("h1", "h2", "h3", "h4", "h5", "h6", "p", "ul", "ol", "li", "table", "tr", "details", "summary", "figure", "figcaption", "aside", "blockquote", "pre", "footer", "hr", "br", "tg-math-block", "tg-button-row", "tg-collage", "tg-slideshow", "tg-map", "img", "video", "audio", "tg-document", "caption", "cite")
class _Plain(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.out: List[str] = [] self.skip = 0
def _break(self, tag: str) -> None: """A line break for a block; two blocks in a row are only one line apart (a <br> is always a break).""" if tag == "br" or (self.out and not self.out[-1].endswith("\n")): self.out.append("\n")
def handle_starttag(self, tag, attrs): if tag in ("script", "style"): self.skip += 1 if tag in _BLOCKY: self._break(tag) if tag == "li": self.out.append("β’ ") elif tag in ("td", "th"): self.out.append(" | " if self.out and not self.out[-1].endswith(("\n", " | ")) else "") elif tag == "input" and any(k == "type" and v == "checkbox" for k, v in attrs): self.out.append("β " if any(k == "checked" for k, _ in attrs) else "β ")
def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs)
def handle_endtag(self, tag): if tag in ("script", "style") and self.skip: self.skip -= 1 if tag in _BLOCKY: self._break(tag)
def handle_data(self, data): if not self.skip: self.out.append(data)
def _tidy(text: str) -> str: lines = [" ".join(line.split()) for line in text.replace("\r", "").split("\n")] return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
def _plain_html(source: str) -> str: p = _Plain() try: p.feed(source) p.close() except Exception: # noqa: BLE001 - a snippet is not worth failing for return _tidy(re.sub(r"<[^>]*>", " ", source)) return _tidy("".join(p.out))
_MD_EMPHASIS = re.compile(r"(\*\*|__|~~|\|\||==)(?=\S)(.+?)(?<=\S)\1")_MD_SINGLE = re.compile(r"(?<![\w*])([*_])(?=\S)([^*_\n]+?)(?<=\S)\1(?![\w*])")
def _plain_markdown(source: str) -> str: out: List[str] = [] fenced = False for line in source.replace("\r", "").split("\n"): if re.match(r"^\s*(```|~~~)", line): fenced = not fenced continue if fenced: out.append(line) continue if re.match(r"^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$", line): # a table's delimiter row continue if re.match(r"^\s*(-{3,}|\*{3,}|_{3,})\s*$", line): out.append("") continue line = re.sub(r"^\s{0,3}#{1,6}\s+", "", line) line = re.sub(r"^(\s*)(?:>\s?)+", r"\1", line) line = re.sub(r"^(\s*)[-*+]\s+\[[xX]\]\s+", r"\1β ", line) line = re.sub(r"^(\s*)[-*+]\s+\[ \]\s+", r"\1β ", line) line = re.sub(r"^(\s*)[-*+]\s+", r"\1β’ ", line) if "|" in line and line.count("|") >= 2: line = " | ".join(c.strip() for c in line.strip().strip("|").split("|")) line = re.sub(r"!\[([^\]]*)\]\([^)]*?(?:\s+\"([^\"]*)\")?\)", lambda m: m.group(2) or m.group(1), line) line = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", line) line = re.sub(r"^\[\^([^\]\s]+)\]:[ \t]*", r"\1: ", line) # a footnote's text, led by its mark line = re.sub(r"\[\^[^\]]+\]", "", line) line = _MD_EMPHASIS.sub(r"\2", line) line = _MD_SINGLE.sub(r"\2", line) line = line.replace("`", "") line = re.sub(r"\\([\\`*_{}\[\]()#+\-.!|~>$=])", r"\1", line) out.append(line) return _tidy("\n".join(out))
def _plain_blocks(blocks) -> str: out: List[str] = []
def brk() -> None: if out and not out[-1].endswith("\n"): out.append("\n")
def walk(o) -> None: if isinstance(o, dict): name = str(o.get("_", "")) if name == "PageTableRow": brk() for n, cell in enumerate(o.get("cells") or []): if n: out.append(" | ") walk(cell) brk() return item = name.startswith(("PageListItem", "PageListOrderedItem")) if name.startswith("PageBlock") or item: brk() if item: out.append(("β " if o.get("checked") else "β ") if o.get("checkbox") else "β’ ") for key in sorted(o, key=lambda k: k != "title"): # a title (of a <details>, a table) is read first v = o[key] if key in ("text", "source") and isinstance(v, str): out.append(v) elif isinstance(v, (dict, list)): walk(v) if name.startswith("PageBlock") or item: brk() elif isinstance(o, list): for v in o: walk(v)
for b in blocks or []: try: walk(b.to_dict()) except Exception: # noqa: BLE001 continue return _tidy("".join(out))
def plain_of(r: Rich) -> str: """What the rich message says, as plain text (what My posts shows and searches).""" if r.fmt == "html": return _plain_html(r.source) if r.fmt == "markdown": return _plain_markdown(r.source) try: inp = _unb64(r.source) return _plain_blocks(getattr(inp, "blocks", None)) except Exception: # noqa: BLE001 return ""
def plain_of_message(m) -> str: return _plain_blocks(getattr(getattr(m, "rich_message", None), "blocks", None))
# ---------------------------------------------------------------------------- reading what the owner typed_FORCE = re.compile(r"\A[ \t]*<rich((?:[ \t]+(?:rtl|noautolink))*)[ \t]*>[ \t]*(?:\r?\n|\Z)", re.I)
# HTML only rich messages have: headings, paragraphs, lists, tables, details, figures, media, maps, math, buttons, marks ..._RICH_TAGS = ( r"h[1-6]", "p", "ul", "ol", "li", "table", "thead", "tbody", "tfoot", "tr", "td", "th", "caption", "details", "summary", "figure", "figcaption", "aside", "hr", "img", "video", "audio", "footer", "cite", "input", "mark", "sub", "sup", "tg-document", "tg-map", "tg-collage", "tg-slideshow", "tg-math", "tg-math-block", "tg-button", "tg-button-row", "tg-time", "tg-reference",)_RICH_HTML = re.compile( r"<(?:" + "|".join(t if t.startswith("h[") else re.escape(t) for t in _RICH_TAGS) + r")(?=[\s/>])[^<>]*>" r"|<a\s[^<>]*?\b(?:name\s*=|href\s*=\s*[\"']?#)", re.I,)_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)
# Markdown only rich messages have (a bullet list or a rule alone does not count: plain posts use those as decoration)_MD_RICH = ( re.compile(r"^ {0,3}#{1,6}[ \t]+\S", re.M), # # heading re.compile(r"^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+\[[ xX]\](?:[ \t]+\S|[ \t]*$)", re.M), # - [x] task re.compile(r"^[^\n]*\|[^\n]*\n[ \t]*\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)+\|?[ \t]*$", re.M), # | table | re.compile(r"\$\$.+?\$\$", re.S), # $$ block math $$ re.compile(r"^\[\^[^\]\s]+\]:[ \t]+\S", re.M), # [^1]: footnote re.compile(r"(?<![=\w])==(?=\S)[^=\n]+?(?<=\S)==(?![=\w])"), # ==marked== re.compile(r"^[ \t]*!\[[^\]\n]*\]\((?!tg://(?:emoji|time)\b)[^)\s]+(?:[ \t]+\"[^\"\n]*\")?\)[ \t]*$", re.M), #  re.compile(r"!\[[^\]\n]*\]\(tg://time\?[^)\s]+\)"), # a formatted date)_CODE = re.compile(r"```.*?```|~~~.*?~~~|<pre\b.*?</pre\s*>|<code\b.*?</code\s*>|`[^`\n]+`", re.S | re.I)
def _blank(m: "re.Match") -> str: return re.sub(r"[^\n]", " ", m.group())
def detect(text: str, forced: bool = False) -> Optional[str]: """"html" or "markdown" when `text` needs a rich message (or `forced` says it is one), else None.""" bare = _CODE.sub(_blank, text) # what stands in code is not markup html_hit = bool(_RICH_HTML.search(bare)) if html_hit and bare.lstrip().startswith("<"): return "html" if any(rx.search(bare) for rx in _MD_RICH): return "markdown" if html_hit: return "html" if forced: return "html" if _BASIC_HTML.search(bare) else "markdown" return None
def read_typed(text: str) -> Optional[Rich]: """The rich message that text typed as HTML or Markdown stands for, or None when it is an ordinary text.
It is a rich message when it has something only rich messages have (a heading, a table, a task list, math, a picture, <details> ...), or when its first line is ``<rich>`` (``<rich rtl>``, ``<rich noautolink>``). Telegram reads the language itself; what is passed on is exactly what was typed (without that first line).""" text = text or "" force = _FORCE.match(text) body = text[force.end():] if force else text fmt = detect(body, forced=bool(force)) if fmt is None or not body.strip(): return None words = (force.group(1) or "").lower().split() if force else [] return Rich(fmt, body.strip(), rtl="rtl" in words, noautolink="noautolink" in words)
def check(r: Rich) -> None: """RichError when Telegram would not take it (only the limit that is cheap to check here).""" if r.fmt != "blocks" and len(r.source) > MAX_SOURCE: raise RichError(f"A rich message can have at most {MAX_SOURCE} characters (yours has {len(r.source)}).")
def with_fingerprint(r: Rich, fp: Optional[str]) -> Rich: return replace(r, fp=fp)
# --------------------------------------------------------------------------------------- the /rich help pagesRICH_HELP = ( "π§© <b>Rich messages</b>\n\n" "Telegram's newer message type: headings, lists, tables, expandable sections, math, maps, pictures and buttons in one " "message (up to 32768 characters, 500 blocks, 16 nesting levels, 50 pictures/files, 20 table columns). The bot " "publishes your text as one when\n" "β’ you send it a rich message made in Telegram, or forward one: it is kept block for block, or\n" "β’ you type HTML or Markdown that has something only rich messages have: a heading, a table, a task list, math, a " "picture, <code><details></code>, <code><h1></code>, <code><table></code> ... or\n" "β’ the first line is just <code><rich></code> (<code><rich rtl></code> for right-to-left text, " "<code><rich noautolink></code> so links, @names and #tags are not made clickable).\n\n" "Telegram reads the text itself, so everything it supports works. π Preview shows what it made of your text before " "you publish. Rich messages are for text posts - a photo's caption can't be rich. The post's own link buttons " "(β Button) work with them.\n\n" "<b>Markdown</b>\n" "<code>**bold** *italic* ~~strike~~ ||spoiler|| ==marked== `code`</code> (underline, subscript and superscript: HTML " "<code><u> <sub> <sup></code>)\n" "<code># Heading</code> β¦ <code>###### Heading</code>\n" "<code>- item</code> <code>1. item</code> lists, <code>- [ ] task</code> <code>- [x] done</code>, <code>---</code> a rule\n" "<code>> quote</code> (a bare <code>></code> line is a new paragraph inside it)\n" "<code>```python</code> β¦ <code>```</code> a code block with a language\n" "<code>$x^2$</code> inline math, <code>$$E = mc^2$$</code> or a <code>```math</code> block: a formula block\n" "<code>| a | b |</code> then <code>|:--|--:|</code> then rows: a table (colons set the alignment; cells hold inline " "formatting only)\n" "<code>text[^1]</code> and a line <code>[^1]: the note</code>: a footnote\n" "<code></code> alone on a line: a picture, video, audio, GIF or file (https links " "only); put several such lines inside <code><tg-collage></code> or <code><tg-slideshow></code>\n" "<code></code> a date shown in the reader's time\n" "<code></code> a custom emoji\n" "<code>[name](tg://user?id=123)</code> <code>[mail](mailto:a@b.c)</code> <code>[call](tel:+123)</code>\n" "Raw HTML works inside Markdown, but Markdown is not read inside block tags (only inside <code><details></code>, " "<code><tg-collage></code> and <code><tg-slideshow></code>).")
RICH_HELP_HTML = ( "π§© <b>Rich HTML</b>\n\n" "<code><h1></code> β¦ <code><h6></code> <code><p></code> <code><hr></code> " "<code><footer></code> <code><b> <i> <u> <s> <mark> <sub> <sup> " "<code> <tg-spoiler></code> <code><br></code>\n" "<code><pre><code class=\"language-python\"></code> a code block\n" "<code><ul></code> <code><ol start=\"3\" type=\"a\" reversed></code> " "<code><li value=\"7\" type=\"i\"></code> (type: a, A, i, I, 1) " "<code><input type=\"checkbox\" checked></code>\n" "<code><blockquote expandable>text<cite>who</cite></blockquote></code> and " "<code><aside>pull quote<cite>who</cite></aside></code>\n" "<code><details open><summary>Title</summary>β¦</details></code> an expandable section\n" "<code><table bordered striped compact><caption>β¦</caption><tr><th colspan=\"2\" " "align=\"center\" valign=\"middle\">β¦</code> (td and th: colspan, rowspan, align left/center/right, valign " "top/middle/bottom)\n" "<code><tg-math>x^2</tg-math></code> <code><tg-math-block>E = mc^2</tg-math-block></code> " "(raw LaTeX)\n" "<code><tg-time unix=\"1647531900\" format=\"wDT\">22:45 tomorrow</tg-time></code>\n" "<code><tg-emoji emoji-id=\"5368324170671202286\">π</tg-emoji></code>\n" "<code><a name=\"top\"></a></code> and <code><a href=\"#top\"></code> anchors; " "<code><tg-reference name=\"n1\">text</tg-reference></code> with <code><a href=\"#n1\"></code> " "a footnote\n" "<code><img src=\"https://β¦\"></code> <code><video src=β¦></code> <code><audio src=β¦></code> " "<code><tg-document src=β¦></code>, each on its own or in " "<code><figure>β¦<figcaption>caption<cite>credit</cite></figcaption></figure></code> " "(https links only; <code>tg-spoiler</code> on img/video hides it); several inside " "<code><tg-collage></code> or <code><tg-slideshow></code>\n" "<code><tg-map lat=\"41.9\" long=\"12.5\" zoom=\"14\"/></code> a map\n" "<code><tg-button-row align=\"center\"><tg-button type=\"url\" url=\"https://t.me\" " "style=\"success\">Open</tg-button></tg-button-row></code> buttons in the text. Types: url, " "web_app and login_url (url=), callback_data (data=), copy_text (text=), switch_inline_query, " "switch_inline_query_current_chat, switch_inline_query_chosen_chat (query=), disabled. Styles: primary, success, " "danger, link.\n" "<code>&lt; &gt; &amp;</code> stand for < > & when they must stay as they are.\n\n" "<b>Good to know</b>\n" "β’ A picture or video typed into a rich message must be a public https link. To use a file that exists only on " "Telegram, send the bot a rich message that already contains it.\n" "β’ A button inside the text that needs the bot (callback_data) only works for the bot that made it - for a forwarded " "rich message that is another bot.\n" "β’ /swap, /handleswap and the post-link changes of /repost change a rich post's buttons, not the links inside its text.\n" "β’ Older Telegram apps may not show rich messages.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552"""Telegram formatting from text typed as HTML or Markdown - for when Telegram's own editor is not at hand.
A message the owner sends can carry Telegram's own formatting: that is used exactly as it is. When it carries none, thetext is read as HTML (when it holds a supported tag together with its closing tag) or else as Markdown, and what isrecognised becomes real formatting. Whatever is not recognised stays as it was typed, so ordinary text (``5 * 3``,``snake_case_names``, ``<3``, ``[Group] Title``, ``Sub | Dub``) is left alone.
HTML, like Telegram's own HTML mode: <b> <strong>, <i> <em>, <u> <ins>, <s> <strike> <del>, <tg-spoiler> or <span class="tg-spoiler">, <code>, <pre> (<pre><code class="language-python">..</code></pre> names a language), <a href="..">, <blockquote> and <blockquote expandable>, <tg-emoji emoji-id="123">π</tg-emoji>, <br> for a line break. ``<`` ``>`` ``&`` stand for those characters. Any other tag is left as typed.
Markdown: **bold** *italic* _italic_ __underline__ ~~strikethrough~~ ||spoiler|| `code` ```code block``` [text](https://link)  a line that starts with ``>`` is quoted (``**>`` starts an expandable quote that ends with ``||``) and a backslash before a punctuation mark keeps it as it is. As in CommonMark, a mark must touch the text it formats (``**bold**``, not ``** bold **``), and a lone ``*`` or ``_`` inside a word does nothing. A link typed as it is (https://...) is never cut up by marks inside it.
Entities come out in the form the bot stores them (see ``tgutil.ser_entities``), with UTF-16 offsets like Telegram's."""from __future__ import annotations
import loggingimport reimport unicodedatafrom html.parser import HTMLParserfrom typing import List, Optional, Tuple
from .tgutil import ser_entities, utf16_len
log = logging.getLogger(__name__)
Span = Tuple[str, int, int, object] # (kind, offset, length, arg) - offsets in UTF-16 units, like Telegram's own
def _entity(kind: str, offset: int, length: int, arg=None) -> dict: """One entity as the bot stores it; `arg` is the pre block's language, the link, the emoji id or "expandable".""" e = {"k": kind, "o": offset, "l": length} if kind == "pre": e["g"] = arg or "" elif kind == "url": e["u"] = arg elif kind == "quote": e["c"] = bool(arg) elif kind == "emoji": e["d"] = arg return e
_NO_NEST = {"bold", "italic", "underline", "strike", "spoiler", "code", "quote", "url"} # a second one inside the first adds nothing
def _entities(spans: List[Span]) -> list: """Entities for the spans, outer ones first (same start: the longer one).
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 out: it changes nothing on screen, and Telegram does not want such entities nested.""" out: list = [] kept: List[Tuple[str, int, int]] = [] for kind, offset, length, arg in sorted((s for s in spans if s[2] > 0), key=lambda s: (s[1], -s[2])): if kind in _NO_NEST and any(k == kind and offset >= a and offset + length <= b for k, a, b in kept): continue kept.append((kind, offset, offset + length)) out.append(_entity(kind, offset, length, arg)) return out
# ------------------------------------------------------------------------------------------------------ links_SCHEMES = ("http://", "https://", "tg://", "ton://")_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*)?")
def clean_url(raw: Optional[str]) -> Optional[str]: """The link as Telegram wants it, or None when it is no link (``t.me/x`` gets its https://).""" url = (raw or "").strip() if not url or len(url) > 2000 or any(c.isspace() for c in url): return None low = url.lower() for scheme in _SCHEMES: if low.startswith(scheme): return url if len(url) > len(scheme) else None return "https://" + url if _DOMAIN.fullmatch(url) else None
# ------------------------------------------------------------------------------------------------------- HTML_TAGS = ("b", "strong", "i", "em", "u", "ins", "s", "strike", "del", "a", "code", "pre", "blockquote", "tg-spoiler", "tg-emoji", "span")_HTML_PAIR = re.compile(r"<(" + "|".join(re.escape(t) for t in _TAGS) + r")(?:\s[^<>]*)?>.*?</\1\s*>", re.I | re.S)_KIND_OF_TAG = { "b": "bold", "strong": "bold", "i": "italic", "em": "italic", "u": "underline", "ins": "underline", "s": "strike", "strike": "strike", "del": "strike", "tg-spoiler": "spoiler", "span": "spoiler",}
def looks_like_html(text: str) -> bool: """A supported tag with its closing tag is there (a lone ``<b>`` in a sentence is just text).""" return bool(_HTML_PAIR.search(text))
class _Html(HTMLParser): """Collects the text and the formatting of an HTML message; what it does not know is kept as it was typed."""
def __init__(self) -> None: super().__init__(convert_charrefs=True) self.parts: List[str] = [] self.pos = 0 # UTF-16 length of the text so far self.open: List[dict] = [] self.spans: List[Span] = []
def text(self, s: str) -> None: if s: self.parts.append(s) self.pos += utf16_len(s)
def literal_zone(self) -> bool: """Inside <pre> / <code> everything is code, so a tag there is shown as typed.""" return any(o["tag"] in ("pre", "code") for o in self.open)
# --- tags def handle_starttag(self, tag, attrs): t, a = tag.lower(), {k: (v or "") for k, v in attrs} raw = self.get_starttag_text() or "" if t == "br" and not self.literal_zone(): self.text("\n") return if self.literal_zone(): top = self.open[-1] if t == "code" and top["tag"] == "pre" and self.pos == top["start"] and "lang" not in top: cls = a.get("class", "") top["lang"] = cls[len("language-"):] if cls.startswith("language-") else "" self.open.append({"tag": "code", "start": self.pos, "holder": True}) else: self.text(raw) return if t == "span" and "tg-spoiler" not in a.get("class", "").split(): self.text(raw) elif t in _TAGS: self.open.append({"tag": t, "start": self.pos, "attrs": a}) else: self.text(raw)
def handle_startendtag(self, tag, attrs): if tag.lower() == "br" and not self.literal_zone(): self.text("\n") else: self.text(self.get_starttag_text() or "")
def handle_endtag(self, tag): t = tag.lower() if t == "br": return idx = next((i for i in range(len(self.open) - 1, -1, -1) if self.open[i]["tag"] == t), None) if idx is None: self.text(f"</{tag}>") return while len(self.open) > idx: # a tag opened inside it and never closed ends with it self.close_tag(self.open.pop())
def close_tag(self, o: dict) -> None: length = self.pos - o["start"] if length <= 0 or o.get("holder"): return t, a = o["tag"], o.get("attrs", {}) if t in _KIND_OF_TAG: self.spans.append((_KIND_OF_TAG[t], o["start"], length, None)) elif t == "code": self.spans.append(("code", o["start"], length, None)) elif t == "pre": self.spans.append(("pre", o["start"], length, o.get("lang", ""))) elif t == "a": url = clean_url(a.get("href")) if url: self.spans.append(("url", o["start"], length, url)) elif t == "blockquote": self.spans.append(("quote", o["start"], length, "expandable" in a)) elif t == "tg-emoji": emoji_id = a.get("emoji-id", "") if emoji_id.isdigit(): self.spans.append(("emoji", o["start"], length, int(emoji_id)))
# --- text and the rest def handle_data(self, data): self.text(data)
def handle_comment(self, data): self.text(f"<!--{data}-->")
def handle_decl(self, decl): self.text(f"<!{decl}>")
def handle_pi(self, data): self.text(f"<?{data}>")
def finish(self) -> Tuple[str, List[Span]]: self.close() while self.open: # a tag that was never closed ends with the text self.close_tag(self.open.pop()) return "".join(self.parts), self.spans
def from_html(source: str) -> Tuple[str, list]: """(text, entities) of an HTML message.""" parser = _Html() parser.feed(source) text, spans = parser.finish() return text, _entities(spans)
# --------------------------------------------------------------------------------------------------- Markdown_FENCE = re.compile(r"```(?:([A-Za-z0-9_+#.-]{1,30})\n)?(.+?)```", re.S)_EMOJI = re.compile(r"!\[([^\[\]\n]{1,16})\]\(tg://emoji\?id=(\d{1,20})\)")_BARE_URL = re.compile(r"(?:https?|tg|ton)://[^\s<>]+", re.I)_URL_END = "?!.,:;*_~|\"'" # what may follow a link without being part of it (a mark, or the end of a sentence)_KIND_OF_MARK = {("*", 2): "bold", ("*", 1): "italic", ("_", 2): "underline", ("_", 1): "italic", ("~", 2): "strike", ("|", 2): "spoiler"}MAX_MARKS = 400 # a message with more marks than this is left as typed (keeps the matching fast)
def _punct(ch: str) -> bool: return unicodedata.category(ch)[0] in "PS"
def _flanking(mark: str, run: int, prev: Optional[str], nxt: Optional[str]) -> Tuple[bool, bool]: """(can open, can close) for a run of `run` marks between the characters `prev` and `nxt`, by the CommonMark rules: it opens when text follows it and closes when text comes before it. A lone ``*`` and ``_`` also need a space or punctuation outside, so ``snake_case`` and a censored f*ck ... s*it stay as typed (``**bold**text`` still works).""" prev_space, next_space = prev is None or prev.isspace(), nxt is None or nxt.isspace() prev_punct, next_punct = prev is not None and _punct(prev), nxt is not None and _punct(nxt) left = not next_space and (not next_punct or prev_space or prev_punct) right = not prev_space and (not prev_punct or next_space or next_punct) if mark == "_" or (mark == "*" and run == 1): return left and (not right or prev_punct), right and (not left or next_punct) return left, right
def _bare_url(s: str, i: int) -> Optional[str]: """A link typed as it is (https://...) that starts at s[i], without what ends the sentence or closes a mark.""" if i and s[i - 1].isalnum(): return None m = _BARE_URL.match(s, i) if not m: return None url = m.group() while url: last = url[-1] if last in _URL_END or (last in ")]" and url.count(last) > url.count("(" if last == ")" else "[")): url = url[:-1] else: break return url if len(url) > url.index("//") + 2 else None
def _link_at(s: str, i: int) -> Optional[Tuple[str, str, int]]: """``[label](url)`` that starts at s[i]: (label, url, end) or None.""" depth, j, limit = 0, i, min(len(s), i + 600) while j < limit: ch = s[j] if ch == "\\": j += 2 continue if ch == "[": depth += 1 elif ch == "]": depth -= 1 if depth == 0: break j += 1 else: return None if j + 1 >= len(s) or s[j + 1] != "(": return None k, depth, limit = j + 2, 1, min(len(s), j + 2 + 2000) while k < limit: ch = s[k] if ch.isspace(): return None if ch == "(": depth += 1 elif ch == ")": depth -= 1 if depth == 0: break k += 1 else: return None url, label = clean_url(s[j + 2:k]), s[i + 1:j] return (label, url, k + 1) if url and label.strip() else None
class _Node: """A piece of a paragraph: plain text, a code span, an emoji, a link, or a run of marks ("d")."""
__slots__ = ("kind", "text", "spans", "arg", "ch", "orig", "left", "can_open", "can_close", "start")
def __init__(self, kind, text="", spans=None, arg=None, ch="", orig=0, can_open=False, can_close=False): self.kind, self.text, self.spans, self.arg = kind, text, spans or [], arg self.ch, self.orig, self.left, self.can_open, self.can_close = ch, orig, orig, can_open, can_close self.start = 0
def _inline(s: str, nested: bool = False) -> Tuple[str, List[Span]]: """Text and formatting of Markdown inside one paragraph (or one quote).""" nodes: List[_Node] = [] buf: List[str] = []
def flush() -> None: if buf: nodes.append(_Node("t", "".join(buf))) buf.clear()
i, n = 0, len(s) while i < n: c = s[i] if c == "\\" and i + 1 < n and s[i + 1].isascii() and _punct(s[i + 1]): buf.append(s[i + 1]) i += 2 continue if c == "`": run = 1 while i + run < n and s[i + run] == "`": run += 1 close = re.compile(r"(?<!`)" + "`" * run + r"(?!`)").search(s, i + run) if close and close.start() > i + run: flush() nodes.append(_Node("code", s[i + run:close.start()])) i = close.end() else: buf.append("`" * run) i += run continue if c == "!" and s.startswith("![", i): m = _EMOJI.match(s, i) if m: flush() nodes.append(_Node("emoji", m.group(1), arg=int(m.group(2)))) i = m.end() continue if c == "[" and not nested: link = _link_at(s, i) if link: flush() label, url, end = link inner, spans = _inline(label, nested=True) nodes.append(_Node("link", inner, spans, url)) i = end continue if c in "hHtT": url = _bare_url(s, i) if url: buf.append(url) i += len(url) continue if c in "*_~|": run = 1 while i + run < n and s[i + run] == c: run += 1 if c in "~|" and run != 2: buf.append(c * run) else: flush() can_open, can_close = _flanking(c, run, s[i - 1] if i else None, s[i + run] if i + run < n else None) nodes.append(_Node("d", ch=c, orig=run, can_open=can_open, can_close=can_close)) i += run continue buf.append(c) i += 1 flush() return _assemble(nodes)
def _assemble(nodes: List[_Node]) -> Tuple[str, List[Span]]: """Match the marks (CommonMark's delimiter-stack way), then lay out the text and the spans.""" marks = [k for k, nd in enumerate(nodes) if nd.kind == "d"] if len(marks) > MAX_MARKS: for k in marks: nodes[k].can_open = nodes[k].can_close = False pairs: List[Tuple[int, int, str]] = [] for pos, j in enumerate(marks): closer = nodes[j] while closer.can_close and closer.left > 0: found = None for kk in range(pos - 1, -1, -1): opener = nodes[marks[kk]] if opener.ch != closer.ch or not opener.can_open or opener.left <= 0: continue # a mark that could do both: runs whose lengths add up to a multiple of 3 do not pair (unless each is one) both = (opener.can_close or closer.can_open) and (opener.orig + closer.orig) % 3 == 0 if closer.ch in "*_" and both and not (opener.orig % 3 == 0 and closer.orig % 3 == 0): continue found = kk break if found is None: break opener = nodes[marks[found]] use = 2 if opener.left >= 2 and closer.left >= 2 else 1 pairs.append((marks[found], j, _KIND_OF_MARK[(closer.ch, use)])) opener.left -= use closer.left -= use for between in marks[found + 1:pos]: # what lies between the two can no longer pair across them nodes[between].can_open = nodes[between].can_close = False out: List[str] = [] pos = 0 for nd in nodes: nd.start = pos piece = nd.ch * nd.left if nd.kind == "d" else nd.text # marks that found no partner stay as typed out.append(piece) pos += utf16_len(piece) spans: List[Span] = [] for a, b, kind in pairs: begin = nodes[a].start + nodes[a].left spans.append((kind, begin, nodes[b].start - begin, None)) for nd in nodes: length = utf16_len(nd.text) if nd.kind == "code": spans.append(("code", nd.start, length, None)) elif nd.kind == "emoji": spans.append(("emoji", nd.start, length, nd.arg)) elif nd.kind == "link": spans.append(("url", nd.start, length, nd.arg)) spans.extend((k, nd.start + o, ln, arg) for k, o, ln, arg in nd.spans) return "".join(out), spans
def _quote_line(line: str) -> Optional[Tuple[str, bool]]: """(the line without its mark, whether it starts an expandable quote) when `line` is part of a quote.""" expandable = line.startswith("**>") if expandable or (line.startswith(">") and not line.startswith(">>")): # ">> Download <<" is decoration, not a quote body = line[3:] if expandable else line[1:] return (body[1:] if body.startswith(" ") else body), expandable return None
def _blocks(seg: str) -> Tuple[str, List[Span]]: """A stretch of Markdown without code blocks: paragraphs and quotes.""" runs: List[list] = [] # [is_quote, expandable, lines] for line in seg.split("\n"): q = _quote_line(line) if q is None: if runs and not runs[-1][0]: runs[-1][2].append(line) else: runs.append([False, False, [line]]) elif runs and runs[-1][0] and not q[1]: runs[-1][2].append(q[0]) else: runs.append([True, q[1], [q[0]]]) out: List[str] = [] spans: List[Span] = [] pos = 0 for is_quote, expandable, lines in runs: if is_quote and expandable and lines[-1].endswith("||"): lines[-1] = lines[-1][:-2] text, inner = _inline("\n".join(lines)) spans.extend((kind, pos + o, n, arg) for kind, o, n, arg in inner) if is_quote and text.strip(): spans.append(("quote", pos, utf16_len(text), expandable)) out.append(text) pos += utf16_len(text) + 1 # + the line break that separates it from the next run return "\n".join(out), spans
def from_markdown(source: str) -> Tuple[str, list]: """(text, entities) of a Markdown message.""" out: List[str] = [] spans: List[Span] = [] pos = 0
def add(text: str, found: List[Span]) -> None: nonlocal pos spans.extend((kind, pos + o, n, arg) for kind, o, n, arg in found) out.append(text) pos += utf16_len(text)
last = 0 for m in _FENCE.finditer(source): code = m.group(2) if m.group(1) is None and code.startswith("\n"): code = code[1:] if code.endswith("\n"): code = code[:-1] if not code: continue add(*_blocks(source[last:m.start()])) add(code, [("pre", 0, utf16_len(code), m.group(1) or "")]) last = m.end() add(*_blocks(source[last:])) return "".join(out), _entities(spans)
# ------------------------------------------------------------------------------------------- what the bot usesdef convert(text: str) -> Tuple[str, list, Optional[str]]: """(text, entities, "html" | "markdown" | None) for text that carries no Telegram formatting.
Text with nothing to read comes back as it was (the third value None). It never raises: text the readers choke on is simply used as typed, so a post is never lost to a formatting quirk. """ try: if looks_like_html(text): new, ents = from_html(text) return new, ents, "html" new, ents = from_markdown(text) except Exception: # noqa: BLE001 log.warning("could not read the formatting of a text - using it as typed", exc_info=True) return text, [], None return (new, ents, "markdown") if (ents or new != text) else (text, [], None)
def message_text(m, enabled: bool = True) -> Tuple[str, list, Optional[str]]: """(text, entities in the form the bot stores, "html" | "markdown" | None) of a message the owner sent.
Telegram's own formatting wins: a message that has some is kept exactly as it is. Otherwise HTML or Markdown in the text becomes formatting (unless `enabled` is False). The last value says which one was read. """ text = m.raw_text or "" own = ser_entities(m.entities) # (links, @mentions, #tags ... that Telegram finds by itself are not formatting) if own or not enabled or not text: return text, own, None return convert(text)
CHEAT_SHEET = ( "βοΈ <b>Formatting</b>\n\n" "Send a post with Telegram's own formatting (bold, italic, quote, spoiler, links ...) and it is published exactly " "like that. When you can't use Telegram's editor, type <b>Markdown</b> or <b>HTML</b> instead - the bot turns it " "into real formatting. A message that already has Telegram formatting is used as it is, and text the bot doesn't " "recognise stays as you typed it. π Preview shows the result before you publish.\n\n" "<b>Markdown</b>\n" "<code>**bold**</code> <code>*italic*</code> <code>_italic_</code> <code>__underline__</code> " "<code>~~strike~~</code> <code>||spoiler||</code>\n" "<code>`code`</code> and <code>```code block```</code> (<code>```python</code> and a line break names the language)\n" "<code>[text](https://t.me/name)</code> - a link\n" "<code>> quote</code> - a line that starts with > is quoted (<code>**></code> on the first line and " "<code>||</code> at the end of the last one make it expandable)\n" "<code>\\*</code> - a backslash keeps the next mark as it is. As in any Markdown, the marks must touch the text " "(<code>**bold**</code>, not <code>** bold **</code>) and <code>_</code> inside a word does nothing.\n\n" "<b>HTML</b>\n" "<code><b>bold</b></code> <code><i>italic</i></code> " "<code><u>underline</u></code> <code><s>strike</s></code> " "<code><tg-spoiler>spoiler</tg-spoiler></code>\n" "<code><code>code</code></code> <code><pre>block</pre></code> " "<code><a href=\"https://t.me/name\">link</a></code>\n" "<code><blockquote>quote</blockquote></code> (<code><blockquote expandable></code> for an " "expandable one) and <code><br></code> for a line break.\n" "Write <code>&lt;</code> for a < that must stay. A text that has an HTML tag with its closing tag is read " "as HTML only.\n\n" "<b>Example</b>\n" "<pre>**Attack on Titan** - Episode 12\n" "__Hindi__ | ||spoiler||\n" "[Watch here](https://t.me/yourchannel)</pre>\n\n" "π§© Headings, lists, tables, expandable sections, math, maps, pictures and buttons are <b>rich messages</b> - " "see /rich.")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455"""Service messages: the notices Telegram puts into a channel by itself - "channel name changed", "channel photoupdated", "<admin> pinned a message", "live stream started" ... The bot removes them from every connected channel."""from __future__ import annotations
import loggingfrom dataclasses import dataclassfrom typing import Optional
from telethon import errors, functions, types
from .tgutil import flood_retry
log = logging.getLogger(__name__)
# Telegram refusals that mean "the bot has no right to delete here" (worth telling the owner about)RIGHTS_ERRORS = ("ChatAdminRequiredError", "ChatWriteForbiddenError", "ChannelPrivateError", "UserNotParticipantError")
def is_service(m) -> bool: return isinstance(m, types.MessageService)
def action_label(m) -> str: """'PinMessage', 'ChatEditTitle', 'GroupCall' ... - for the log.""" name = type(getattr(m, "action", None)).__name__ return name[len("MessageAction"):] if name.startswith("MessageAction") else name
@dataclassclass Removed: deleted: int = 0 failed: int = 0 error: Optional[BaseException] = None # the first thing Telegram refused with
@property def error_name(self) -> Optional[str]: return type(self.error).__name__ if self.error is not None else None
async def remove(client, peer, ids: list) -> Removed: """Delete these messages, 100 per request. A refusal is reported in the result, never raised.""" out = Removed() ids = sorted(set(ids)) for i in range(0, len(ids), 100): part = ids[i : i + 100] try: res = await flood_retry(lambda part=part: client(functions.channels.DeleteMessagesRequest(channel=peer, id=part))) except errors.RPCError as e: out.failed += len(part) out.error = out.error or e continue n = getattr(res, "pts_count", None) out.deleted += len(part) if n is None else min(len(part), int(n)) return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187"""/shift: copy posts of one channel into another channel - text, formatting, media, albums, buttons and replies- and register the copies in My posts. The source is only read, never changed or deleted.
It is the /repost copy loop pointed at two channels. Links from a shifted post to another post of the source channelfollow the content: when that post was shifted too, the link points at its copy in the destination.
Three optional extras are remembered with the shift (job marks), so that continuing a stopped shift keeps them: -c afterwards every link to a post of the source, in ANY connected channel, is pointed at the copy (crosslinks.relink_after_shift; the source itself is only read); -all afterwards the destination gets the source's name, description and profile photo (profile_copy.copy_profile); --no-media the copies get no files: every post is copied as its text, with its formatting and buttons (mark "nomedia"; repost_engine.without_files). A post that is only a file has nothing to copy and is left out.
When Telegram hides the first new copies (read back right after posting) the shift stops by itself - more copies wouldonly be more posts nobody can see - and goes on only when the owner presses Continue (mark "hiddenok").
A source that Telegram restricts (a copyright strike: "This channel is unavailable due to copyright infringement", itsposts marked or shown as a notice) is copied from what My posts saved of its posts - every post that has a saved copy,however intact Telegram's version looks (repost_engine.copy_source). A post without a saved copy is copied as Telegramhands 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 (abanned or private channel) is copied from My posts alone: mark "fromdb", set when the plan was made that way."""from __future__ import annotations
import loggingfrom types import SimpleNamespacefrom typing import Any, Awaitable, Callable, Optional
from .crosslinks import CrossResult, relink_after_shift, shift_linksfrom .profile_copy import copy_profilefrom .repost_engine import ( STOP_IF_HIDDEN, CopyJob, DeleteResult, RepostOptions, RepostPlan, RepostResult, copy_loop, delete_pending, plan_from_saved, relink_copies, saved_lookup, saved_units,)from .restrictions import probe_channelfrom .tgutil import peer_of
log = logging.getLogger(__name__)
def source_of(shift) -> SimpleNamespace: """The source channel as stored with the shift (it need not be registered in the bot).""" return SimpleNamespace( id=shift.src_channel_id, access_hash=shift.src_access_hash, username=shift.src_username, title=shift.src_title )
async def plan_from_my_posts( db, src, first_id=None, last_id=None, unreadable=None, no_media: bool = False) -> Optional[RepostPlan]: """The plan of a shift made from My posts alone, for a source that can't be read; None when My posts has nothing of that channel (in that range).""" plan = plan_from_saved( src, await db.sent_posts_from(src.id, first_id or 1), RepostOptions(), first_id=first_id, last_id=last_id, unreadable=unreadable, no_media=no_media, ) return None if plan.error else plan
async def run_shift( client, db, shift, dst, user_id: int, *, delay: float = 1.2, settle_pause: float = 0.7, progress: Optional[Callable[[RepostResult], Awaitable[None]]] = None, should_stop: Optional[Callable[[], bool]] = None,) -> RepostResult: """Copy the posts shift.first_id..shift.last_id of the source into `dst` (a registered channel), in order. Safe to run again to continue: posts that already have a copy are skipped.""" src = source_of(shift) idmap = dict(await db.shift_pairs(shift.id, alive_only=False)) links = shift_links(src, dst, idmap) marks = await db.marks_of(shift.id) from_db = "fromdb" in marks # the source can't be read: its posts come from My posts alone restricted = None if not from_db: # does Telegram restrict the source channel itself (a copyright strike)? Then My posts is used try: _top, restricted, _err = await probe_channel(client, peer_of(src)) except Exception: # unknown is treated as "not restricted": marks on single posts and the read-back still guard log.warning("could not ask Telegram whether the source channel is restricted", exc_info=True) job = CopyJob( src_peer=peer_of(src), dst_peer=peer_of(dst), opts=RepostOptions(), links=links, first_id=shift.first_id, last_id=shift.last_id, done=await db.shift_done_ids(shift.id), idmap=idmap, record=lambda rows: db.record_shift(shift.id, dst.id, rows, user_id), saved=saved_lookup(db, src.id), # posts Telegram holds back (a copyright strike) are copied from My posts use_saved=True, units=(lambda: saved_units(db, src.id, shift.first_id, shift.last_id)) if from_db else None, from_db=from_db, restricted=restricted, no_media="nomedia" in marks, stop_if_hidden=0 if "hiddenok" in marks else STOP_IF_HIDDEN, # the owner said to go on although Telegram hides them ) res = await copy_loop(client, job, delay=delay, progress=progress, should_stop=should_stop, settle_pause=settle_pause) if not res.stopped and not res.aborted: res.phase = "finish" if progress: await progress(res) try: pairs = await db.shift_pairs(shift.id) res.final = await relink_copies( client, db, dst, dict(pairs), [n for _, n in pairs], links=links, delay=delay, settle_pause=settle_pause, should_stop=should_stop, ) except Exception as e: # the copies are fine; only the links between them were not updated log.exception("pointing the links of a shift at the copies failed") res.final_error = type(e).__name__ marks = await db.marks_of(shift.id) if "profile" in marks and "profile_done" not in marks: await shift_profile(client, db, shift, dst, user_id, res, progress) if "relink" in marks and not (res.final is not None and res.final.stopped): res.phase = "links" res.cross = CrossResult()
async def watch(_cross) -> None: if progress: await progress(res)
if progress: await progress(res) try: await relink_after_shift( client, db, shift, src, dst, delay=delay, settle_pause=settle_pause, progress=watch, should_stop=should_stop, result=res.cross, ) except Exception as e: # the copies are fine; only the links in the other channels were not updated log.exception("pointing the links of the other channels at the shifted posts failed") res.cross_error = type(e).__name__ return res
async def shift_profile(client, db, shift, dst, user_id: int, res: RepostResult, progress=None) -> None: """-all: the destination takes over the source's name, description and photo (the outcome goes into `res`).""" res.phase = "profile" if progress: await progress(res) try: res.profile = await copy_profile(client, source_of(shift), dst) if res.profile.title: # the destination has a new name: keep the bot's own list right await db.save_channel(dst.id, dst.access_hash, res.profile.title, dst.username, user_id) if res.profile.ok: await db.set_mark(shift.id, "profile_done") except Exception as e: # the copies are fine; only the channel's name / description / photo were not copied log.exception("copying the channel profile failed") res.profile_error = type(e).__name__
async def delete_shift_copies( client, db, dst, shift, *, delay: float = 0.5, progress: Optional[Callable[[DeleteResult], Awaitable[None]]] = None, fallback: Optional[Callable[[list], Awaitable[Any]]] = None,) -> DeleteResult: """Undo: remove the copies of this shift from the destination channel (the source is not touched).""" todo = await db.shift_pending_new(shift.id, 1_000_000)
async def mark(ids: list) -> None: await db.mark_shift_deleted(shift.id, dst.id, ids)
res = await delete_pending(client, peer_of(dst), todo, mark, delay=delay, progress=progress, fallback=fallback) res.remaining = (await db.shift_counts(shift.id))["new_left"] res.blocked = res.remaining > 0 and not res.error return res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Auto-suggest the next episode batch: 'Download Episodes 01 to 20' -> 'Download Episodes 21 to 40'."""from __future__ import annotations
import copyimport refrom dataclasses import dataclass, fieldfrom typing import Optional
from telethon.helpers import add_surrogate, del_surrogate
from .linkswap import apply_span_replacementsfrom .richmsg import is_richfrom .tgutil import de_entities, ser_entities
RANGE_RX = re.compile(r"(?P<a>\d+)(?P<sep>\s*(?:to|[-ββ~&])\s*)(?P<pre>(?:ep?\.?\s*)?)(?P<b>\d+)", re.I)SINGLE_RX = re.compile(r"(?<![\w.])(?P<label>episodes?|eps?\.?|e)(?P<gap>\s*[-:#]?\s*)(?P<n>\d+)(?!\d)", re.I)
@dataclassclass Advance: new_text: str # the whole string with the numbers moved on old_span: str # e.g. "01 to 20" new_span: str # e.g. "21 to 40"
def advance_plain(s: str) -> Optional[Advance]: """Move the first episode range (or single episode) in `s` on to the next batch.""" for m in RANGE_RX.finditer(s or ""): a_s, b_s = m.group("a"), m.group("b") a, b = int(a_s), int(b_s) if a > b or b - a > 5000: continue step = b - a + 1 width = max(len(a_s), len(b_s)) if (a_s.startswith("0") or b_s.startswith("0")) else 0 na, nb = str(b + 1).zfill(width), str(b + step).zfill(width) new_span = na + s[m.end("a"):m.start("b")] + nb return Advance( new_text=s[: m.start("a")] + new_span + s[m.end("b"):], old_span=s[m.start("a"):m.end("b")], new_span=new_span, ) for m in SINGLE_RX.finditer(s or ""): n_s = m.group("n") width = len(n_s) if n_s.startswith("0") else 0 nn = str(int(n_s) + 1).zfill(width) return Advance( new_text=s[: m.start("n")] + nn + s[m.end("n"):], old_span=s[m.start("label"):m.end("n")], new_span=s[m.start("label"):m.start("n")] + nn, ) return None
@dataclassclass Suggestion: text: str entities: list buttons: list media_kind: Optional[str] media_file_id: Optional[str] pending: list = field(default_factory=list) # [(row, col)] of buttons that still need a link prev_label: str = "" new_label: str = "" source_post_id: int = 0
def build_suggestion(post) -> Optional[Suggestion]: if is_rich(post): # its text lives in blocks Telegram made: the numbers can't be moved on in them return None rows: list = [] pending: list = [] first: Optional[Advance] = None prev_label = "" for row in post.buttons or []: new_row: list = [] for b in row: if b.get("raw"): # other bots' buttons (e.g. reactions) are not carried over continue b = dict(b) b.pop("s", None) adv = advance_plain(b.get("t", "")) if b.get("u") else None if adv: if first is None: first, prev_label = adv, b["t"] b["t"] = adv.new_text b["u"] = None pending.append((len(rows), len(new_row))) new_row.append(b) if new_row: rows.append(new_row) if not pending or first is None: return None
text = post.text or "" entities = copy.deepcopy(post.entities or []) sur = add_surrogate(text) repls: list = [] pos = 0 while first.old_span: i = sur.find(first.old_span, pos) if i < 0: break repls.append((i, i + len(first.old_span), first.new_span)) pos = i + len(first.old_span) if repls: new_sur, new_ents = apply_span_replacements(sur, de_entities(entities), repls) text, entities = del_surrogate(new_sur), ser_entities(new_ents)
return Suggestion( text=text, entities=entities, buttons=rows, media_kind=post.media_kind, media_file_id=post.media_file_id, pending=pending, prev_label=prev_label, new_label=rows[pending[0][0]][pending[0][1]]["t"], source_post_id=post.id, )
async def make_suggestion(db, channel_id: int) -> Optional[Suggestion]: for p in await db.latest_sent(channel_id, 30): s = build_suggestion(p) if s: return s return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600"""Keeps My posts in step with the channels: what admins do outside the bot is noticed and recorded.
What a look at a channel does * every post the bot has saved is read back from Telegram: a post that is gone is removed here, a post that was edited gets its saved copy updated (text, formatting, buttons, media); * messages that appeared since the last look are saved as new posts (source "adopted"); * the posts that were in the channel BEFORE the bot was added are read into My posts too, oldest first, up to the newest message that existed at the first look. Where the reading stopped is saved, so a long channel takes a few looks. Posts the owner told the bot to forget are skipped for good; * service messages ("channel name changed", "pinned a message", video chat ...) found on the way are deleted.
Safety rules * posts the bot touched a moment ago, and messages that appeared a moment ago, are left for the next look (the bot may still be saving them); * a saved copy is only changed if nobody changed it since it was read (optimistic check in the database); * buttons that are missing in the channel are never removed from the saved copy (Telegram sometimes hides a keyboard for a while - the saved buttons are what "Check buttons" restores from); * if EVERY saved post of a channel looks deleted, the bot first makes sure it can read the channel at all: when it still sees other messages there (or the channel's event counter moved by at least that many events, which is what really deleting them looks like) the posts are really gone and leave My posts; only when it sees nothing at all - more likely the bot lost access - is nothing removed; * what TELEGRAM does to a channel is not an admin's edit: a channel it restricts (a copyright strike turns every post into "This message couldn't be displayed on your device due to copyright infringement"), a single post it holds back, a notice shown instead of a post, or many posts that suddenly all show one and the same text are left exactly as saved - nothing is edited, removed or added for them."""from __future__ import annotations
import asyncioimport loggingimport timefrom dataclasses import dataclass, fieldfrom typing import Any, Optional
from telethon import errors, types
from .db import as_utc, utcnowfrom .replace_engine import fetch_messagesfrom .repost_engine import delete_batchfrom .restrictions import message_restriction, norm_text, probe_channelfrom .richmsg import Rich, entry as rich_entry, is_rich_message, plain_of_message, rich_from_received, rich_of, with_fingerprintfrom .tgutil import classify_media, explain_rpc, media_from_ref, media_info, peer_of, ser_entities, ser_markup
log = logging.getLogger(__name__)
CHUNK = 100 # Telegram returns at most 100 messages per requestGRACE = 120.0 # seconds a post or message must be old before it is judgedPAUSE = 0.25 # between two requests of a scanSLACK_CAP = 300 # a quick look reads this many ids beyond the most likely end of the new messagesDEEP_EVERY = 24 * 3600 # the automatic looks read every possible id at least this oftenMIN_FOR_ANOMALY = 5MASS_SAME = 5 # this many posts that suddenly show the very same new text are not edits by a personMAX_PROBE = 300 # requests spent finding the newest message the first time (30 000 ids)
# ----------------------------------------------------------------------------------------------- options@dataclassclass SyncOptions: deep: bool = False # read every possible id for new messages, not only the likely ones delete_services: bool = True adopt: bool = True # save new posts of others history: bool = True # also read the posts from before the bot was added into My posts history_seconds: Optional[float] = None # ... for at most this long per look (None: as long as it takes) grace: float = GRACE pause: float = PAUSE ignore: Any = field(default_factory=set) # (channel id, message id) of posts the owner told the bot to forget
@dataclassclass SyncReport: channel: Any phase: str = "" checked: int = 0 # saved posts compared with the channel deleted: list = field(default_factory=list) # message ids that were gone: removed from My posts edited: list = field(default_factory=list) # message ids whose saved copy was brought up to date refreshed: int = 0 # saved copies corrected for trifles (a trailing space ...) adopted: list = field(default_factory=list) # message ids of new posts that were saved imported: int = 0 # older posts (from before the bot was added) that were added to My posts history_unsupported: int = 0 # older messages My posts can't hold (polls, stickers ...) history_top: int = 0 # the newest message that counts as older (0: the older posts were not looked at) history_to: int = 0 # the older posts have been read up to this message id history_done: bool = False # ... and that was all of them unsupported: int = 0 # new messages of a kind My posts can't show (polls, stickers ...) buttons_missing: list = field(default_factory=list) # saved buttons that the channel shows no keyboard for services_deleted: int = 0 services_failed: int = 0 services_error: Optional[str] = None # name of the refusal restricted: list = field(default_factory=list) # message ids Telegram holds back (copyright ...): left as saved restricted_why: Optional[str] = None # what Telegram says about them restricted_channel: Optional[str] = None # the whole channel is restricted: nothing was looked at young: list = field(default_factory=list) # saved posts the bot touched a moment ago: judge them later young_new: list = field(default_factory=list) # new messages that appeared a moment ago: save them later changed_meanwhile: int = 0 # saved posts that were changed through the bot while we looked (left alone) first_look: bool = False busy: bool = False # a long job started: the look was cut short anomaly: Optional[str] = None error: Optional[str] = None scanned_to: int = 0
@property def changed(self) -> bool: return bool(self.deleted or self.edited or self.adopted or self.imported or self.services_deleted)
# ------------------------------------------------------------------------------------- comparing a postdef age(dt, now) -> float: """Seconds since `dt` (never negative); unknown = very old.""" if dt is None: return float("inf") return max(0.0, (now - as_utc(dt)).total_seconds())
def media_key(media) -> Optional[tuple]: """Which photo / file a message carries (its id - the file reference changes from fetch to fetch).""" if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None): return ("photo", media.photo.id) if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None): return ("doc", media.document.id) return None
def stored_media_key(ref: Optional[str]) -> Optional[tuple]: if not ref: return None try: return media_key(media_from_ref(ref)) except Exception: return ("unreadable", ref[:40]) # differs from anything real: the saved reference gets replaced
def live_rich(m) -> Optional[Rich]: """The rich message the live message is (as blocks), or None for an ordinary post.""" rm = getattr(m, "rich_message", None) return rich_from_received(rm) if rm is not None else None
def live_fields(m) -> dict: """The saved-post fields of a message as it is in the channel now.""" kind, ref = media_info(m) rich = live_rich(m) return { "text": plain_of_message(m) if rich is not None else (m.message or ""), "entities": [rich_entry(rich)] if rich is not None else ser_entities(m.entities), "buttons": ser_markup(m.reply_markup), "media_kind": kind, "media_file_id": ref, }
def message_supported(m) -> bool: """Something My posts can show and edit: text, a rich message, or a photo / video / GIF / audio / file.""" return bool((m.message or "").strip()) or classify_media(m) is not None or is_rich_message(m)
def adopt_fields(m) -> dict: f = live_fields(m) f["link_preview"] = isinstance(getattr(m, "media", None), types.MessageMediaWebPage) return f
# ------------------------------------------------------------------- what Telegram itself does to a channelMASS_NOTE = "many posts suddenly show one and the same text - that is Telegram's notice, not an edit"
def split_mass_text(edits: list) -> tuple: """(edits to save, edits to hold back). Five or more saved posts that had five different texts and now all show the very same text at once: nobody edits like that - Telegram does it to a channel it restricts.""" groups: dict = {} for item in edits: new = norm_text(item[1].fields.get("text")) if new: groups.setdefault(new, []).append(item) bad: set = set() for items in groups.values(): if len(items) >= MASS_SAME and len({norm_text(p.text) for p, _ in items}) >= MASS_SAME: bad.update(id(i) for i in items) return [i for i in edits if id(i) not in bad], [i for i in edits if id(i) in bad]
def hold_back(rep: "SyncReport", ids, why: Optional[str]) -> None: rep.restricted.extend(ids) rep.restricted_why = rep.restricted_why or why
@dataclassclass Diff: fields: dict = field(default_factory=dict) # what to save buttons_missing: bool = False quiet: bool = False # only a trifle differs (surrounding spaces): fix it without counting it as an edit
def diff_post(p, m) -> Diff: """What differs between the saved post `p` and the live message `m`.""" live = live_fields(m) fields: dict = {} saved_rich, now_rich = rich_of(p), live_rich(m) if is_rich_message(m) else None first_look = False if saved_rich is None and now_rich is None: if (p.text or "") != live["text"]: fields["text"] = live["text"] if list(p.entities or []) != live["entities"]: fields["entities"] = live["entities"] elif now_rich is not None: # A rich message is compared by what Telegram shows of it (a fingerprint of its blocks), never by its text: the # saved copy keeps the source the bot sent. A post that became rich in the channel is taken over as its blocks. if saved_rich is None or (saved_rich.fp is not None and saved_rich.fp != now_rich.fp): fields["text"], fields["entities"] = live["text"], live["entities"] elif saved_rich.fp is None: # the bot's own rich post, seen for the first time: remember what Telegram shows fields["entities"] = [rich_entry(with_fingerprint(saved_rich, now_rich.fp))] first_look = True elif live["text"].strip() or live["media_kind"] is not None: # the channel shows an ordinary post where a rich message was saved (an empty answer is not trusted) fields["text"], fields["entities"] = live["text"], live["entities"] # media: replaced media is taken over; media that seems to have vanished is not (a message can't lose its media) if live["media_kind"] is not None: if p.media_kind != live["media_kind"] or stored_media_key(p.media_file_id) != media_key(m.media): fields["media_kind"], fields["media_file_id"] = live["media_kind"], live["media_file_id"] missing = False if live["buttons"]: if list(p.buttons or []) != live["buttons"]: fields["buttons"] = live["buttons"] elif p.buttons: missing = True quiet = (set(fields) == {"text"} and (p.text or "").strip() == live["text"].strip()) or ( first_look and set(fields) == {"entities"} ) return Diff(fields, missing, quiet)
# --------------------------------------------------------------------------------------- talking to Telegramdef is_gone(m) -> bool: return m is None or isinstance(m, types.MessageEmpty)
async def find_top(client, peer, pts: int, floor: int, *, pause: float = PAUSE) -> int: """The newest message id that exists. Only the event counter is known (never lower), so look downwards from it; `floor` (the newest saved post) is where the looking can stop.""" hi = pts for _ in range(MAX_PROBE): if hi <= floor: break lo = max(floor + 1, hi - CHUNK + 1) msgs = await fetch_messages(client, peer, list(range(lo, hi + 1))) alive = [m.id for m in msgs if not is_gone(m)] if alive: return max(alive) hi = lo - 1 await asyncio.sleep(pause) return max(floor, hi)
async def sees_live_messages(client, peer, pts: Optional[int], *, pause: float = PAUSE, tries: int = MAX_PROBE) -> bool: """True when the bot can read at least one message of the channel (a post or a service message). Then a saved post that is missing from the channel really is gone - the bot is not just blind. Looks downwards from the event counter.""" if not pts or pts < 1: return False hi = pts for _ in range(tries): if hi < 1: return False lo = max(1, hi - CHUNK + 1) msgs = await fetch_messages(client, peer, list(range(lo, hi + 1))) if any(not is_gone(m) for m in msgs): return True hi = lo - 1 await asyncio.sleep(pause) return False
async def delete_services(client, peer, ids: list, rep: SyncReport) -> None: """Delete service messages and count what happened (the bot only: Telegram may refuse the old ones).""" ids = sorted(set(ids)) for i in range(0, len(ids), CHUNK): part = ids[i : i + CHUNK] out = await delete_batch(client, peer, part) rep.services_deleted += len(out.gone) left = len(part) - len(out.gone) if left: rep.services_failed += left rep.services_error = rep.services_error or out.bot_error or "NotDeleted"
# ------------------------------------------------------------------------------------- the three stepsasync def _save_edits(db, rep: SyncReport, edits: list, busy) -> None: for p, d in edits: if busy(): rep.busy = True return if await db.sync_update_post(p.id, p.updated_at, d.fields): if d.quiet: rep.refreshed += 1 else: rep.edited.append(p.message_id) else: rep.changed_meanwhile += 1
async def _adopt(db, ch, rep: SyncReport, fresh: list, opts: SyncOptions, busy, now) -> None: """Save messages the bot does not know (ascending ids); too fresh ones are left for the next look.""" known: set = set() ids = [m.id for m in fresh] for i in range(0, len(ids), 500): known |= {p.message_id for p in await db.posts_at(ch.id, ids[i : i + 500])} forgotten = await db.ignored_ids(ch.id) if fresh else set() todo = [] for m in fresh: if m.id in known or m.id in forgotten or (ch.id, m.id) in opts.ignore: continue why = message_restriction(m) if why: # Telegram holds it back: what it shows now is not what the post says hold_back(rep, [m.id], why) elif age(m.date, now) < opts.grace: rep.young_new.append(m.id) elif not message_supported(m): rep.unsupported += 1 else: todo.append(m) for m in todo: if busy(): rep.busy = True return _, created = await db.adopt_message(ch.id, m.id, adopt_fields(m), sent_at=m.date) if created: rep.adopted.append(m.id)
async def _compare_saved( client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, moved=None, pts: Optional[int] = None) -> None: """Every saved post against the channel. `moved`: how far the channel's event counter has come since the last look (None: unknown) - deleting posts is an event each, which tells "everything was deleted" from "I can't see anything". `pts`: the channel's event counter now - where the bot looks for other messages to prove that it can read the channel.""" rep.phase = "comparing the saved posts" peer = peer_of(ch) posts = await db.sent_posts(ch.id) # the saved copies are read BEFORE the channel is, never after now = utcnow() judge = [] for p in posts: if min(age(p.updated_at, now), age(p.sent_at, now)) < opts.grace: rep.young.append(p.message_id) else: judge.append(p) rep.checked = len(judge) by_id = {p.message_id: p for p in judge} ids = sorted(by_id) gone, edits = [], [] for i in range(0, len(ids), CHUNK): if busy(): rep.busy = True return chunk = ids[i : i + CHUNK] msgs = await fetch_messages(client, peer, chunk) for mid, m in zip(chunk, msgs): p = by_id[mid] if is_gone(m): gone.append(p) elif isinstance(m, types.MessageService): continue # not a post any more (cannot happen: ids are never reused) else: why = message_restriction(m, p.text) if why: # Telegram's doing, not an admin's: the saved copy stays exactly as it is hold_back(rep, [mid], why) continue d = diff_post(p, m) if d.buttons_missing: rep.buttons_missing.append(mid) if d.fields: edits.append((p, d)) rep.scanned_to = chunk[-1] if progress: await progress(rep) await asyncio.sleep(opts.pause) edits, held = split_mass_text(edits) if held: hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE) if gone: really = moved is not None and moved >= len(gone) # at least one event for each post that vanished everything = len(ids) >= MIN_FOR_ANOMALY and len(gone) == len(ids) if everything and not really: # No earlier look to compare with (or too few events): is the bot blind, or are the posts really gone? If it # can read other messages of the channel it is not blind. if busy(): rep.busy = True return really = await sees_live_messages(client, peer, pts, pause=opts.pause) if everything and not really: rep.anomaly = ( f"All {len(ids)} saved posts look deleted, and I can't read any other message of the channel either, " "so none was removed here - check that the bot is still an admin of the channel." ) else: gone_ids = [p.message_id for p in gone] await db.forget_posts(ch.id, gone_ids) rep.deleted.extend(gone_ids) await _save_edits(db, rep, edits, busy)
async def _look_for_new(client, db, ch, rep: SyncReport, opts: SyncOptions, state, pts: int, busy, progress) -> None: """Messages that appeared since the last look: new posts are saved, service messages deleted.""" rep.phase = "looking for new posts" peer = peer_of(ch) now = utcnow() if state is None: # the first look: only note where the channel stands floor = await db.max_saved_id(ch.id) top = await find_top(client, peer, pts, floor, pause=opts.pause) rep.first_look, rep.scanned_to = True, top await db.save_sync(ch.id, last_top=top, last_pts=pts, deferred=0, deep=True) return deep = opts.deep or age(state.last_deep, now) > DEEP_EVERY if pts == state.last_pts and not state.deferred and not deep: return # not a single event since the last look: a quick look would read exactly what it read then delta = max(0, pts - state.last_pts) slack = min(max(0, state.last_pts - state.last_top), SLACK_CAP) soft = pts if deep else min(pts, state.last_top + delta + slack) a, highest, had_live = state.last_top + 1, state.last_top, True fresh, services = [], [] while a <= pts: if a > soft and not had_live: break # past the likely end and the last stretch was empty if busy(): rep.busy = True return hi = min(a + CHUNK - 1, pts) msgs = await fetch_messages(client, peer, list(range(a, hi + 1))) had_live = False for m in msgs: if is_gone(m): continue had_live = True highest = max(highest, m.id) if isinstance(m, types.MessageService): services.append(m) else: fresh.append(m) rep.scanned_to = hi if progress: await progress(rep) a = hi + 1 await asyncio.sleep(opts.pause) services_ids = [m.id for m in services] if opts.delete_services and services_ids: await delete_services(client, peer, services_ids, rep) if opts.adopt and fresh: await _adopt(db, ch, rep, fresh, opts, busy, now) if rep.busy: return new_top = highest if rep.young_new: # these have to be looked at again: don't move the mark past them new_top = min(new_top, min(rep.young_new) - 1) await db.save_sync( ch.id, last_top=max(state.last_top, new_top), last_pts=pts, deferred=len(rep.young_new), deep=deep )
async def _import_history(client, db, ch, rep: SyncReport, opts: SyncOptions, busy, progress, state=None) -> None: """The posts that were in the channel before the bot was added are read into My posts: from message 1 up to the newest message that existed at the first look (what came after is the business of _look_for_new). The place where the reading stopped is saved - a long channel takes a few looks, and a restart loses nothing. `state`: where the look before this one stopped (None at the very first look: the mark that look has just set is used).""" hist = await db.get_history(ch.id) if hist is None: base = state if state is not None else await db.get_sync(ch.id) if base is None: return hist = await db.start_history(ch.id, base.last_top) if hist.done: return rep.phase = "reading the older posts" peer = peer_of(ch) began = time.monotonic() forgotten = await db.ignored_ids(ch.id) rep.history_top = hist.top a = hist.next_id rep.history_to = a - 1 while a <= hist.top: if busy(): rep.busy = True return if opts.history_seconds is not None and time.monotonic() - began > opts.history_seconds: return # the next look goes on from here hi = min(a + CHUNK - 1, hist.top) msgs = await fetch_messages(client, peer, list(range(a, hi + 1))) now = utcnow() stop = None todo = [] # posts the bot has saved already are none of the reading's business: the comparison of the saved posts looks # after them (and counts the ones Telegram holds back there - not a second time here) have = {p.message_id for p in await db.posts_at(ch.id, [m.id for m in msgs if not is_gone(m)])} for m in msgs: if is_gone(m) or isinstance(m, types.MessageService): continue if age(m.date, now) < opts.grace: # the bot may still be saving it: the next look reads it stop = m.id break if m.id in forgotten or m.id in have or (ch.id, m.id) in opts.ignore: continue why = message_restriction(m) if why: hold_back(rep, [m.id], why) elif not message_supported(m): rep.history_unsupported += 1 else: todo.append(m) made = await db.adopt_many(ch.id, [(m.id, adopt_fields(m), m.date) for m in todo]) # (skips what is saved) rep.imported += len(made) a = hi + 1 if stop is None else stop rep.history_done = stop is None and a > hist.top await db.save_history(ch.id, next_id=a, imported=len(made), done=rep.history_done) rep.history_to = rep.scanned_to = a - 1 if stop is not None: return if progress: await progress(rep) await asyncio.sleep(opts.pause) rep.history_done = True # (also the case when the channel had nothing to read)
# ----------------------------------------------------------------------------------------- entry pointsasync def sync_channel(client, db, ch, opts: Optional[SyncOptions] = None, *, busy=None, progress=None) -> SyncReport: """One full look at a channel (see the module text). Never raises Telegram's refusals: they end up in `report.error`.""" opts = opts or SyncOptions() busy = busy or (lambda: False) rep = SyncReport(channel=ch) pts, restricted, err = await probe_channel(client, peer_of(ch)) if pts is None: rep.error = err return rep if restricted: # Telegram restricted the channel (a copyright strike ...): My posts stay untouched rep.restricted_channel = restricted return rep try: state = await db.get_sync(ch.id) moved = None if state is None else max(0, pts - state.last_pts) await _compare_saved(client, db, ch, rep, opts, busy, progress, moved, pts) if not rep.busy: await _look_for_new(client, db, ch, rep, opts, state, pts, busy, progress) if not rep.busy and opts.history: await _import_history(client, db, ch, rep, opts, busy, progress, state) except errors.RPCError as e: rep.error = explain_rpc(e) return rep
async def sync_ids(client, db, ch, ids, opts: Optional[SyncOptions] = None, *, adopt_ids=(), busy=None) -> SyncReport: """A look at these messages only - the ones an update told about. `adopt_ids`: the ones that are new posts, so a message the bot does not know may be saved (an edited message the bot does not know is history: left alone).""" opts = opts or SyncOptions() busy = busy or (lambda: False) rep = SyncReport(channel=ch) peer = peer_of(ch) ids = sorted(set(ids)) adopt_set = set(adopt_ids) try: rows = {p.message_id: p for p in await db.posts_at(ch.id, ids)} # saved copies first, the channel second now = utcnow() gone, edits, fresh, services = [], [], [], [] for i in range(0, len(ids), CHUNK): if busy(): rep.busy = True return rep chunk = ids[i : i + CHUNK] msgs = await fetch_messages(client, peer, chunk) for mid, m in zip(chunk, msgs): row = rows.get(mid) recent = row is not None and min(age(row.updated_at, now), age(row.sent_at, now)) < opts.grace if is_gone(m): if row is not None and not recent: gone.append(row) elif isinstance(m, types.MessageService): services.append(mid) elif row is not None: why = message_restriction(m, row.text) if why: # Telegram's doing, not an admin's: the saved copy stays exactly as it is hold_back(rep, [mid], why) continue if recent: rep.young.append(mid) continue d = diff_post(row, m) if d.buttons_missing: rep.buttons_missing.append(mid) if d.fields: edits.append((row, d)) elif mid in adopt_set: fresh.append(m) if opts.delete_services and services: await delete_services(client, peer, services, rep) edits, held = split_mass_text(edits) if held: hold_back(rep, [p.message_id for p, _ in held], MASS_NOTE) if gone: gone_ids = [p.message_id for p in gone] await db.forget_posts(ch.id, gone_ids) rep.deleted.extend(gone_ids) await _save_edits(db, rep, edits, busy) if opts.adopt and fresh and not rep.busy: await _adopt(db, ch, rep, fresh, opts, busy, now) except errors.RPCError as e: rep.error = explain_rpc(e) return rep123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319"""The background side of the sync.
* a timer: every SYNC_INTERVAL_MINUTES each connected channel is compared with My posts (app/sync_engine.py);* a queue for what Telegram tells the bot while it runs: a post deleted / edited / added in a channel is looked at a few seconds later (the wait lets a burst of changes settle, and lets the bot finish saving its own posts first);* service messages ("pinned a message", "channel photo changed" ...) are deleted the moment they appear.
Nothing here holds the bot's one-long-job lock: a running /repost, /shift, /swap ... always wins, and what happenswhile it runs is picked up by the next timed check."""from __future__ import annotations
import asyncioimport loggingimport timefrom typing import Optional
from .servicemsg import RIGHTS_ERRORS, action_label, removefrom .sync_engine import SyncOptions, SyncReport, sync_channel, sync_idsfrom .tgutil import esc, peer_of
log = logging.getLogger(__name__)
class Syncer: def __init__(self, ctx): self.ctx = ctx # timings (seconds) - the tests make them small self.start_delay = 90.0 # after the bot starts, before the first timed check self.debounce = 5.0 # quiet time needed before the queue is worked off self.max_debounce = 30.0 # ... but never wait longer than this self.lock_wait = 30.0 # a long job runs: look again after this self.rt_grace = 10.0 # live changes: posts the bot touched / messages younger than this are judged next round self.pause = 0.25 # between two requests self.cache_ttl = 60.0 # how long "is this channel connected?" is remembered self.tell_every = 86400.0 # the same warning goes to the owners at most this often self.tell_restricted_every = 7 * 86400.0 # ... a restriction by Telegram can last for weeks: once a week self.max_ids = 300 # more changed ids than this in one channel: look at the whole channel instead self.max_tries = 8 # a message that stays "too fresh" is given up after this many rounds self.history_seconds = 150.0 # a timed check reads a channel's older posts for this long, then goes on next time self._busy = asyncio.Lock() # one look at a time self._edits: dict = {} # channel id -> message ids edited self._news: dict = {} # channel id -> message ids that are new posts self._tries: dict = {} self._stamp = 0 self._wake = asyncio.Event() self._tasks: list = [] self._cache: dict = {} self._told: dict = {} self.last_reports: dict = {} # channel id -> its latest SyncReport
# ----------------------------------------------------------------------------------------- running @property def enabled(self) -> bool: return self.ctx.cfg.sync_interval_minutes > 0
def start(self) -> None: if self._tasks or not self.enabled: return self._tasks = [ asyncio.create_task(self._periodic(), name="sync-timer"), asyncio.create_task(self._events(), name="sync-live"), ]
async def stop(self) -> None: tasks, self._tasks = self._tasks, [] for t in tasks: t.cancel() for t in tasks: try: await t except (asyncio.CancelledError, Exception): pass
async def _periodic(self) -> None: await asyncio.sleep(self.start_delay) while True: try: await self.run_all() except asyncio.CancelledError: raise except Exception: log.exception("the timed check of the channels failed") await asyncio.sleep(max(5, self.ctx.cfg.sync_interval_minutes) * 60)
async def _events(self) -> None: while True: await self._wake.wait() self._wake.clear() try: await self.flush_events() except asyncio.CancelledError: raise except Exception: log.exception("working off the channel changes failed")
# ----------------------------------------------------------------------------------------- helpers async def channel(self, cid: int): """The connected channel with this id, or None (remembered for a minute: busy channels cost no database reads).""" now = time.monotonic() hit = self._cache.get(cid) if hit is not None and now - hit[0] < self.cache_ttl: return hit[1] ch = await self.ctx.db.get_channel(cid) if ch is not None and not ch.active: ch = None self._cache[cid] = (now, ch) return ch
def forget_cache(self) -> None: self._cache.clear()
def exclusive(self): """Held (`async with`) while no look at any channel runs - for a change that must not race with one.""" return self._busy
def options(self, **kw) -> SyncOptions: ctx = self.ctx base = dict( delete_services=ctx.cfg.delete_service_messages, history=ctx.cfg.import_old_posts, ignore=ctx.sync_ignore, pause=self.pause, ) base.update(kw) return SyncOptions(**base)
async def tell_owners(self, ch, key: str, text: str, every: Optional[float] = None) -> None: """A warning for the owners - the same one (per channel and kind) at most once a day (or every `every` seconds).""" now = time.monotonic() k = (ch.id, key) if now - self._told.get(k, -1e12) < (self.tell_every if every is None else every): return self._told[k] = now for uid in sorted(self.ctx.cfg.owners): try: await self.ctx.client.send_message(uid, text, link_preview=False) except Exception: log.warning("could not warn user %s about %s", uid, ch.id, exc_info=True)
async def _after(self, ch, rep: SyncReport) -> None: self.last_reports[ch.id] = rep if rep.changed or rep.error or rep.anomaly: log.info( "channel %s: %s removed, %s updated, %s new, %s service messages deleted%s", ch.id, len(rep.deleted), len(rep.edited), len(rep.adopted), rep.services_deleted, f" - {rep.error or rep.anomaly}" if (rep.error or rep.anomaly) else "", ) if rep.services_failed and rep.services_error in RIGHTS_ERRORS: await self.tell_owners(ch, "rights", self._rights_text(ch, rep.services_error)) if rep.restricted_channel: log.info("channel %s is restricted by Telegram (%s): My posts left untouched", ch.id, rep.restricted_channel) text = self._restricted_text(ch, rep.restricted_channel) await self.tell_owners(ch, "restricted", text, every=self.tell_restricted_every) elif rep.restricted: log.info("channel %s: %s post(s) held back by Telegram (%s): left untouched", ch.id, len(rep.restricted), rep.restricted_why) text = self._held_back_text(ch, len(rep.restricted), rep.restricted_why) await self.tell_owners(ch, "held-back", text, every=self.tell_restricted_every)
@staticmethod def _restricted_text(ch, why: str) -> str: return ( f"π« Telegram has restricted <b>{esc(ch.title)}</b> ({esc(why)}). While that lasts I don't change anything in " "My posts for this channel - the saved posts stay exactly as they are, whatever the channel shows now." )
@staticmethod def _held_back_text(ch, n: int, why: Optional[str]) -> str: return ( f"π« Telegram holds back {n} post(s) of <b>{esc(ch.title)}</b> ({esc(why or 'restricted')}). " "Their saved copies in My posts stay exactly as they are." )
@staticmethod def _rights_text(ch, why: Optional[str]) -> str: return ( f"β οΈ I can't delete the service messages (name changes, βpinned a messageβ ...) in <b>{esc(ch.title)}</b> " f"({esc(why or 'refused')}). Give the bot the <i>Delete messages</i> right there, or set " "DELETE_SERVICE_MESSAGES=false to stop trying." )
# ------------------------------------------------------------------------------------ full looks async def run_all( self, chans: Optional[list] = None, *, explicit: bool = False, history: Optional[bool] = None, progress=None ) -> list: """Look at the connected channels one after the other. `explicit` (the /sync command): the caller holds the one-long-job lock and everything is read; the timed check gives way to any long job instead. `history`: True reads the channels' older posts even if IMPORT_OLD_POSTS is off (/sync --history).""" ctx = self.ctx if chans is None: chans = await ctx.db.list_channels() busy = (lambda: False) if explicit else ctx.lock.locked reports: list = [] for ch in chans: if busy(): break
async def prog(rep, ch=ch): if progress is not None: await progress(ch, rep)
try: async with self._busy: extra = {} if history is None else {"history": history} opts = self.options(deep=explicit, history_seconds=None if explicit else self.history_seconds, **extra) rep = await sync_channel(ctx.client, ctx.db, ch, opts, busy=busy, progress=prog) except asyncio.CancelledError: raise except Exception as e: log.exception("looking at channel %s failed", ch.id) rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}") await self._after(ch, rep) reports.append(rep) return reports
# ----------------------------------------------------------------------------- live: what updates say def _touch(self) -> None: self._stamp += 1 self._wake.set()
def note_new(self, cid: int, msg) -> None: """A post appeared in a channel. The bot's own posts are skipped (it saves them itself).""" if not self.enabled or self.ctx.lock.locked() or getattr(msg, "out", False): return self._news.setdefault(cid, set()).add(msg.id) self._touch()
def note_edit(self, cid: int, msg) -> None: if not self.enabled or self.ctx.lock.locked(): return self._edits.setdefault(cid, set()).add(msg.id) self._touch()
async def note_deleted(self, cid: int, ids) -> None: """Posts were deleted in a channel: they leave My posts at once (nothing to read from Telegram for that).""" if not self.enabled: return ch = await self.channel(cid) if ch is None: return for pending in (self._edits, self._news): if cid in pending: pending[cid].difference_update(ids) n = await self.ctx.db.forget_posts(cid, list(ids)) if n: log.info("%s post(s) were deleted in channel %s: removed from My posts", n, cid)
async def on_service(self, cid: int, msg) -> None: """A service message appeared: delete it.""" if not self.ctx.cfg.delete_service_messages: return ch = await self.channel(cid) if ch is None: return out = await remove(self.ctx.client, peer_of(ch), [msg.id]) if out.error is None: log.info("removed the β%sβ notice %s from channel %s", action_label(msg), msg.id, cid) return log.warning("could not delete the β%sβ notice %s in channel %s: %s", action_label(msg), msg.id, cid, out.error_name) if out.error_name in RIGHTS_ERRORS: await self.tell_owners(ch, "rights", self._rights_text(ch, out.error_name))
def _pending(self) -> bool: return bool(self._edits or self._news)
async def flush_events(self) -> None: """Work off the queue once it has been quiet for a moment (and no long job is running).""" first = time.monotonic() while self._pending(): stamp = self._stamp await asyncio.sleep(self.debounce) if stamp != self._stamp and time.monotonic() - first < self.max_debounce: continue # more is still coming in: let it settle if self.ctx.lock.locked(): await asyncio.sleep(self.lock_wait) continue edits, news = self._edits, self._news self._edits, self._news = {}, {} await self._process(edits, news) first = time.monotonic()
def _requeue(self, pending: dict, cid: int, mid: int) -> None: key = (cid, mid) self._tries[key] = self._tries.get(key, 0) + 1 if self._tries[key] > self.max_tries: self._tries.pop(key, None) return pending.setdefault(cid, set()).add(mid)
async def _process(self, edits: dict, news: dict) -> None: ctx = self.ctx for cid in sorted(set(edits) | set(news)): ch = await self.channel(cid) if ch is None: continue e_ids, n_ids = set(edits.get(cid, ())), set(news.get(cid, ())) opts = self.options(grace=self.rt_grace, history=False) # live: the older posts wait for the timed check try: async with self._busy: if len(e_ids | n_ids) > self.max_ids: # a burst: one look at the whole channel is cheaper rep = await sync_channel(ctx.client, ctx.db, ch, opts, busy=ctx.lock.locked) else: rep = await sync_ids( ctx.client, ctx.db, ch, e_ids | n_ids, opts, adopt_ids=n_ids, busy=ctx.lock.locked ) except asyncio.CancelledError: raise except Exception as e: log.exception("looking at the changes in channel %s failed", cid) rep = SyncReport(channel=ch, error=f"{type(e).__name__}: {str(e)[:120]}") await self._after(ch, rep) if rep.busy: # a long job started in the meantime: let the next timed check have it continue for mid in set(rep.young): self._requeue(self._edits, cid, mid) for mid in set(rep.young_new): self._requeue(self._news, cid, mid) for mid in (e_ids | n_ids) - set(rep.young) - set(rep.young_new): self._tries.pop((cid, mid), None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482"""Helpers around Telethon types: entity/button (de)serialisation, media info, raw edits, rights."""from __future__ import annotations
import asyncioimport base64import copyimport htmlimport loggingimport osfrom dataclasses import dataclass, fieldfrom types import SimpleNamespacefrom typing import Any, Awaitable, Callable, Optional
from telethon import errors, functions, typesfrom telethon.extensions import BinaryReader
log = logging.getLogger(__name__)esc = html.escape
# Telegram refusals that do not go away with the next message: the bot has no access (or no right) in that channelFATAL = { "ChatAdminRequiredError", "ChatWriteForbiddenError", "ChannelPrivateError", "UserBannedInChannelError", "ChannelInvalidError", "ChatRestrictedError",}
# ----------------------------------------------------------------------------- entities_SIMPLE = { "bold": types.MessageEntityBold, "italic": types.MessageEntityItalic, "underline": types.MessageEntityUnderline, "strike": types.MessageEntityStrike, "code": types.MessageEntityCode,}if hasattr(types, "MessageEntitySpoiler"): _SIMPLE["spoiler"] = types.MessageEntitySpoiler
# entities Telegram works out by itself from the text - never stored_AUTO = tuple( getattr(types, n) for n in ( "MessageEntityUrl", "MessageEntityMention", "MessageEntityHashtag", "MessageEntityCashtag", "MessageEntityBotCommand", "MessageEntityEmail", "MessageEntityPhone", "MessageEntityBankCard", ) if hasattr(types, n))
def _b64(obj: Any) -> str: return base64.b64encode(bytes(obj)).decode()
def _unb64(data: str) -> Any: return BinaryReader(base64.b64decode(data)).tgread_object()
def ser_entities(entities) -> list: """Message entities -> JSON-friendly list (UTF-16 offsets, as Telegram uses).""" out: list = [] for e in entities or []: if isinstance(e, _AUTO): continue done = False for key, cls in _SIMPLE.items(): if isinstance(e, cls): out.append({"k": key, "o": e.offset, "l": e.length}) done = True break if done: continue if isinstance(e, types.MessageEntityPre): out.append({"k": "pre", "o": e.offset, "l": e.length, "g": e.language or ""}) elif isinstance(e, types.MessageEntityTextUrl): out.append({"k": "url", "o": e.offset, "l": e.length, "u": e.url}) elif isinstance(e, types.MessageEntityBlockquote): out.append({"k": "quote", "o": e.offset, "l": e.length, "c": bool(getattr(e, "collapsed", False))}) elif isinstance(e, types.MessageEntityCustomEmoji): out.append({"k": "emoji", "o": e.offset, "l": e.length, "d": e.document_id}) else: try: # anything else is kept byte-for-byte out.append({"k": "raw", "b": _b64(e)}) except Exception: # pragma: no cover log.warning("cannot store entity %r", e) return out
def de_entities(data) -> list: out: list = [] for d in data or []: k = d.get("k") try: if k in _SIMPLE: out.append(_SIMPLE[k](d["o"], d["l"])) elif k == "pre": out.append(types.MessageEntityPre(d["o"], d["l"], d.get("g", ""))) elif k == "url": out.append(types.MessageEntityTextUrl(d["o"], d["l"], d["u"])) elif k == "quote": out.append(types.MessageEntityBlockquote(d["o"], d["l"], True if d.get("c") else None)) elif k == "emoji": out.append(types.MessageEntityCustomEmoji(d["o"], d["l"], d["d"])) elif k == "raw": out.append(_unb64(d["b"])) except Exception: # pragma: no cover log.warning("bad stored entity %r", d) return out
# ------------------------------------------------------------------------------ buttons_LEGACY = hasattr(types, "KeyboardButtonUrl") # Telethon < 1.45 used one class per button kind
def button_url(b) -> Optional[str]: """The link of a URL button, else None.""" if _LEGACY: return b.url if isinstance(b, types.KeyboardButtonUrl) else None t = getattr(b, "type", None) return t.url if isinstance(t, types.InlineButtonTypeUrl) else None
def is_callback_button(b) -> bool: if _LEGACY: return isinstance(b, types.KeyboardButtonCallback) return isinstance(getattr(b, "type", None), types.InlineButtonTypeCallback)
def make_url_button(text: str, url: str, style=None): if _LEGACY: return types.KeyboardButtonUrl(text, url) return types.KeyboardButton(text=text, type=types.InlineButtonTypeUrl(url), style=style)
def with_url(b, new_url: str): """Copy of URL button `b` pointing to `new_url`; every other attribute (colour, ...) is kept.""" nb = copy.copy(b) if _LEGACY: nb.url = new_url else: nb.type = copy.copy(b.type) nb.type.url = new_url return nb
def with_text(b, new_text: str): """Copy of button `b` with another name; the link, colour ... are kept.""" nb = copy.copy(b) nb.text = new_text return nb
def _style_dump(b) -> Optional[str]: st = getattr(b, "style", None) if st is None: return None if not any(getattr(st, f, None) for f in ("bg_primary", "bg_danger", "bg_success", "icon")): return None try: return _b64(st) except Exception: # pragma: no cover return None
def ser_markup(markup) -> list: """Inline keyboard -> rows of {'t': text, 'u': url} (URL buttons) or {'t', 'raw'} (any other kind).""" rows: list = [] if isinstance(markup, types.ReplyInlineMarkup): for row in markup.rows: r = [] for b in row.buttons: url = button_url(b) if url is not None: item = {"t": b.text, "u": url} s = _style_dump(b) if s: item["s"] = s r.append(item) else: try: r.append({"t": getattr(b, "text", ""), "raw": _b64(b)}) except Exception: # pragma: no cover log.warning("cannot store button %r", b) if r: rows.append(r) return rows
def build_markup(rows) -> Optional[types.ReplyInlineMarkup]: out = [] for row in rows or []: btns = [] for b in row: if b.get("raw"): try: btns.append(_unb64(b["raw"])) except Exception: # pragma: no cover continue elif b.get("u"): style = None if b.get("s"): try: style = _unb64(b["s"]) except Exception: # pragma: no cover style = None btns.append(make_url_button(b["t"], b["u"], style)) if btns: out.append(types.KeyboardButtonRow(btns)) return types.ReplyInlineMarkup(out) if out else None
def state_of(text, entities, markup, preview) -> dict: """Snapshot used for the undo log.""" return { "text": text or "", "entities": ser_entities(entities), "buttons": ser_markup(markup), "preview": preview, # True/False for text messages, None for media messages }
# --------------------------------------------------------------------------------- mediadef classify_media(m) -> Optional[str]: """photo | video | animation | audio | document, or None (text / unsupported).""" media = getattr(m, "media", None) if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None): return "photo" if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None): if m.gif: return "animation" if m.video: return "video" if m.audio: return "audio" if m.voice or m.video_note or m.sticker: return None return "document" return None
# Media is stored as the serialised Telegram media object ("tl:<base64>"). Telethon's Bot-API style# file_id helper cannot pack photos with the current Telegram schema, so we don't rely on it._REF_PREFIX = "tl:"
def media_ref(m) -> Optional[str]: """A storable reference to the photo / document attached to message `m` (None if it has none).""" media = getattr(m, "media", None) if isinstance(media, (types.MessageMediaPhoto, types.MessageMediaDocument)): try: return _REF_PREFIX + _b64(media) except Exception: # pragma: no cover log.warning("cannot store media reference", exc_info=True) return None
pack_file_id = media_ref # older name, kept for the callers
def media_from_ref(ref: str, *, blank_reference: bool = False): """Rebuild the media object; `blank_reference` drops the (possibly expired) file reference.""" media = _unb64(ref[len(_REF_PREFIX):]) if ref.startswith(_REF_PREFIX) else None if media is None: raise ValueError("unknown media reference") if blank_reference: media = copy.copy(media) inner = copy.copy(media.photo if isinstance(media, types.MessageMediaPhoto) else media.document) inner.file_reference = b"" if isinstance(media, types.MessageMediaPhoto): media.photo = inner else: media.document = inner return media
async def with_media(ref: str, call): """call(media): first with the stored file reference, then (if Telegram says it expired) without it.""" try: return await call(media_from_ref(ref)) except errors.RPCError as e: if "FileReference" not in type(e).__name__ and type(e).__name__ != "MediaEmptyError": raise log.info("stored file reference rejected (%s) - retrying without it", type(e).__name__) return await call(media_from_ref(ref, blank_reference=True))
def media_info(m) -> tuple: kind = classify_media(m) return kind, (media_ref(m) if kind else None)
def media_key(media) -> Optional[tuple]: """("photo" | "doc", id) of the photo / file in a message's media; the id is the same on every account.""" if isinstance(media, types.MessageMediaPhoto) and getattr(media, "photo", None): return "photo", media.photo.id if isinstance(media, types.MessageMediaDocument) and getattr(media, "document", None): return "doc", media.document.id return None
@dataclassclass MediaFile: """A photo or file downloaded from Telegram, with what is needed to upload it again as the same kind of post."""
path: str kind: str # photo | video | animation | audio | document name: str mime_type: Optional[str] = None attributes: list = field(default_factory=list) # the file's name, video size and length, GIF mark ... as it had them thumb_path: Optional[str] = None # the picture Telegram shows for the file (JPEG); None: it has none
async def fetch_media(client, ref: str, kind: str, folder: str) -> MediaFile: """Download the photo / file behind the stored media reference `ref` (as `client` sees it) into `folder`.
A file's thumbnail comes along: without it the file would be uploaded again with a plain file icon.""" path = await with_media(ref, lambda media: client.download_media(media, file=folder + os.sep)) if not path: raise ValueError("Telegram gave me nothing to download for that media") doc = getattr(media_from_ref(ref), "document", None) return MediaFile( path=str(path), kind=kind, name=os.path.basename(str(path)), mime_type=getattr(doc, "mime_type", None), attributes=list(getattr(doc, "attributes", None) or []), thumb_path=await fetch_thumb(client, ref, folder) if doc is not None else None, )
async def fetch_thumb(client, ref: str, folder: str) -> Optional[str]: """The thumbnail of the file behind `ref` (the largest one Telegram has) as a JPEG in `folder`, or None.
Best effort: a file that goes out without its thumbnail is better than an edit that fails.""" where = os.path.join(folder, "thumb") try: os.makedirs(where, exist_ok=True) path = await with_media(ref, lambda media: client.download_media(media, file=where + os.sep, thumb=-1)) except (errors.RPCError, OSError, ValueError, TypeError) as e: log.info("could not download the thumbnail: %s", type(e).__name__) return None return str(path) if path and os.path.isfile(str(path)) else None
def utf16_len(s: str) -> int: return len(s.encode("utf-16-le")) // 2
# --------------------------------------------------------------------------------- miscdef peer_of(ch) -> types.InputPeerChannel: return types.InputPeerChannel(ch.id, ch.access_hash)
def post_link(ch, message_id: int) -> str: if ch.username: return f"https://t.me/{ch.username}/{message_id}" return f"https://t.me/c/{ch.id}/{message_id}"
def short(s: str, n: int) -> str: s = " ".join((s or "").split()) return s if len(s) <= n else s[: n - 1] + "β¦"
async def flood_retry(factory: Callable[[], Awaitable[Any]], tries: int = 4) -> Any: for _ in range(tries): try: return await factory() except errors.FloodWaitError as e: wait = int(getattr(e, "seconds", 5)) + 1 log.warning("flood wait %ss", wait) await asyncio.sleep(min(wait, 900)) return await factory()
async def edit_raw( client, peer, message_id: int, *, text: Optional[str] = None, entities=None, markup=None, preview=None, media=None, rich_message=None,): """messages.editMessage with every field explicit.
`markup=None` together with `text` (or `rich_message`) removes the keyboard (that is how Telegram behaves); a markup-only edit (text=None) leaves the text alone. `media` (an InputMedia) replaces the photo / file. `rich_message` (an InputRichMessage*) makes the message that rich message instead of text. """ kw: dict = {"peer": peer, "id": message_id} if markup is not None: kw["reply_markup"] = markup if media is not None: kw["media"] = media if rich_message is not None: kw["rich_message"] = rich_message elif text is not None: kw["message"] = text kw["entities"] = list(entities or []) if preview is not None: kw["no_webpage"] = not preview return await client(functions.messages.EditMessageRequest(**kw))
async def get_rights(client, ch): """The bot's own admin rights in a channel, or None if Telegram won't tell us.""" try: res = await client( functions.channels.GetParticipantRequest(channel=peer_of(ch), participant=types.InputPeerSelf()) ) except Exception as e: log.info("could not read own rights in %s: %s", ch.id, e) return None p = res.participant if isinstance(p, (types.ChannelParticipantCreator, types.ChannelParticipantAdmin)): r = getattr(p, "admin_rights", None) creator = isinstance(p, types.ChannelParticipantCreator)
def has(name: str) -> bool: return True if (creator and r is None) else bool(getattr(r, name, False))
return SimpleNamespace( admin=True, post=has("post_messages"), edit=has("edit_messages"), delete=has("delete_messages"), invite=has("invite_users"), add_admins=has("add_admins"), change_info=has("change_info"), ) return SimpleNamespace( admin=False, post=False, edit=False, delete=False, invite=False, add_admins=False, change_info=False )
_HINTS = { "ChatAdminRequiredError": "The bot needs admin rights in that channel (post / edit / delete messages).", "MessageAuthorRequiredError": "Telegram wants the message author. Give the bot the 'Edit messages of others' right.", "InlineBotRequiredError": "That post was sent through another bot's inline mode, so only that bot can edit it.", "MessageEditTimeExpiredError": "Telegram no longer allows editing that message.", "MessageIdInvalidError": ( "Telegram won't let the bot change that message (or it was deleted). If the post is still there, " "the usual reason is that its buttons were added by another bot: only that bot may change them." ), "ButtonUrlInvalidError": "Telegram rejected one of the button links.", "ReplyMarkupInvalidError": "Telegram rejected the buttons.", "ChatWriteForbiddenError": "The bot can't post in that channel - check its admin rights.", "ChannelPrivateError": "The bot can't access that channel any more (removed or banned?).", "UserBannedInChannelError": "The bot is banned in that channel.", "FileReferenceExpiredError": "The saved media expired - send the media again.", "MediaEmptyError": "Telegram could not use that media - send it again.", "EntityBoundsInvalidError": "The text formatting doesn't fit the text.", "EntitiesTooLongError": "The text has too many formatted pieces (bold, links ...) for Telegram - use less formatting.", "MessageTooLongError": "The text is too long for Telegram.", "MediaCaptionTooLongError": "The caption is too long for Telegram.",}
# Telegram's own error codes (the name of the Python class is only "BadRequestError" for the ones Telethon doesn't know)_CODE_HINTS = { "RICH_MESSAGE_BLOCK_INVALID": "Telegram would not take one of the blocks of that rich message.",}
def explain_rpc(e: BaseException) -> str: name = type(e).__name__ code = getattr(e, "message", None) or "" hint = _HINTS.get(name) if hint is None and code in _CODE_HINTS: hint = f"{_CODE_HINTS[code]} ({code})" return f"Telegram refused ({name}). " + (hint if hint is not None else str(e)[:200])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114"""Texts and inline keyboards for the post panel."""from __future__ import annotations
from telethon import Button
from .buttons import count, grid_label, link_positions, missing_linksfrom .richmsg import rich_offrom .tgutil import esc, post_link, short
CANCEL = [[Button.inline("βοΈ Cancel", "cx")]]KIND_ICON = {None: "π", "photo": "πΌ", "video": "π¬", "animation": "π", "audio": "π΅", "document": "π"}KIND_NAME = {None: "text", "photo": "photo", "video": "video", "animation": "GIF", "audio": "audio", "document": "file"}
def post_title(p) -> str: for row in p.buttons or []: for b in row: if b.get("t"): return b["t"] text = (p.text or "").strip() return text.splitlines()[0] if text else (KIND_NAME.get(p.media_kind) or "post")
def post_label(p) -> str: icon = "π" if p.status == "draft" else "β
" return f"{icon} #{p.id} {short(post_title(p), 34)}"
def panel_text(p, ch, note=None) -> str: state = "draft (not published yet)" if p.status == "draft" else "published" lines = [f"<b>Post #{p.id}</b> Β· {state}", f"Channel: <b>{esc(ch.title)}</b>"] if p.status == "sent" and p.message_id: lines.append(f'<a href="{post_link(ch, p.message_id)}">Open in the channel</a>') rich = rich_of(p) if rich is not None: origin = {"html": "typed as HTML", "markdown": "typed as Markdown"}.get(rich.fmt, "made in Telegram") lines.append(f"Type: π§© rich message ({origin})") else: lines.append(f"Type: {KIND_ICON.get(p.media_kind, 'π')} {KIND_NAME.get(p.media_kind, p.media_kind)}") n, miss = count(p.buttons), missing_links(p.buttons) lines.append(f"Buttons: {n}" + (f" (β οΈ {miss} without a link)" if miss else "")) if p.source == "adopted": lines.append("<i>Picked up from the channel - it was not made with this bot.</i>") snippet = short(p.text or "", 220) or "(no text)" lines += ["", f"<i>{esc(snippet)}</i>"] if note: lines += ["", note] return "\n".join(lines)
def panel_keyboard(p) -> list: pid = p.id kb = [] for r, row in enumerate(p.buttons or []): kb.append([Button.inline(grid_label(b), f"bs:{pid}:{r}:{c}") for c, b in enumerate(row)]) rich = rich_of(p) is not None kb.append( [Button.inline("βοΈ Caption" if p.media_kind else "βοΈ Text", f"et:{pid}")] + ([] if rich else [Button.inline("πΌ Media", f"em:{pid}")]) # a rich message has no media slot ) row3 = [Button.inline("β Button", f"ba:{pid}"), Button.inline("π Set buttons", f"bp:{pid}")] if p.buttons: row3.append(Button.inline("π§Ή Clear", f"bc:{pid}")) kb.append(row3) extra = [] if not p.media_kind and not rich: extra.append(Button.inline(f"π Link preview: {'on' if p.link_preview else 'off'}", f"lp:{pid}")) if p.media_kind and p.status == "draft": extra.append(Button.inline("π« Remove media", f"rm:{pid}")) if extra: kb.append(extra) if p.status == "sent" and p.message_id and link_positions(p.buttons): kb.append([Button.inline("π Mass replace links", f"mlp:{pid}")]) if p.status == "draft": kb.append([Button.inline("π Preview", f"pv:{pid}"), Button.inline("π Publish", f"pb:{pid}")]) kb.append([Button.inline("π Discard", f"dl:{pid}"), Button.inline("π My posts", "pc:d:0")]) else: kb.append([Button.inline("π Preview", f"pv:{pid}"), Button.inline("π Delete", f"dl:{pid}")]) kb.append([Button.inline("π My posts", f"pc:{p.channel_id}:0")]) return kb
def button_text(p, r: int, c: int) -> str: b = p.buttons[r][c] if b.get("raw"): return ( f"π <b>Button from another bot</b> (row {r + 1}, position {c + 1})\n" f"Text: <code>{esc(b.get('t') or '')}</code>\n" "Buttons like reactions only work with the bot that made them, so you can move or delete it, " "but not edit it." ) return ( f"π <b>Button</b> (row {r + 1}, position {c + 1})\n" f"Text: <code>{esc(b.get('t') or '')}</code>\n" f"Link: <code>{esc(b.get('u') or '- none yet -')}</code>" )
def button_keyboard(p, r: int, c: int) -> list: pid, at = p.id, f"{p.id}:{r}:{c}" b = p.buttons[r][c] kb = [] if not b.get("raw"): kb.append([Button.inline("βοΈ Change text", f"bt:{at}"), Button.inline("π Change link", f"bu:{at}")]) kb.append( [ Button.inline("β¬
οΈ", f"bm:{at}:l"), Button.inline("β¬οΈ", f"bm:{at}:u"), Button.inline("β¬οΈ", f"bm:{at}:d"), Button.inline("β‘οΈ", f"bm:{at}:r"), ] ) kb.append([Button.inline("π Delete", f"bd:{at}"), Button.inline("π Back", f"po:{pid}")]) return kb.env.exampleAdded+25
.gitattributes+8-34
.gitignoreAdded+7
Dockerfile+6-15
app.pyDeleted-147
app/__init__.pyAdded
app/autopost.pyAdded+81
app/backup.pyAdded+337
app/buttons.pyAdded+150
app/buttons_sync.pyAdded+186
app/channelref.pyAdded+119
app/common.pyAdded+406
app/config.pyAdded+133
app/crosslinks.pyAdded+406
app/db.pyAdded+1067
app/errorlog.pyAdded+300
app/expiry.pyAdded+208
app/handlers/__init__.pyAdded
app/handlers/autopost.pyAdded+203
app/handlers/backup.pyAdded+173
app/handlers/basic.pyAdded+201
app/handlers/broadcast.pyAdded+268
app/handlers/channels.pyAdded+182
app/handlers/checkbtn.pyAdded+115
app/handlers/create.pyAdded+191
app/handlers/masslinks.pyAdded+159
app/handlers/panel.pyAdded+135
app/handlers/posts.pyAdded+534
app/handlers/replace.pyAdded+502
app/handlers/repost.pyAdded+820
app/handlers/shift.pyAdded+618
app/handlers/sync.pyAdded+223
app/handleswap.pyAdded+97
app/health.pyAdded+26
app/linkswap.pyAdded+236
app/picker.pyAdded+104
app/postlinks.pyAdded+226
app/profile_copy.pyAdded+170
app/replace_engine.pyAdded+343
app/repost_engine.pyAdded+1372
app/restrictions.pyAdded+77
app/richmsg.pyAdded+698
app/richtext.pyAdded+552
app/servicemsg.pyAdded+55
app/shift_engine.pyAdded+187
app/suggest.pyAdded+127
app/sync_engine.pyAdded+600
app/syncer.pyAdded+319
app/tgutil.pyAdded+482
app/ui.pyAdded+114