Spaces:
Running
Running
github-actions[bot] commited on
Commit Β·
de05efa
1
Parent(s): 8d18810
Automated sync from GitHub
Browse files- app/dbpublish.py +204 -11
- tests/test_dbdelete.py +429 -0
- tests/test_dblink.py +60 -0
app/dbpublish.py
CHANGED
|
@@ -18,6 +18,11 @@ The message of the autorename bot (it writes the Channel and Episode lines from
|
|
| 18 |
so on) and the button name ("Download Episode {episode}"). The button opens the file link of the Share URL button.
|
| 19 |
It goes to the channel the message names - nothing is guessed from the file name.
|
| 20 |
4. "Post published successfully" - or "Publication failed: <why>" - goes back to the communication chat.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
"""
|
| 22 |
from __future__ import annotations
|
| 23 |
|
|
@@ -40,8 +45,9 @@ from .config import MIN_SHARE_URL_WAIT
|
|
| 40 |
from .db import utcnow
|
| 41 |
from .linkswap import apply_span_replacements
|
| 42 |
from .replace_engine import fetch_messages, get_top_id, is_skippable
|
|
|
|
| 43 |
from .tgutil import button_url, de_entities, explain_rpc, peer_of, post_link, ser_entities
|
| 44 |
-
from .userbot import UserbotError
|
| 45 |
|
| 46 |
log = logging.getLogger(__name__)
|
| 47 |
|
|
@@ -57,6 +63,8 @@ BUTTON_MAX = 60 # of the button name template
|
|
| 57 |
BUTTON_SHOWN = 64 # a button name is cut at this length when the post is made
|
| 58 |
|
| 59 |
_NOTICE_RX = re.compile(r"(?i)file\s+uploaded\s+to\s+the\s+database\s+channel")
|
|
|
|
|
|
|
| 60 |
_SHARE_RX = re.compile(r"(?i)\bshare\s*url\b")
|
| 61 |
_SHARE_LINK_RX = re.compile(r"(?i)^https?://(?:t\.me|telegram\.me|telegram\.dog)/share(?:/url)?\?(.*)$")
|
| 62 |
# {episode}, {episode number}, {episode_number}, {channel} (also {channel name}); spaces inside the braces do not matter
|
|
@@ -89,6 +97,12 @@ def chat_number(raw: Optional[str]) -> Optional[int]:
|
|
| 89 |
return int(m.group(1)) if m else None
|
| 90 |
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
def parse_notice(text: Optional[str]) -> Optional[Notice]:
|
| 93 |
"""The message the autorename bot writes ("File uploaded to the Database Channel", then Episode / Channel / File /
|
| 94 |
Post / Ref lines); None for anything else."""
|
|
@@ -96,8 +110,7 @@ def parse_notice(text: Optional[str]) -> Optional[Notice]:
|
|
| 96 |
return None
|
| 97 |
|
| 98 |
def field_of(label: str) -> str:
|
| 99 |
-
|
| 100 |
-
return m.group(1).strip() if m else ""
|
| 101 |
|
| 102 |
post = field_of("post")
|
| 103 |
channel_raw = field_of("channel")
|
|
@@ -111,7 +124,61 @@ def parse_notice(text: Optional[str]) -> Optional[Notice]:
|
|
| 111 |
)
|
| 112 |
|
| 113 |
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
return f"\nRef: {notice.ref}" if notice is not None and notice.ref else ""
|
| 116 |
|
| 117 |
|
|
@@ -134,6 +201,7 @@ class Published:
|
|
| 134 |
file: str
|
| 135 |
episode: str = ""
|
| 136 |
notes: list = field(default_factory=list)
|
|
|
|
| 137 |
|
| 138 |
|
| 139 |
def published_text(p: Published, notice: Optional[Notice] = None) -> str:
|
|
@@ -141,8 +209,10 @@ def published_text(p: Published, notice: Optional[Notice] = None) -> str:
|
|
| 141 |
"β
Post published successfully",
|
| 142 |
f"Channel: {p.channel.title}",
|
| 143 |
f"Post: {p.link}",
|
| 144 |
-
f"Button: {p.label} β {p.url}",
|
| 145 |
]
|
|
|
|
|
|
|
|
|
|
| 146 |
if p.episode:
|
| 147 |
lines.append(f"Episode: {p.episode}")
|
| 148 |
lines += [f"βΉοΈ {n}" for n in p.notes]
|
|
@@ -151,6 +221,31 @@ def published_text(p: Published, notice: Optional[Notice] = None) -> str:
|
|
| 151 |
return "\n".join(lines) + _tail(notice)
|
| 152 |
|
| 153 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
# ------------------------------------------------------------------------------------------------ chat ids, names
|
| 155 |
def channel_id_of(value: int) -> int:
|
| 156 |
"""The id the database keeps for a channel, from the id as Telegram apps write it (-100β¦); a bare id stays as it is."""
|
|
@@ -325,12 +420,21 @@ class AutoPublisher:
|
|
| 325 |
# --------------------------------------------------------------------------------------------- entry point
|
| 326 |
async def handle(self, event: Any) -> None:
|
| 327 |
"""A message of the autorename bot in the communication chat."""
|
| 328 |
-
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
| 330 |
return # something else it says, or the same notice again
|
| 331 |
self._handled[event.id] = None
|
| 332 |
while len(self._handled) > KEEP_NOTICES:
|
| 333 |
self._handled.popitem(last=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
await self._answer(event, received_text(notice))
|
| 335 |
async with self.lock:
|
| 336 |
try:
|
|
@@ -344,6 +448,44 @@ class AutoPublisher:
|
|
| 344 |
text = failed_text(f"something went wrong inside the bot ({type(e).__name__}: {str(e)[:150]})", notice)
|
| 345 |
await self._answer(event, text)
|
| 346 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
async def _answer(self, event: Any, text: str) -> None:
|
| 348 |
try:
|
| 349 |
await event.reply(text, parse_mode=None, link_preview=False)
|
|
@@ -384,23 +526,73 @@ class AutoPublisher:
|
|
| 384 |
done.notes.append("The Share URL button was read through the userbot.")
|
| 385 |
return done
|
| 386 |
|
| 387 |
-
async def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
"""The channel the message names: connected to this bot, switched on, and not the Database Channel itself."""
|
| 389 |
if notice.channel is None:
|
| 390 |
if notice.channel_raw:
|
| 391 |
raise Failure(f"The message names β{notice.channel_raw}β as the channel, which is not a channel id (like -1001234567890).")
|
|
|
|
|
|
|
| 392 |
raise Failure(
|
| 393 |
"The message does not say which channel to post in: it has no βChannel:β line "
|
| 394 |
"(the Channel option of the format the episode was renamed with)."
|
| 395 |
)
|
| 396 |
cid = channel_id_of(notice.channel)
|
| 397 |
if cid == channel_id_of(self.ctx.cfg.db_channel):
|
| 398 |
-
raise Failure(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
ch = await self.ctx.db.get_channel(cid)
|
| 400 |
if ch is None or not ch.active:
|
| 401 |
raise Failure(
|
| 402 |
f"The channel {notice.channel} is not connected to this bot (/channels lists the connected ones, /addchannel adds one), "
|
| 403 |
-
"so I cannot post there."
|
| 404 |
)
|
| 405 |
return ch
|
| 406 |
|
|
@@ -541,5 +733,6 @@ class AutoPublisher:
|
|
| 541 |
await db.release_slot(ch.id, sent.id, keep_pid=post.id) # the sync may have picked the message up a moment ago
|
| 542 |
await db.update_post(post.id, status="sent", message_id=sent.id, sent_at=utcnow())
|
| 543 |
return Published(
|
| 544 |
-
channel=ch, link=post_link(ch, sent.id), label=label, url=link, file=name or notice.file, episode=notice.episode
|
|
|
|
| 545 |
)
|
|
|
|
| 18 |
so on) and the button name ("Download Episode {episode}"). The button opens the file link of the Share URL button.
|
| 19 |
It goes to the channel the message names - nothing is guessed from the file name.
|
| 20 |
4. "Post published successfully" - or "Publication failed: <why>" - goes back to the communication chat.
|
| 21 |
+
|
| 22 |
+
Deleting: the "Delete post" button of the autorename bot writes "Delete the published post" in the communication chat
|
| 23 |
+
(Channel / Message / File / Ref lines: the channel and the message id of the post, as this bot reported them). This bot then
|
| 24 |
+
deletes that post in the channel - only one it published by itself - and in My posts, and answers "Post deleted successfully"
|
| 25 |
+
(also when the post was already gone) or "Deletion failed: <why>".
|
| 26 |
"""
|
| 27 |
from __future__ import annotations
|
| 28 |
|
|
|
|
| 45 |
from .db import utcnow
|
| 46 |
from .linkswap import apply_span_replacements
|
| 47 |
from .replace_engine import fetch_messages, get_top_id, is_skippable
|
| 48 |
+
from .repost_engine import delete_batch, gone_ids
|
| 49 |
from .tgutil import button_url, de_entities, explain_rpc, peer_of, post_link, ser_entities
|
| 50 |
+
from .userbot import UserbotError, delete_problem_text
|
| 51 |
|
| 52 |
log = logging.getLogger(__name__)
|
| 53 |
|
|
|
|
| 63 |
BUTTON_SHOWN = 64 # a button name is cut at this length when the post is made
|
| 64 |
|
| 65 |
_NOTICE_RX = re.compile(r"(?i)file\s+uploaded\s+to\s+the\s+database\s+channel")
|
| 66 |
+
_DELETE_RX = re.compile(r"(?i)\A\s*delete\s+the\s+published\s+post\b") # the first words of the message, not anywhere in it
|
| 67 |
+
_LINK_RX = re.compile(r"(?i)\A\s*get\s+the\s+share\s+url\b")
|
| 68 |
_SHARE_RX = re.compile(r"(?i)\bshare\s*url\b")
|
| 69 |
_SHARE_LINK_RX = re.compile(r"(?i)^https?://(?:t\.me|telegram\.me|telegram\.dog)/share(?:/url)?\?(.*)$")
|
| 70 |
# {episode}, {episode number}, {episode_number}, {channel} (also {channel name}); spaces inside the braces do not matter
|
|
|
|
| 97 |
return int(m.group(1)) if m else None
|
| 98 |
|
| 99 |
|
| 100 |
+
def _field(text: Optional[str], label: str) -> str:
|
| 101 |
+
"""The value of a ``Label: value`` line of a message; empty when there is no such line."""
|
| 102 |
+
m = re.search(rf"(?im)^\s*{label}\s*:\s*(.+?)\s*$", text or "")
|
| 103 |
+
return m.group(1).strip() if m else ""
|
| 104 |
+
|
| 105 |
+
|
| 106 |
def parse_notice(text: Optional[str]) -> Optional[Notice]:
|
| 107 |
"""The message the autorename bot writes ("File uploaded to the Database Channel", then Episode / Channel / File /
|
| 108 |
Post / Ref lines); None for anything else."""
|
|
|
|
| 110 |
return None
|
| 111 |
|
| 112 |
def field_of(label: str) -> str:
|
| 113 |
+
return _field(text, label)
|
|
|
|
| 114 |
|
| 115 |
post = field_of("post")
|
| 116 |
channel_raw = field_of("channel")
|
|
|
|
| 124 |
)
|
| 125 |
|
| 126 |
|
| 127 |
+
@dataclass
|
| 128 |
+
class DeleteNotice:
|
| 129 |
+
"""The autorename bot asking for a published post to be deleted."""
|
| 130 |
+
|
| 131 |
+
channel: Optional[int] = None # the channel the post is in, as written (-100β¦); None when the message names none
|
| 132 |
+
channel_raw: str = "" # what stood after "Channel:" (shown when it is not an id)
|
| 133 |
+
message_id: Optional[int] = None # the post, as a message of that channel (the "Message:" line of "Post published successfully")
|
| 134 |
+
file: str = ""
|
| 135 |
+
ref: str = "" # repeated in every answer, as in the notice of an upload
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def parse_delete_notice(text: Optional[str]) -> Optional[DeleteNotice]:
|
| 139 |
+
"""The message the autorename bot writes to have a post deleted ("Delete the published post", then Channel / Message /
|
| 140 |
+
File / Ref lines); None for anything else."""
|
| 141 |
+
if not _DELETE_RX.search(text or ""):
|
| 142 |
+
return None
|
| 143 |
+
channel_raw, message = _field(text, "channel"), _field(text, "message")
|
| 144 |
+
return DeleteNotice(
|
| 145 |
+
channel=chat_number(channel_raw),
|
| 146 |
+
channel_raw=channel_raw[:60],
|
| 147 |
+
message_id=int(message) if re.fullmatch(r"\d{1,12}", message) else None,
|
| 148 |
+
file=_field(text, "file"),
|
| 149 |
+
ref=_field(text, "ref")[:40],
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@dataclass
|
| 154 |
+
class LinkNotice:
|
| 155 |
+
"""The autorename bot asking only for the Share URL of a file in the Database Channel (nothing is published)."""
|
| 156 |
+
|
| 157 |
+
post_id: Optional[int] = None # the file in the Database Channel
|
| 158 |
+
ref: str = ""
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def parse_link_notice(text: Optional[str]) -> Optional[LinkNotice]:
|
| 162 |
+
""""Get the share URL", then Post / Ref lines; None for anything else."""
|
| 163 |
+
if not _LINK_RX.search(text or ""):
|
| 164 |
+
return None
|
| 165 |
+
post = _field(text, "post")
|
| 166 |
+
return LinkNotice(post_id=int(post) if re.fullmatch(r"\d{1,12}", post) else None, ref=_field(text, "ref")[:40])
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def link_received_text(notice: Optional[LinkNotice] = None) -> str:
|
| 170 |
+
return "π₯ Message received - looking for the Share URLβ¦" + _tail(notice)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def link_ready_text(url: str, notes: list, notice: Optional[LinkNotice] = None) -> str:
|
| 174 |
+
return "\n".join(["π Share URL ready", f"URL: {url}", *[f"βΉοΈ {n}" for n in notes]]) + _tail(notice)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def link_failed_text(reason: str, notice: Optional[LinkNotice] = None) -> str:
|
| 178 |
+
return f"β Share URL failed: {' '.join((reason or 'unknown reason').split())[:600]}" + _tail(notice)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _tail(notice: Any) -> str:
|
| 182 |
return f"\nRef: {notice.ref}" if notice is not None and notice.ref else ""
|
| 183 |
|
| 184 |
|
|
|
|
| 201 |
file: str
|
| 202 |
episode: str = ""
|
| 203 |
notes: list = field(default_factory=list)
|
| 204 |
+
message_id: int = 0 # the new post as a message of its channel (what a deletion names)
|
| 205 |
|
| 206 |
|
| 207 |
def published_text(p: Published, notice: Optional[Notice] = None) -> str:
|
|
|
|
| 209 |
"β
Post published successfully",
|
| 210 |
f"Channel: {p.channel.title}",
|
| 211 |
f"Post: {p.link}",
|
|
|
|
| 212 |
]
|
| 213 |
+
if p.message_id:
|
| 214 |
+
lines.append(f"Message: {p.message_id}")
|
| 215 |
+
lines.append(f"Button: {p.label} β {p.url}")
|
| 216 |
if p.episode:
|
| 217 |
lines.append(f"Episode: {p.episode}")
|
| 218 |
lines += [f"βΉοΈ {n}" for n in p.notes]
|
|
|
|
| 221 |
return "\n".join(lines) + _tail(notice)
|
| 222 |
|
| 223 |
|
| 224 |
+
@dataclass
|
| 225 |
+
class Deleted:
|
| 226 |
+
channel: Any
|
| 227 |
+
message_id: int
|
| 228 |
+
file: str = ""
|
| 229 |
+
notes: list = field(default_factory=list)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def delete_received_text(notice: Optional[DeleteNotice] = None) -> str:
|
| 233 |
+
return "π₯ Message received - deleting the postβ¦" + _tail(notice)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def deleted_text(d: Deleted, notice: Optional[DeleteNotice] = None) -> str:
|
| 237 |
+
lines = ["π Post deleted successfully", f"Channel: {d.channel.title}", f"Message: {d.message_id}"]
|
| 238 |
+
lines += [f"βΉοΈ {n}" for n in d.notes]
|
| 239 |
+
if d.file:
|
| 240 |
+
lines.append(f"File: {d.file}")
|
| 241 |
+
return "\n".join(lines) + _tail(notice)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def delete_failed_text(reason: str, notice: Optional[DeleteNotice] = None) -> str:
|
| 245 |
+
reason = " ".join((reason or "unknown reason").split())
|
| 246 |
+
return f"β Deletion failed: {reason[:600]}" + (f"\nFile: {notice.file}" if notice is not None and notice.file else "") + _tail(notice)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
# ------------------------------------------------------------------------------------------------ chat ids, names
|
| 250 |
def channel_id_of(value: int) -> int:
|
| 251 |
"""The id the database keeps for a channel, from the id as Telegram apps write it (-100β¦); a bare id stays as it is."""
|
|
|
|
| 420 |
# --------------------------------------------------------------------------------------------- entry point
|
| 421 |
async def handle(self, event: Any) -> None:
|
| 422 |
"""A message of the autorename bot in the communication chat."""
|
| 423 |
+
text = getattr(event, "raw_text", None)
|
| 424 |
+
notice = parse_notice(text)
|
| 425 |
+
removal = None if notice is not None else parse_delete_notice(text)
|
| 426 |
+
lookup = None if notice is not None or removal is not None else parse_link_notice(text)
|
| 427 |
+
if (notice is None and removal is None and lookup is None) or event.id in self._handled:
|
| 428 |
return # something else it says, or the same notice again
|
| 429 |
self._handled[event.id] = None
|
| 430 |
while len(self._handled) > KEEP_NOTICES:
|
| 431 |
self._handled.popitem(last=False)
|
| 432 |
+
if removal is not None:
|
| 433 |
+
await self._remove(event, removal)
|
| 434 |
+
return
|
| 435 |
+
if lookup is not None:
|
| 436 |
+
await self._lookup(event, lookup)
|
| 437 |
+
return
|
| 438 |
await self._answer(event, received_text(notice))
|
| 439 |
async with self.lock:
|
| 440 |
try:
|
|
|
|
| 448 |
text = failed_text(f"something went wrong inside the bot ({type(e).__name__}: {str(e)[:150]})", notice)
|
| 449 |
await self._answer(event, text)
|
| 450 |
|
| 451 |
+
async def _remove(self, event: Any, notice: DeleteNotice) -> None:
|
| 452 |
+
"""A request to delete a published post: "received", then "deleted" or why not."""
|
| 453 |
+
await self._answer(event, delete_received_text(notice))
|
| 454 |
+
async with self.lock:
|
| 455 |
+
try:
|
| 456 |
+
text = deleted_text(await self.delete(notice), notice)
|
| 457 |
+
except Failure as f:
|
| 458 |
+
log.info("automatic deletion: %s", f)
|
| 459 |
+
text = delete_failed_text(str(f), notice)
|
| 460 |
+
except Exception as e: # noqa: BLE001 - the autorename bot must always get an answer
|
| 461 |
+
log.exception("automatic deletion failed")
|
| 462 |
+
text = delete_failed_text(f"something went wrong inside the bot ({type(e).__name__}: {str(e)[:150]})", notice)
|
| 463 |
+
await self._answer(event, text)
|
| 464 |
+
|
| 465 |
+
async def _lookup(self, event: Any, notice: LinkNotice) -> None:
|
| 466 |
+
"""A request for the Share URL of a file in the Database Channel: "received", then the link or why not."""
|
| 467 |
+
await self._answer(event, link_received_text(notice))
|
| 468 |
+
async with self.lock:
|
| 469 |
+
try:
|
| 470 |
+
text = link_ready_text(*await self.share_link(notice), notice)
|
| 471 |
+
except Failure as f:
|
| 472 |
+
text = link_failed_text(str(f), notice)
|
| 473 |
+
except Exception as e: # noqa: BLE001 - the autorename bot must always get an answer
|
| 474 |
+
log.exception("looking for the share url failed")
|
| 475 |
+
text = link_failed_text(f"something went wrong inside the bot ({type(e).__name__}: {str(e)[:150]})", notice)
|
| 476 |
+
await self._answer(event, text)
|
| 477 |
+
|
| 478 |
+
async def share_link(self, notice: LinkNotice) -> tuple:
|
| 479 |
+
"""(file link, notes) of the π Share URL button of that Database Channel post - waited for like when publishing, the
|
| 480 |
+
userbot looking too when the bot cannot see it. Nothing is posted anywhere."""
|
| 481 |
+
if not notice.post_id:
|
| 482 |
+
raise Failure("The message does not say which post of the Database Channel: it has no βPost:β line.")
|
| 483 |
+
seen = await self._wait_for_share(await self._database_channel(), Notice(post_id=notice.post_id))
|
| 484 |
+
link = norm_url(file_link(seen.found[1]))
|
| 485 |
+
if not link:
|
| 486 |
+
raise Failure(f"The π Share URL button of that post has a link I cannot use: {seen.found[1][:150]}")
|
| 487 |
+
return link, (["The Share URL button was read through the userbot."] if seen.via == "userbot" else [])
|
| 488 |
+
|
| 489 |
async def _answer(self, event: Any, text: str) -> None:
|
| 490 |
try:
|
| 491 |
await event.reply(text, parse_mode=None, link_preview=False)
|
|
|
|
| 526 |
done.notes.append("The Share URL button was read through the userbot.")
|
| 527 |
return done
|
| 528 |
|
| 529 |
+
async def delete(self, notice: DeleteNotice) -> Deleted:
|
| 530 |
+
"""Delete a post this bot made by itself: in its channel (the userbot takes over where Telegram refuses the bot, as in
|
| 531 |
+
My posts) and in My posts. A post that is gone from the channel and from My posts counts as deleted."""
|
| 532 |
+
ctx, db = self.ctx, self.ctx.db
|
| 533 |
+
ch = await self._target_channel(notice, deleting=True)
|
| 534 |
+
mid = notice.message_id
|
| 535 |
+
if not mid:
|
| 536 |
+
raise Failure("The message does not say which post to delete: it has no βMessage:β line.")
|
| 537 |
+
peer = peer_of(ch)
|
| 538 |
+
post = await db.find_by_message(ch.id, mid)
|
| 539 |
+
done = Deleted(channel=ch, message_id=mid, file=notice.file)
|
| 540 |
+
if post is None: # not in My posts: only a message that is gone from the channel as well counts as deleted
|
| 541 |
+
try:
|
| 542 |
+
gone = await gone_ids(ctx.client, peer, [mid])
|
| 543 |
+
except errors.RPCError as e:
|
| 544 |
+
raise Failure(f"I could not look at the post in β{ch.title}β: {explain_rpc(e)}")
|
| 545 |
+
if mid not in gone:
|
| 546 |
+
raise Failure(
|
| 547 |
+
f"Message {mid} of β{ch.title}β is not one of the posts this bot published (My posts does not have it), "
|
| 548 |
+
"so I did not delete it."
|
| 549 |
+
)
|
| 550 |
+
done.notes.append("The post was already gone from the channel and from My posts.")
|
| 551 |
+
return done
|
| 552 |
+
if post.source != "bot" or post.created_by:
|
| 553 |
+
raise Failure(
|
| 554 |
+
f"Message {mid} of β{ch.title}β was not published automatically, so I did not delete it. "
|
| 555 |
+
"Delete it from My posts if you want it gone."
|
| 556 |
+
)
|
| 557 |
+
fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None)
|
| 558 |
+
try:
|
| 559 |
+
out = await delete_batch(ctx.client, peer, [mid], fallback)
|
| 560 |
+
except errors.RPCError as e:
|
| 561 |
+
raise Failure(f"Telegram refused to look at the post in β{ch.title}β: {explain_rpc(e)}")
|
| 562 |
+
finally:
|
| 563 |
+
if deleter is not None:
|
| 564 |
+
await deleter.close()
|
| 565 |
+
if mid not in out.gone:
|
| 566 |
+
why = delete_problem_text(ctx.userbot, bot_error=out.bot_error, fallback_error=out.fallback_error, tried=out.tried_userbot)
|
| 567 |
+
raise Failure(f"Telegram did not delete the post in β{ch.title}β. {why} It is still in My posts.")
|
| 568 |
+
await db.forget_posts(post.channel_id, [mid]) # gone from the channel: from My posts too, with what hangs on it
|
| 569 |
+
if out.by_userbot:
|
| 570 |
+
done.notes.append("The bot was not allowed to delete it, so the userbot did.")
|
| 571 |
+
return done
|
| 572 |
+
|
| 573 |
+
async def _target_channel(self, notice: Any, *, deleting: bool = False) -> Any:
|
| 574 |
"""The channel the message names: connected to this bot, switched on, and not the Database Channel itself."""
|
| 575 |
if notice.channel is None:
|
| 576 |
if notice.channel_raw:
|
| 577 |
raise Failure(f"The message names β{notice.channel_raw}β as the channel, which is not a channel id (like -1001234567890).")
|
| 578 |
+
if deleting:
|
| 579 |
+
raise Failure("The message does not say which channel the post is in: it has no βChannel:β line.")
|
| 580 |
raise Failure(
|
| 581 |
"The message does not say which channel to post in: it has no βChannel:β line "
|
| 582 |
"(the Channel option of the format the episode was renamed with)."
|
| 583 |
)
|
| 584 |
cid = channel_id_of(notice.channel)
|
| 585 |
if cid == channel_id_of(self.ctx.cfg.db_channel):
|
| 586 |
+
raise Failure(
|
| 587 |
+
"The channel in the message is the Database Channel itself - this bot only deletes the posts it made in the channel of the series."
|
| 588 |
+
if deleting
|
| 589 |
+
else "The channel in the message is the Database Channel itself - the post has to go to the channel of the series."
|
| 590 |
+
)
|
| 591 |
ch = await self.ctx.db.get_channel(cid)
|
| 592 |
if ch is None or not ch.active:
|
| 593 |
raise Failure(
|
| 594 |
f"The channel {notice.channel} is not connected to this bot (/channels lists the connected ones, /addchannel adds one), "
|
| 595 |
+
f"so I cannot {'delete' if deleting else 'post'} there."
|
| 596 |
)
|
| 597 |
return ch
|
| 598 |
|
|
|
|
| 733 |
await db.release_slot(ch.id, sent.id, keep_pid=post.id) # the sync may have picked the message up a moment ago
|
| 734 |
await db.update_post(post.id, status="sent", message_id=sent.id, sent_at=utcnow())
|
| 735 |
return Published(
|
| 736 |
+
channel=ch, link=post_link(ch, sent.id), label=label, url=link, file=name or notice.file, episode=notice.episode,
|
| 737 |
+
message_id=sent.id,
|
| 738 |
)
|
tests/test_dbdelete.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deleting an automatically published post: the autorename bot's "Delete the published post" message in the communication
|
| 2 |
+
chat -> the post goes from its channel and from My posts, and the answer says so (or says why not)."""
|
| 3 |
+
import asyncio
|
| 4 |
+
import datetime
|
| 5 |
+
from types import SimpleNamespace
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
|
| 9 |
+
from app.db import utcnow
|
| 10 |
+
from app.dbpublish import DeleteNotice, parse_delete_notice, parse_notice
|
| 11 |
+
|
| 12 |
+
from .fakes import FakeChannelClient, rpc
|
| 13 |
+
from .test_dbpublish import BLACK, BLACKM, COMM, DBM, FILE, Comm, file_post, handle, make_app, notice, notice_handler, run
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def removal(*, channel=BLACKM, message=None, file=FILE, ref="d1"):
|
| 17 |
+
"""What the autorename bot writes when its "Delete post" button is confirmed."""
|
| 18 |
+
lines = ["Delete the published post"]
|
| 19 |
+
if channel is not None:
|
| 20 |
+
lines.append(f"Channel: {channel}")
|
| 21 |
+
if message is not None:
|
| 22 |
+
lines.append(f"Message: {message}")
|
| 23 |
+
if file:
|
| 24 |
+
lines.append(f"File: {file}")
|
| 25 |
+
if ref:
|
| 26 |
+
lines.append(f"Ref: {ref}")
|
| 27 |
+
return "\n".join(lines)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
async def make_series(tmp_path, **cfg):
|
| 31 |
+
"""The app, and the channel of the series as a simulated channel of its own: posts land in it and can be deleted from it."""
|
| 32 |
+
app = await make_app(tmp_path, **cfg)
|
| 33 |
+
black = FakeChannelClient(cid=BLACK, title="Black Clover English", username="blackclover")
|
| 34 |
+
app.tg.add_channel(black)
|
| 35 |
+
|
| 36 |
+
async def send(peer, message="", **kw):
|
| 37 |
+
return SimpleNamespace(id=black._new(message, None, None).id)
|
| 38 |
+
|
| 39 |
+
app.tg.send_message = send
|
| 40 |
+
return app, black
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
async def publish(app, black, *, ref="p1", mid=900):
|
| 44 |
+
"""Publish an episode the way the autorename bot asks for it (event id 900: no clash with the deletions); the message id of the new post."""
|
| 45 |
+
db_post = file_post(app)
|
| 46 |
+
ev = await handle(app, notice(post=db_post.id, ref=ref), mid=mid)
|
| 47 |
+
assert ev.replies[-1].startswith("β
Post published successfully"), ev.replies
|
| 48 |
+
(row,) = await app.db.latest_sent(BLACK)
|
| 49 |
+
return row.message_id
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class FakeDeleter:
|
| 53 |
+
"""What the userbot hands over for deleting: the posts it deletes are gone from the simulated channel."""
|
| 54 |
+
|
| 55 |
+
def __init__(self, black, *, fail=None):
|
| 56 |
+
self.black, self.fail, self.asked, self.closed = black, fail, [], 0
|
| 57 |
+
|
| 58 |
+
async def delete(self, ids):
|
| 59 |
+
self.asked.append(list(ids))
|
| 60 |
+
if self.fail is not None:
|
| 61 |
+
raise self.fail
|
| 62 |
+
for i in ids:
|
| 63 |
+
self.black.msgs.pop(i, None)
|
| 64 |
+
|
| 65 |
+
async def close(self):
|
| 66 |
+
self.closed += 1
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class FakeUserbot:
|
| 70 |
+
def __init__(self, deleter=None, *, enabled=True, ready=True, last_error=""):
|
| 71 |
+
self.deleter, self.enabled, self.ready, self.last_error = deleter, enabled, ready, last_error
|
| 72 |
+
|
| 73 |
+
async def fallback_for(self, ch):
|
| 74 |
+
return (self.deleter.delete, self.deleter) if self.deleter is not None else (None, None)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# ------------------------------------------------------------------------------------------------ the message
|
| 78 |
+
def test_the_delete_message_is_read_line_by_line():
|
| 79 |
+
n = parse_delete_notice(removal(message=57))
|
| 80 |
+
assert n == DeleteNotice(channel=BLACKM, channel_raw=str(BLACKM), message_id=57, file=FILE, ref="d1")
|
| 81 |
+
again = parse_delete_notice(" DELETE the Published Post\nchannel : -100123\nmessage:5\nREF: x")
|
| 82 |
+
assert (again.channel, again.message_id, again.file, again.ref) == (-100123, 5, "", "x")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_it_must_begin_with_the_words_and_is_not_an_upload_notice():
|
| 86 |
+
assert parse_delete_notice("Please delete the published post\nChannel: -100123\nMessage: 5") is None
|
| 87 |
+
assert parse_delete_notice("Message received\nDelete the published post") is None
|
| 88 |
+
assert parse_delete_notice(None) is None and parse_delete_notice("") is None
|
| 89 |
+
assert parse_delete_notice(notice(post=3)) is None # an upload notice is no deletion ...
|
| 90 |
+
assert parse_notice(removal(message=3)) is None # ... and a deletion is no upload notice
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@pytest.mark.parametrize("message", ["", "abc", "12 34", "-5", "1" * 13])
|
| 94 |
+
def test_a_message_id_that_is_no_number_is_none(message):
|
| 95 |
+
assert parse_delete_notice(f"Delete the published post\nChannel: {BLACKM}\nMessage: {message}").message_id is None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ----------------------------------------------------------------------------------------- the post names its id
|
| 99 |
+
def test_the_published_reply_names_the_message_id_of_the_post(tmp_path):
|
| 100 |
+
async def go():
|
| 101 |
+
app, black = await make_series(tmp_path)
|
| 102 |
+
ev = await handle(app, notice(post=file_post(app).id, ref="p1"))
|
| 103 |
+
(row,) = await app.db.latest_sent(BLACK)
|
| 104 |
+
done = ev.replies[-1]
|
| 105 |
+
assert f"\nMessage: {row.message_id}\n" in done and f"Post: https://t.me/blackclover/{row.message_id}\n" in done
|
| 106 |
+
assert row.message_id in black.msgs
|
| 107 |
+
await app.db.close()
|
| 108 |
+
|
| 109 |
+
run(go())
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ---------------------------------------------------------------------------------------------- the deletion
|
| 113 |
+
def test_the_post_is_deleted_in_the_channel_and_in_my_posts(tmp_path):
|
| 114 |
+
async def go():
|
| 115 |
+
app, black = await make_series(tmp_path)
|
| 116 |
+
msg_id = await publish(app, black)
|
| 117 |
+
assert msg_id in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is not None
|
| 118 |
+
ev = await handle(app, removal(message=msg_id), mid=2)
|
| 119 |
+
assert ev.replies[0] == "π₯ Message received - deleting the postβ¦\nRef: d1"
|
| 120 |
+
assert len(ev.replies) == 2
|
| 121 |
+
done = ev.replies[1]
|
| 122 |
+
assert done.startswith("π Post deleted successfully")
|
| 123 |
+
for part in ("Channel: Black Clover English", f"Message: {msg_id}", f"File: {FILE}", "Ref: d1"):
|
| 124 |
+
assert part in done, done
|
| 125 |
+
assert ev.kw == {"parse_mode": None, "link_preview": False}
|
| 126 |
+
assert msg_id not in black.msgs and black.delete_requests == [[msg_id]]
|
| 127 |
+
assert await app.db.find_by_message(BLACK, msg_id) is None
|
| 128 |
+
assert (await app.db.list_posts(BLACK, None, 0, 10))[1] == 0 # not in My posts any more
|
| 129 |
+
assert app.tg.delete_requests == [] and app.tg.msgs # the Database Channel was not touched
|
| 130 |
+
await app.db.close()
|
| 131 |
+
|
| 132 |
+
run(go())
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def test_only_the_named_post_goes(tmp_path):
|
| 136 |
+
async def go():
|
| 137 |
+
app, black = await make_series(tmp_path)
|
| 138 |
+
first = await publish(app, black, ref="p1", mid=1)
|
| 139 |
+
second_file = file_post(app, "Black Clover - S2 E06.mkv")
|
| 140 |
+
await handle(app, notice(post=second_file.id, episode="06", file="Black Clover - S2 E06.mkv", ref="p2"), mid=2)
|
| 141 |
+
rows = await app.db.latest_sent(BLACK)
|
| 142 |
+
second = next(r.message_id for r in rows if r.message_id != first)
|
| 143 |
+
await handle(app, removal(message=first), mid=3)
|
| 144 |
+
assert first not in black.msgs and second in black.msgs
|
| 145 |
+
assert [r.message_id for r in await app.db.latest_sent(BLACK)] == [second]
|
| 146 |
+
await app.db.close()
|
| 147 |
+
|
| 148 |
+
run(go())
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_what_hangs_on_the_post_goes_with_it(tmp_path):
|
| 152 |
+
async def go():
|
| 153 |
+
app, black = await make_series(tmp_path)
|
| 154 |
+
msg_id = await publish(app, black)
|
| 155 |
+
await app.db.schedule_deletes(
|
| 156 |
+
[dict(channel_id=BLACK, message_id=msg_id, delete_at=utcnow() + datetime.timedelta(days=1), group_id="g", created_by=1)]
|
| 157 |
+
)
|
| 158 |
+
await app.db.ignore_post(BLACK, msg_id)
|
| 159 |
+
await handle(app, removal(message=msg_id), mid=2)
|
| 160 |
+
assert await app.db.pending_deletes() == [] and msg_id not in await app.db.ignored_ids(BLACK)
|
| 161 |
+
await app.db.close()
|
| 162 |
+
|
| 163 |
+
run(go())
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_a_post_that_was_deleted_by_hand_is_removed_from_my_posts(tmp_path):
|
| 167 |
+
async def go():
|
| 168 |
+
app, black = await make_series(tmp_path)
|
| 169 |
+
msg_id = await publish(app, black)
|
| 170 |
+
del black.msgs[msg_id] # deleted in Telegram: My posts does not know yet
|
| 171 |
+
ev = await handle(app, removal(message=msg_id), mid=2)
|
| 172 |
+
assert ev.replies[-1].startswith("π Post deleted successfully")
|
| 173 |
+
assert await app.db.find_by_message(BLACK, msg_id) is None
|
| 174 |
+
await app.db.close()
|
| 175 |
+
|
| 176 |
+
run(go())
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def test_a_post_that_is_gone_everywhere_counts_as_deleted(tmp_path):
|
| 180 |
+
"""Pressing the button twice, or deleting the post in My posts first, must not end in a failure."""
|
| 181 |
+
async def go():
|
| 182 |
+
app, black = await make_series(tmp_path)
|
| 183 |
+
msg_id = await publish(app, black)
|
| 184 |
+
await handle(app, removal(message=msg_id, ref="a"), mid=2)
|
| 185 |
+
again = await handle(app, removal(message=msg_id, ref="b"), mid=3)
|
| 186 |
+
assert again.replies[-1].startswith("π Post deleted successfully")
|
| 187 |
+
assert "βΉοΈ The post was already gone from the channel and from My posts." in again.replies[-1]
|
| 188 |
+
assert "Ref: b" in again.replies[-1] and black.delete_requests == [[msg_id]] # nothing was asked of Telegram twice
|
| 189 |
+
await app.db.close()
|
| 190 |
+
|
| 191 |
+
run(go())
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def test_a_message_that_is_not_in_my_posts_but_still_in_the_channel_is_left_alone(tmp_path):
|
| 195 |
+
async def go():
|
| 196 |
+
app, black = await make_series(tmp_path)
|
| 197 |
+
by_hand = black._new("somebody's own post", None, None).id
|
| 198 |
+
ev = await handle(app, removal(message=by_hand))
|
| 199 |
+
failed = ev.replies[-1]
|
| 200 |
+
assert failed.startswith("β Deletion failed: ") and f"Message {by_hand} of βBlack Clover Englishβ is not one of the posts" in failed
|
| 201 |
+
assert "so I did not delete it" in failed and f"File: {FILE}" in failed and "Ref: d1" in failed
|
| 202 |
+
assert by_hand in black.msgs and black.delete_requests == []
|
| 203 |
+
await app.db.close()
|
| 204 |
+
|
| 205 |
+
run(go())
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@pytest.mark.parametrize("fields", [dict(created_by=1, source="bot"), dict(created_by=0, source="adopted")])
|
| 209 |
+
def test_a_post_that_was_not_published_automatically_is_left_alone(tmp_path, fields):
|
| 210 |
+
"""A post somebody made with the bot (or one it adopted) is deleted from My posts, never by a message in the chat."""
|
| 211 |
+
async def go():
|
| 212 |
+
app, black = await make_series(tmp_path)
|
| 213 |
+
mid = black._new("a post made by hand", None, None).id
|
| 214 |
+
row = await app.db.create_post(
|
| 215 |
+
channel_id=BLACK, message_id=mid, status="sent", text="a post made by hand", entities=[], buttons=[], **fields
|
| 216 |
+
)
|
| 217 |
+
ev = await handle(app, removal(message=mid))
|
| 218 |
+
assert "was not published automatically, so I did not delete it" in ev.replies[-1] and ev.replies[-1].startswith("β Deletion failed")
|
| 219 |
+
assert mid in black.msgs and black.delete_requests == [] and (await app.db.get_post(row.id)) is not None
|
| 220 |
+
await app.db.close()
|
| 221 |
+
|
| 222 |
+
run(go())
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def test_a_post_the_bot_may_not_delete_stays_and_the_reason_is_given(tmp_path):
|
| 226 |
+
async def go():
|
| 227 |
+
app, black = await make_series(tmp_path)
|
| 228 |
+
msg_id = await publish(app, black)
|
| 229 |
+
black.undeletable = {msg_id} # like a post older than 48 hours
|
| 230 |
+
ev = await handle(app, removal(message=msg_id))
|
| 231 |
+
failed = ev.replies[-1]
|
| 232 |
+
assert failed.startswith("β Deletion failed: Telegram did not delete the post in βBlack Clover Englishβ.")
|
| 233 |
+
assert "/userbot" in failed and "still in My posts" in failed and "Ref: d1" in failed
|
| 234 |
+
assert msg_id in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is not None
|
| 235 |
+
await app.db.close()
|
| 236 |
+
|
| 237 |
+
run(go())
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def test_telegrams_refusal_is_named(tmp_path):
|
| 241 |
+
async def go():
|
| 242 |
+
app, black = await make_series(tmp_path)
|
| 243 |
+
msg_id = await publish(app, black)
|
| 244 |
+
black.delete_error = rpc("ChatAdminRequiredError")
|
| 245 |
+
ev = await handle(app, removal(message=msg_id))
|
| 246 |
+
assert "Telegram refused the bot (ChatAdminRequiredError)" in ev.replies[-1]
|
| 247 |
+
assert msg_id in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is not None
|
| 248 |
+
await app.db.close()
|
| 249 |
+
|
| 250 |
+
run(go())
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def test_the_userbot_deletes_what_the_bot_may_not(tmp_path):
|
| 254 |
+
async def go():
|
| 255 |
+
app, black = await make_series(tmp_path)
|
| 256 |
+
msg_id = await publish(app, black)
|
| 257 |
+
black.undeletable = {msg_id}
|
| 258 |
+
deleter = FakeDeleter(black)
|
| 259 |
+
app.ctx.userbot = FakeUserbot(deleter)
|
| 260 |
+
ev = await handle(app, removal(message=msg_id))
|
| 261 |
+
done = ev.replies[-1]
|
| 262 |
+
assert done.startswith("π Post deleted successfully") and "βΉοΈ The bot was not allowed to delete it, so the userbot did." in done
|
| 263 |
+
assert deleter.asked == [[msg_id]] and deleter.closed == 1 # the deleter is always closed again
|
| 264 |
+
assert msg_id not in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is None
|
| 265 |
+
await app.db.close()
|
| 266 |
+
|
| 267 |
+
run(go())
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def test_the_userbot_is_not_used_when_the_bot_can_delete(tmp_path):
|
| 271 |
+
async def go():
|
| 272 |
+
app, black = await make_series(tmp_path)
|
| 273 |
+
msg_id = await publish(app, black)
|
| 274 |
+
deleter = FakeDeleter(black)
|
| 275 |
+
app.ctx.userbot = FakeUserbot(deleter)
|
| 276 |
+
ev = await handle(app, removal(message=msg_id))
|
| 277 |
+
assert ev.replies[-1].startswith("π Post deleted successfully") and "userbot" not in ev.replies[-1]
|
| 278 |
+
assert deleter.asked == [] and deleter.closed == 1
|
| 279 |
+
await app.db.close()
|
| 280 |
+
|
| 281 |
+
run(go())
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def test_a_userbot_that_cannot_delete_is_explained(tmp_path):
|
| 285 |
+
async def go():
|
| 286 |
+
app, black = await make_series(tmp_path)
|
| 287 |
+
msg_id = await publish(app, black)
|
| 288 |
+
black.undeletable = {msg_id}
|
| 289 |
+
deleter = FakeDeleter(black, fail=RuntimeError("no right"))
|
| 290 |
+
app.ctx.userbot = FakeUserbot(deleter)
|
| 291 |
+
ev = await handle(app, removal(message=msg_id))
|
| 292 |
+
assert "The userbot could not help: no right" in ev.replies[-1] and ev.replies[-1].startswith("β Deletion failed")
|
| 293 |
+
assert deleter.closed == 1 and msg_id in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is not None
|
| 294 |
+
await app.db.close()
|
| 295 |
+
|
| 296 |
+
run(go())
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def test_a_userbot_that_is_not_connected_is_named(tmp_path):
|
| 300 |
+
async def go():
|
| 301 |
+
app, black = await make_series(tmp_path)
|
| 302 |
+
msg_id = await publish(app, black)
|
| 303 |
+
black.undeletable = {msg_id}
|
| 304 |
+
app.ctx.userbot = FakeUserbot(None, ready=False, last_error="session expired")
|
| 305 |
+
ev = await handle(app, removal(message=msg_id))
|
| 306 |
+
assert "The userbot is not connected: session expired" in ev.replies[-1]
|
| 307 |
+
await app.db.close()
|
| 308 |
+
|
| 309 |
+
run(go())
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
# ------------------------------------------------------------------------------------ what cannot be deleted
|
| 313 |
+
@pytest.mark.parametrize(
|
| 314 |
+
"text, complaint",
|
| 315 |
+
[
|
| 316 |
+
(removal(channel=None, message=5), "does not say which channel the post is in: it has no βChannel:β line"),
|
| 317 |
+
(removal(channel="Black Clover", message=5), "names βBlack Cloverβ as the channel, which is not a channel id"),
|
| 318 |
+
(removal(channel=DBM, message=5), "is the Database Channel itself - this bot only deletes the posts it made in the channel of the series"),
|
| 319 |
+
(removal(channel=-1009999999999, message=5), "-1009999999999 is not connected to this bot"),
|
| 320 |
+
(removal(message=None), "does not say which post to delete: it has no βMessage:β line"),
|
| 321 |
+
],
|
| 322 |
+
)
|
| 323 |
+
def test_a_message_that_cannot_work_is_refused_with_its_reason_and_nothing_is_touched(tmp_path, text, complaint):
|
| 324 |
+
async def go():
|
| 325 |
+
app, black = await make_series(tmp_path)
|
| 326 |
+
msg_id = await publish(app, black)
|
| 327 |
+
ev = await handle(app, text, mid=2)
|
| 328 |
+
assert ev.replies[-1].startswith("β Deletion failed: ") and complaint in ev.replies[-1] and "Ref: d1" in ev.replies[-1]
|
| 329 |
+
assert msg_id in black.msgs and black.delete_requests == [] and app.tg.delete_requests == []
|
| 330 |
+
assert (await app.db.find_by_message(BLACK, msg_id)) is not None
|
| 331 |
+
await app.db.close()
|
| 332 |
+
|
| 333 |
+
run(go())
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def test_a_channel_that_is_not_connected_any_more_cannot_be_deleted_in(tmp_path):
|
| 337 |
+
async def go():
|
| 338 |
+
app, black = await make_series(tmp_path)
|
| 339 |
+
msg_id = await publish(app, black)
|
| 340 |
+
await app.db.set_channel_active(BLACK, False)
|
| 341 |
+
ev = await handle(app, removal(message=msg_id))
|
| 342 |
+
assert f"The channel {BLACKM} is not connected to this bot" in ev.replies[-1] and "so I cannot delete there" in ev.replies[-1]
|
| 343 |
+
assert msg_id in black.msgs
|
| 344 |
+
await app.db.close()
|
| 345 |
+
|
| 346 |
+
run(go())
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def test_when_telegram_cannot_be_asked_the_reason_is_reported(tmp_path):
|
| 350 |
+
async def go():
|
| 351 |
+
app, black = await make_series(tmp_path)
|
| 352 |
+
msg_id = await publish(app, black)
|
| 353 |
+
black.fail["GetMessagesRequest"] = rpc("ChannelPrivateError") # the bot cannot read the channel at all
|
| 354 |
+
ev = await handle(app, removal(message=msg_id, ref="a"), mid=2)
|
| 355 |
+
assert ev.replies[-1].startswith("β Deletion failed: Telegram refused to look at the post in βBlack Clover Englishβ")
|
| 356 |
+
assert (await app.db.find_by_message(BLACK, msg_id)) is not None
|
| 357 |
+
await app.db.delete_post((await app.db.find_by_message(BLACK, msg_id)).id) # (not in My posts any more: the other path)
|
| 358 |
+
ev = await handle(app, removal(message=msg_id, ref="b"), mid=3)
|
| 359 |
+
assert ev.replies[-1].startswith("β Deletion failed: I could not look at the post in βBlack Clover Englishβ")
|
| 360 |
+
await app.db.close()
|
| 361 |
+
|
| 362 |
+
run(go())
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
# ---------------------------------------------------------------------------------------- the conversation
|
| 366 |
+
def test_something_unexpected_still_gets_an_answer(tmp_path):
|
| 367 |
+
async def go():
|
| 368 |
+
app, black = await make_series(tmp_path)
|
| 369 |
+
|
| 370 |
+
async def boom(notice):
|
| 371 |
+
raise RuntimeError("kaput")
|
| 372 |
+
|
| 373 |
+
app.ctx.publisher.delete = boom
|
| 374 |
+
ev = await handle(app, removal(message=5))
|
| 375 |
+
assert ev.replies[-1].startswith("β Deletion failed: something went wrong inside the bot (RuntimeError: kaput)")
|
| 376 |
+
assert "Ref: d1" in ev.replies[-1]
|
| 377 |
+
await app.db.close()
|
| 378 |
+
|
| 379 |
+
run(go())
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def test_the_same_message_is_answered_once(tmp_path):
|
| 383 |
+
async def go():
|
| 384 |
+
app, black = await make_series(tmp_path)
|
| 385 |
+
msg_id = await publish(app, black)
|
| 386 |
+
first = await handle(app, removal(message=msg_id), mid=7)
|
| 387 |
+
again = await handle(app, removal(message=msg_id), mid=7) # delivered twice
|
| 388 |
+
assert len(first.replies) == 2 and again.replies == []
|
| 389 |
+
await app.db.close()
|
| 390 |
+
|
| 391 |
+
run(go())
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def test_a_deletion_waits_for_the_post_that_is_being_made(tmp_path):
|
| 395 |
+
"""One thing at a time: the answer "received" comes at once, the deletion when the lock is free."""
|
| 396 |
+
async def go():
|
| 397 |
+
app, black = await make_series(tmp_path)
|
| 398 |
+
msg_id = await publish(app, black)
|
| 399 |
+
pub = app.ctx.publisher
|
| 400 |
+
await pub.lock.acquire()
|
| 401 |
+
ev = Comm(removal(message=msg_id), mid=5)
|
| 402 |
+
task = asyncio.ensure_future(pub.handle(ev))
|
| 403 |
+
await asyncio.sleep(0.5) # (the database answers from another thread: that takes real time)
|
| 404 |
+
assert len(ev.replies) == 1 and ev.replies[0].startswith("π₯ Message received") and msg_id in black.msgs
|
| 405 |
+
pub.lock.release()
|
| 406 |
+
await task
|
| 407 |
+
assert len(ev.replies) == 2 and ev.replies[1].startswith("π Post deleted successfully") and msg_id not in black.msgs
|
| 408 |
+
await app.db.close()
|
| 409 |
+
|
| 410 |
+
run(go())
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def test_the_listener_deletes_only_for_the_autorename_bot_in_the_communication_chat(tmp_path):
|
| 414 |
+
async def go():
|
| 415 |
+
app, black = await make_series(tmp_path)
|
| 416 |
+
msg_id = await publish(app, black)
|
| 417 |
+
fn = notice_handler(app)
|
| 418 |
+
elsewhere = Comm(removal(message=msg_id), mid=2, chat=-1000000000555)
|
| 419 |
+
stranger = Comm(removal(message=msg_id), mid=3, sender=12345)
|
| 420 |
+
await fn(elsewhere)
|
| 421 |
+
await fn(stranger)
|
| 422 |
+
assert elsewhere.replies == [] and stranger.replies == [] and msg_id in black.msgs
|
| 423 |
+
good = Comm(removal(message=msg_id), mid=4)
|
| 424 |
+
await fn(good)
|
| 425 |
+
assert len(good.replies) == 2 and good.replies[1].startswith("π Post deleted successfully") and msg_id not in black.msgs
|
| 426 |
+
assert good.chat_id == COMM
|
| 427 |
+
await app.db.close()
|
| 428 |
+
|
| 429 |
+
run(go())
|
tests/test_dblink.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Only the Share URL: the autorename bot asks for the link of a file in the Database Channel; nothing is published."""
|
| 2 |
+
from app.dbpublish import LinkNotice, parse_link_notice, parse_notice, parse_delete_notice
|
| 3 |
+
|
| 4 |
+
from .test_dbpublish import FILE_LINK, FakeReader, FakeUserbot, file_post, handle, make_app, notice, run
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def ask(post=None, ref="l1"):
|
| 8 |
+
lines = ["Get the share URL"]
|
| 9 |
+
if post is not None:
|
| 10 |
+
lines.append(f"Post: {post}")
|
| 11 |
+
if ref:
|
| 12 |
+
lines.append(f"Ref: {ref}")
|
| 13 |
+
return "\n".join(lines)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_the_message_is_read_and_is_nothing_else():
|
| 17 |
+
assert parse_link_notice(ask(7)) == LinkNotice(post_id=7, ref="l1")
|
| 18 |
+
assert parse_link_notice("GET the Share URL\npost : x").post_id is None
|
| 19 |
+
assert parse_link_notice("please get the share url\nPost: 7") is None and parse_link_notice(None) is None
|
| 20 |
+
assert parse_notice(ask(7)) is None and parse_delete_notice(ask(7)) is None and parse_link_notice(notice(post=3)) is None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_the_link_is_returned_and_nothing_is_posted(tmp_path):
|
| 24 |
+
async def go():
|
| 25 |
+
app = await make_app(tmp_path)
|
| 26 |
+
post = file_post(app)
|
| 27 |
+
ev = await handle(app, ask(post.id))
|
| 28 |
+
assert ev.replies[0] == "π₯ Message received - looking for the Share URLβ¦\nRef: l1"
|
| 29 |
+
assert ev.replies[1] == f"π Share URL ready\nURL: {FILE_LINK}\nRef: l1"
|
| 30 |
+
assert not app.tg.sent and not app.tg.requests
|
| 31 |
+
await app.db.close()
|
| 32 |
+
|
| 33 |
+
run(go())
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_the_userbot_reads_it_when_the_bot_cannot_see_the_button(tmp_path):
|
| 37 |
+
async def go():
|
| 38 |
+
app = await make_app(tmp_path)
|
| 39 |
+
hidden = file_post(app, buttons=False)
|
| 40 |
+
seen = file_post(app)
|
| 41 |
+
reader = FakeReader(app.clock, {hidden.id: seen})
|
| 42 |
+
app.ctx.userbot = FakeUserbot(reader)
|
| 43 |
+
ev = await handle(app, ask(hidden.id))
|
| 44 |
+
assert ev.replies[-1].startswith("π Share URL ready") and "read through the userbot" in ev.replies[-1]
|
| 45 |
+
await app.db.close()
|
| 46 |
+
|
| 47 |
+
run(go())
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_failures_are_reported(tmp_path):
|
| 51 |
+
async def go():
|
| 52 |
+
app = await make_app(tmp_path)
|
| 53 |
+
none = await handle(app, ask(None), mid=2)
|
| 54 |
+
assert "no βPost:β line" in none.replies[-1] and none.replies[-1].startswith("β Share URL failed: ")
|
| 55 |
+
bare = file_post(app, buttons=False)
|
| 56 |
+
no_button = await handle(app, ask(bare.id), mid=3)
|
| 57 |
+
assert "No π Share URL button" in no_button.replies[-1] and "Ref: l1" in no_button.replies[-1]
|
| 58 |
+
await app.db.close()
|
| 59 |
+
|
| 60 |
+
run(go())
|