85 lines
3.3 KiB
Python
85 lines
3.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Удаление сообщений в Telegram-канале (уборка дублей после бага fix-double-publish).
|
|
|
|
Осторожно: операция НЕОБРАТИМА. По умолчанию только показывает, что будет удалено.
|
|
|
|
Примеры:
|
|
python3 scripts/delete-tg-messages.py --channel @dedinit_vesti --ids 107-114 --dry-run
|
|
python3 scripts/delete-tg-messages.py --channel @dedinit_vesti --ids 107-114 --yes
|
|
|
|
Требования: бот — администратор канала с правом удалять сообщения; удалять можно
|
|
сообщения не старше 48 часов (ограничение Bot API).
|
|
"""
|
|
import argparse
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
|
|
import httpx # noqa: E402
|
|
|
|
from services.publisher.app.config import settings # noqa: E402
|
|
|
|
|
|
def parse_ids(raw: str) -> list[int]:
|
|
"""'105-107,110' → [105, 106, 107, 110]."""
|
|
out: list[int] = []
|
|
for chunk in raw.split(","):
|
|
chunk = chunk.strip()
|
|
if not chunk:
|
|
continue
|
|
if "-" in chunk:
|
|
a, b = chunk.split("-", 1)
|
|
out.extend(range(int(a), int(b) + 1))
|
|
else:
|
|
out.append(int(chunk))
|
|
return out
|
|
|
|
|
|
def delete(channel: str, message_id: int) -> tuple[bool, str]:
|
|
if not settings.bot_token:
|
|
return False, "VESTI_BOT_TOKEN не задан"
|
|
url = f"{settings.api_base}/bot{settings.bot_token}/deleteMessage"
|
|
try:
|
|
with httpx.Client(proxy=settings.tg_proxy, timeout=20.0) as client:
|
|
resp = client.post(url, json={"chat_id": channel, "message_id": message_id})
|
|
except Exception as exc:
|
|
return False, f"сеть/прокси: {exc}"
|
|
if resp.status_code == 200 and resp.json().get("ok"):
|
|
return True, "удалено"
|
|
try:
|
|
return False, resp.json().get("description", resp.text[:120])
|
|
except Exception:
|
|
return False, resp.text[:120]
|
|
|
|
|
|
def main() -> int:
|
|
ap = argparse.ArgumentParser(description="Удалить сообщения в канале (уборка дублей)")
|
|
ap.add_argument("--channel", required=True, help="например @dedinit_vesti")
|
|
ap.add_argument("--ids", required=True, help="id сообщений: '105-114' или '105,106,108'")
|
|
ap.add_argument("--dry-run", action="store_true", help="только показать план (по умолчанию)")
|
|
ap.add_argument("--yes", action="store_true", help="действительно удалить")
|
|
args = ap.parse_args()
|
|
|
|
ids = parse_ids(args.ids)
|
|
if not ids:
|
|
print("нечего удалять: пустой список id")
|
|
return 2
|
|
if not args.yes:
|
|
print(f"[dry-run] канал {args.channel}, к удалению {len(ids)} сообщений: {ids}")
|
|
print("повторите с --yes, чтобы удалить по-настоящему")
|
|
return 0
|
|
|
|
ok = fail = 0
|
|
for mid in ids:
|
|
done, msg = delete(args.channel, mid)
|
|
print(f" {mid}: {'✅' if done else '⚠'} {msg}")
|
|
ok += done
|
|
fail += not done
|
|
print(f"итог: удалено {ok}, ошибок {fail}")
|
|
return 0 if fail == 0 else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|