Spaces:
Running
Running
github-actions[bot] commited on
Commit Β·
de05efa
1
Parent(s): 8d18810
Automated sync from GitHub
Browse filesFiles changed (3)
- app/dbpublish.py+204-11
- tests/test_dbdelete.pyAdded+429
- tests/test_dblink.pyAdded+60
17 unmodified lines18192021222316 unmodified lines40414243444546479 unmodified lines57585960616226 unmodified lines8990919293941 unmodified line969798991001011021037 unmodified lines11111211311411511611716 unmodified lines1341351361371381391 unmodified line1411421431441451461471482 unmodified lines151152153154155156168 unmodified lines3253263273283293303313323333343353367 unmodified lines34434534634734834934 unmodified lines384385386387388389390391392393394395396397398399400401402403404405406134 unmodified lines54154254354454517 unmodified linesso on) and the button name ("Download Episode {episode}"). The button opens the file link of the Share URL button.It goes to the channel the message names - nothing is guessed from the file name.4. "Post published successfully" - or "Publication failed: <why>" - goes back to the communication chat."""from __future__ import annotations16 unmodified linesfrom .db import utcnowfrom .linkswap import apply_span_replacementsfrom .replace_engine import fetch_messages, get_top_id, is_skippablefrom .tgutil import button_url, de_entities, explain_rpc, peer_of, post_link, ser_entitiesfrom .userbot import UserbotErrorlog = logging.getLogger(__name__)9 unmodified linesBUTTON_SHOWN = 64 # a button name is cut at this length when the post is made_NOTICE_RX = re.compile(r"(?i)file\s+uploaded\s+to\s+the\s+database\s+channel")_SHARE_RX = re.compile(r"(?i)\bshare\s*url\b")_SHARE_LINK_RX = re.compile(r"(?i)^https?://(?:t\.me|telegram\.me|telegram\.dog)/share(?:/url)?\?(.*)$")# {episode}, {episode number}, {episode_number}, {channel} (also {channel name}); spaces inside the braces do not matter26 unmodified linesreturn int(m.group(1)) if m else Nonedef parse_notice(text: Optional[str]) -> Optional[Notice]:"""The message the autorename bot writes ("File uploaded to the Database Channel", then Episode / Channel / File /Post / Ref lines); None for anything else."""1 unmodified linereturn Nonedef field_of(label: str) -> str:m = re.search(rf"(?im)^\s*{label}\s*:\s*(.+?)\s*$", text or "")return m.group(1).strip() if m else ""post = field_of("post")channel_raw = field_of("channel")7 unmodified lines)def _tail(notice: Optional[Notice]) -> str:return f"\nRef: {notice.ref}" if notice is not None and notice.ref else ""16 unmodified linesfile: strepisode: str = ""notes: list = field(default_factory=list)def published_text(p: Published, notice: Optional[Notice] = None) -> str:1 unmodified line"β Post published successfully",f"Channel: {p.channel.title}",f"Post: {p.link}",f"Button: {p.label} β {p.url}",]if p.episode:lines.append(f"Episode: {p.episode}")lines += [f"βΉοΈ {n}" for n in p.notes]2 unmodified linesreturn "\n".join(lines) + _tail(notice)# ------------------------------------------------------------------------------------------------ chat ids, namesdef channel_id_of(value: int) -> int:"""The id the database keeps for a channel, from the id as Telegram apps write it (-100β¦); a bare id stays as it is."""168 unmodified lines# --------------------------------------------------------------------------------------------- entry pointasync def handle(self, event: Any) -> None:"""A message of the autorename bot in the communication chat."""notice = parse_notice(getattr(event, "raw_text", None))if notice is None or event.id in self._handled:return # something else it says, or the same notice againself._handled[event.id] = Nonewhile len(self._handled) > KEEP_NOTICES:self._handled.popitem(last=False)await self._answer(event, received_text(notice))async with self.lock:try:7 unmodified linestext = failed_text(f"something went wrong inside the bot ({type(e).__name__}: {str(e)[:150]})", notice)await self._answer(event, text)async def _answer(self, event: Any, text: str) -> None:try:await event.reply(text, parse_mode=None, link_preview=False)34 unmodified linesdone.notes.append("The Share URL button was read through the userbot.")return doneasync def _target_channel(self, notice: Notice) -> Any:"""The channel the message names: connected to this bot, switched on, and not the Database Channel itself."""if notice.channel is None:if notice.channel_raw:raise Failure(f"The message names β{notice.channel_raw}β as the channel, which is not a channel id (like -1001234567890).")raise Failure("The message does not say which channel to post in: it has no βChannel:β line ""(the Channel option of the format the episode was renamed with).")cid = channel_id_of(notice.channel)if cid == channel_id_of(self.ctx.cfg.db_channel):raise Failure("The channel in the message is the Database Channel itself - the post has to go to the channel of the series.")ch = await self.ctx.db.get_channel(cid)if ch is None or not ch.active:raise Failure(f"The channel {notice.channel} is not connected to this bot (/channels lists the connected ones, /addchannel adds one), ""so I cannot post there.")return ch134 unmodified linesawait db.release_slot(ch.id, sent.id, keep_pid=post.id) # the sync may have picked the message up a moment agoawait db.update_post(post.id, status="sent", message_id=sent.id, sent_at=utcnow())return Published(channel=ch, link=post_link(ch, sent.id), label=label, url=link, file=name or notice.file, episode=notice.episode)17 unmodified lines181920212223242526272816 unmodified lines4546474849505152539 unmodified lines636465666768697026 unmodified lines9798991001011021031041051061071081 unmodified line1101111121131141151167 unmodified lines12412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318416 unmodified lines2012022032042052062071 unmodified line2092102112122132142152162172182 unmodified lines221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251168 unmodified lines4204214224234244254264274284294304314324334344354364374384394407 unmodified lines44844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049134 unmodified lines526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598134 unmodified lines73373473573673773817 unmodified linesso on) and the button name ("Download Episode {episode}"). The button opens the file link of the Share URL button.It goes to the channel the message names - nothing is guessed from the file name.4. "Post published successfully" - or "Publication failed: <why>" - goes back to the communication chat.Deleting: the "Delete post" button of the autorename bot writes "Delete the published post" in the communication chat(Channel / Message / File / Ref lines: the channel and the message id of the post, as this bot reported them). This bot thendeletes that post in the channel - only one it published by itself - and in My posts, and answers "Post deleted successfully"(also when the post was already gone) or "Deletion failed: <why>"."""from __future__ import annotations16 unmodified linesfrom .db import utcnowfrom .linkswap import apply_span_replacementsfrom .replace_engine import fetch_messages, get_top_id, is_skippablefrom .repost_engine import delete_batch, gone_idsfrom .tgutil import button_url, de_entities, explain_rpc, peer_of, post_link, ser_entitiesfrom .userbot import UserbotError, delete_problem_textlog = logging.getLogger(__name__)9 unmodified linesBUTTON_SHOWN = 64 # a button name is cut at this length when the post is made_NOTICE_RX = re.compile(r"(?i)file\s+uploaded\s+to\s+the\s+database\s+channel")_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_LINK_RX = re.compile(r"(?i)\A\s*get\s+the\s+share\s+url\b")_SHARE_RX = re.compile(r"(?i)\bshare\s*url\b")_SHARE_LINK_RX = re.compile(r"(?i)^https?://(?:t\.me|telegram\.me|telegram\.dog)/share(?:/url)?\?(.*)$")# {episode}, {episode number}, {episode_number}, {channel} (also {channel name}); spaces inside the braces do not matter26 unmodified linesreturn int(m.group(1)) if m else Nonedef _field(text: Optional[str], label: str) -> str:"""The value of a ``Label: value`` line of a message; empty when there is no such line."""m = re.search(rf"(?im)^\s*{label}\s*:\s*(.+?)\s*$", text or "")return m.group(1).strip() if m else ""def parse_notice(text: Optional[str]) -> Optional[Notice]:"""The message the autorename bot writes ("File uploaded to the Database Channel", then Episode / Channel / File /Post / Ref lines); None for anything else."""1 unmodified linereturn Nonedef field_of(label: str) -> str:return _field(text, label)post = field_of("post")channel_raw = field_of("channel")7 unmodified lines)@dataclassclass DeleteNotice:"""The autorename bot asking for a published post to be deleted."""channel: Optional[int] = None # the channel the post is in, as written (-100β¦); None when the message names nonechannel_raw: str = "" # what stood after "Channel:" (shown when it is not an id)message_id: Optional[int] = None # the post, as a message of that channel (the "Message:" line of "Post published successfully")file: str = ""ref: str = "" # repeated in every answer, as in the notice of an uploaddef parse_delete_notice(text: Optional[str]) -> Optional[DeleteNotice]:"""The message the autorename bot writes to have a post deleted ("Delete the published post", then Channel / Message /File / Ref lines); None for anything else."""if not _DELETE_RX.search(text or ""):return Nonechannel_raw, message = _field(text, "channel"), _field(text, "message")return DeleteNotice(channel=chat_number(channel_raw),channel_raw=channel_raw[:60],message_id=int(message) if re.fullmatch(r"\d{1,12}", message) else None,file=_field(text, "file"),ref=_field(text, "ref")[:40],)@dataclassclass LinkNotice:"""The autorename bot asking only for the Share URL of a file in the Database Channel (nothing is published)."""post_id: Optional[int] = None # the file in the Database Channelref: str = ""def parse_link_notice(text: Optional[str]) -> Optional[LinkNotice]:""""Get the share URL", then Post / Ref lines; None for anything else."""if not _LINK_RX.search(text or ""):return Nonepost = _field(text, "post")return LinkNotice(post_id=int(post) if re.fullmatch(r"\d{1,12}", post) else None, ref=_field(text, "ref")[:40])def link_received_text(notice: Optional[LinkNotice] = None) -> str:return "π₯ Message received - looking for the Share URLβ¦" + _tail(notice)def link_ready_text(url: str, notes: list, notice: Optional[LinkNotice] = None) -> str:return "\n".join(["π Share URL ready", f"URL: {url}", *[f"βΉοΈ {n}" for n in notes]]) + _tail(notice)def link_failed_text(reason: str, notice: Optional[LinkNotice] = None) -> str:return f"β Share URL failed: {' '.join((reason or 'unknown reason').split())[:600]}" + _tail(notice)def _tail(notice: Any) -> str:return f"\nRef: {notice.ref}" if notice is not None and notice.ref else ""16 unmodified linesfile: strepisode: str = ""notes: list = field(default_factory=list)message_id: int = 0 # the new post as a message of its channel (what a deletion names)def published_text(p: Published, notice: Optional[Notice] = None) -> str:1 unmodified line"β Post published successfully",f"Channel: {p.channel.title}",f"Post: {p.link}",]if p.message_id:lines.append(f"Message: {p.message_id}")lines.append(f"Button: {p.label} β {p.url}")if p.episode:lines.append(f"Episode: {p.episode}")lines += [f"βΉοΈ {n}" for n in p.notes]2 unmodified linesreturn "\n".join(lines) + _tail(notice)@dataclassclass Deleted:channel: Anymessage_id: intfile: str = ""notes: list = field(default_factory=list)def delete_received_text(notice: Optional[DeleteNotice] = None) -> str:return "π₯ Message received - deleting the postβ¦" + _tail(notice)def deleted_text(d: Deleted, notice: Optional[DeleteNotice] = None) -> str:lines = ["π Post deleted successfully", f"Channel: {d.channel.title}", f"Message: {d.message_id}"]lines += [f"βΉοΈ {n}" for n in d.notes]if d.file:lines.append(f"File: {d.file}")return "\n".join(lines) + _tail(notice)def delete_failed_text(reason: str, notice: Optional[DeleteNotice] = None) -> str:reason = " ".join((reason or "unknown reason").split())return f"β Deletion failed: {reason[:600]}" + (f"\nFile: {notice.file}" if notice is not None and notice.file else "") + _tail(notice)# ------------------------------------------------------------------------------------------------ chat ids, namesdef channel_id_of(value: int) -> int:"""The id the database keeps for a channel, from the id as Telegram apps write it (-100β¦); a bare id stays as it is."""168 unmodified lines# --------------------------------------------------------------------------------------------- entry pointasync def handle(self, event: Any) -> None:"""A message of the autorename bot in the communication chat."""text = getattr(event, "raw_text", None)notice = parse_notice(text)removal = None if notice is not None else parse_delete_notice(text)lookup = None if notice is not None or removal is not None else parse_link_notice(text)if (notice is None and removal is None and lookup is None) or event.id in self._handled:return # something else it says, or the same notice againself._handled[event.id] = Nonewhile len(self._handled) > KEEP_NOTICES:self._handled.popitem(last=False)if removal is not None:await self._remove(event, removal)returnif lookup is not None:await self._lookup(event, lookup)returnawait self._answer(event, received_text(notice))async with self.lock:try:7 unmodified linestext = failed_text(f"something went wrong inside the bot ({type(e).__name__}: {str(e)[:150]})", notice)await self._answer(event, text)async def _remove(self, event: Any, notice: DeleteNotice) -> None:"""A request to delete a published post: "received", then "deleted" or why not."""await self._answer(event, delete_received_text(notice))async with self.lock:try:text = deleted_text(await self.delete(notice), notice)except Failure as f:log.info("automatic deletion: %s", f)text = delete_failed_text(str(f), notice)except Exception as e: # noqa: BLE001 - the autorename bot must always get an answerlog.exception("automatic deletion failed")text = delete_failed_text(f"something went wrong inside the bot ({type(e).__name__}: {str(e)[:150]})", notice)await self._answer(event, text)async def _lookup(self, event: Any, notice: LinkNotice) -> None:"""A request for the Share URL of a file in the Database Channel: "received", then the link or why not."""await self._answer(event, link_received_text(notice))async with self.lock:try:text = link_ready_text(*await self.share_link(notice), notice)except Failure as f:text = link_failed_text(str(f), notice)except Exception as e: # noqa: BLE001 - the autorename bot must always get an answerlog.exception("looking for the share url failed")text = link_failed_text(f"something went wrong inside the bot ({type(e).__name__}: {str(e)[:150]})", notice)await self._answer(event, text)async def share_link(self, notice: LinkNotice) -> tuple:"""(file link, notes) of the π Share URL button of that Database Channel post - waited for like when publishing, theuserbot looking too when the bot cannot see it. Nothing is posted anywhere."""if not notice.post_id:raise Failure("The message does not say which post of the Database Channel: it has no βPost:β line.")seen = await self._wait_for_share(await self._database_channel(), Notice(post_id=notice.post_id))link = norm_url(file_link(seen.found[1]))if not link:raise Failure(f"The π Share URL button of that post has a link I cannot use: {seen.found[1][:150]}")return link, (["The Share URL button was read through the userbot."] if seen.via == "userbot" else [])async def _answer(self, event: Any, text: str) -> None:try:await event.reply(text, parse_mode=None, link_preview=False)34 unmodified linesdone.notes.append("The Share URL button was read through the userbot.")return doneasync def delete(self, notice: DeleteNotice) -> Deleted:"""Delete a post this bot made by itself: in its channel (the userbot takes over where Telegram refuses the bot, as inMy posts) and in My posts. A post that is gone from the channel and from My posts counts as deleted."""ctx, db = self.ctx, self.ctx.dbch = await self._target_channel(notice, deleting=True)mid = notice.message_idif not mid:raise Failure("The message does not say which post to delete: it has no βMessage:β line.")peer = peer_of(ch)post = await db.find_by_message(ch.id, mid)done = Deleted(channel=ch, message_id=mid, file=notice.file)if post is None: # not in My posts: only a message that is gone from the channel as well counts as deletedtry:gone = await gone_ids(ctx.client, peer, [mid])except errors.RPCError as e:raise Failure(f"I could not look at the post in β{ch.title}β: {explain_rpc(e)}")if mid not in gone:raise Failure(f"Message {mid} of β{ch.title}β is not one of the posts this bot published (My posts does not have it), ""so I did not delete it.")done.notes.append("The post was already gone from the channel and from My posts.")return doneif post.source != "bot" or post.created_by:raise Failure(f"Message {mid} of β{ch.title}β was not published automatically, so I did not delete it. ""Delete it from My posts if you want it gone.")fallback, deleter = await ctx.userbot.fallback_for(ch) if ctx.userbot is not None else (None, None)try:out = await delete_batch(ctx.client, peer, [mid], fallback)except errors.RPCError as e:raise Failure(f"Telegram refused to look at the post in β{ch.title}β: {explain_rpc(e)}")finally:if deleter is not None:await deleter.close()if mid 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 Failure(f"Telegram did not delete the post in β{ch.title}β. {why} It is still in My posts.")await db.forget_posts(post.channel_id, [mid]) # gone from the channel: from My posts too, with what hangs on itif out.by_userbot:done.notes.append("The bot was not allowed to delete it, so the userbot did.")return doneasync def _target_channel(self, notice: Any, *, deleting: bool = False) -> Any:"""The channel the message names: connected to this bot, switched on, and not the Database Channel itself."""if notice.channel is None:if notice.channel_raw:raise Failure(f"The message names β{notice.channel_raw}β as the channel, which is not a channel id (like -1001234567890).")if deleting:raise Failure("The message does not say which channel the post is in: it has no βChannel:β line.")raise Failure("The message does not say which channel to post in: it has no βChannel:β line ""(the Channel option of the format the episode was renamed with).")cid = channel_id_of(notice.channel)if cid == channel_id_of(self.ctx.cfg.db_channel):raise Failure("The channel in the message is the Database Channel itself - this bot only deletes the posts it made in the channel of the series."if deletingelse "The channel in the message is the Database Channel itself - the post has to go to the channel of the series.")ch = await self.ctx.db.get_channel(cid)if ch is None or not ch.active:raise Failure(f"The channel {notice.channel} is not connected to this bot (/channels lists the connected ones, /addchannel adds one), "f"so I cannot {'delete' if deleting else 'post'} there.")return ch134 unmodified linesawait db.release_slot(ch.id, sent.id, keep_pid=post.id) # the sync may have picked the message up a moment agoawait db.update_post(post.id, status="sent", message_id=sent.id, sent_at=utcnow())return Published(channel=ch, link=post_link(ch, sent.id), label=label, url=link, file=name or notice.file, episode=notice.episode,message_id=sent.id,)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429"""Deleting an automatically published post: the autorename bot's "Delete the published post" message in the communicationchat -> the post goes from its channel and from My posts, and the answer says so (or says why not)."""import asyncioimport datetimefrom types import SimpleNamespace
import pytest
from app.db import utcnowfrom app.dbpublish import DeleteNotice, parse_delete_notice, parse_notice
from .fakes import FakeChannelClient, rpcfrom .test_dbpublish import BLACK, BLACKM, COMM, DBM, FILE, Comm, file_post, handle, make_app, notice, notice_handler, run
def removal(*, channel=BLACKM, message=None, file=FILE, ref="d1"): """What the autorename bot writes when its "Delete post" button is confirmed.""" lines = ["Delete the published post"] if channel is not None: lines.append(f"Channel: {channel}") if message is not None: lines.append(f"Message: {message}") if file: lines.append(f"File: {file}") if ref: lines.append(f"Ref: {ref}") return "\n".join(lines)
async def make_series(tmp_path, **cfg): """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.""" app = await make_app(tmp_path, **cfg) black = FakeChannelClient(cid=BLACK, title="Black Clover English", username="blackclover") app.tg.add_channel(black)
async def send(peer, message="", **kw): return SimpleNamespace(id=black._new(message, None, None).id)
app.tg.send_message = send return app, black
async def publish(app, black, *, ref="p1", mid=900): """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.""" db_post = file_post(app) ev = await handle(app, notice(post=db_post.id, ref=ref), mid=mid) assert ev.replies[-1].startswith("β
Post published successfully"), ev.replies (row,) = await app.db.latest_sent(BLACK) return row.message_id
class FakeDeleter: """What the userbot hands over for deleting: the posts it deletes are gone from the simulated channel."""
def __init__(self, black, *, fail=None): self.black, self.fail, self.asked, self.closed = black, fail, [], 0
async def delete(self, ids): self.asked.append(list(ids)) if self.fail is not None: raise self.fail for i in ids: self.black.msgs.pop(i, None)
async def close(self): self.closed += 1
class FakeUserbot: def __init__(self, deleter=None, *, enabled=True, ready=True, last_error=""): self.deleter, self.enabled, self.ready, self.last_error = deleter, enabled, ready, last_error
async def fallback_for(self, ch): return (self.deleter.delete, self.deleter) if self.deleter is not None else (None, None)
# ------------------------------------------------------------------------------------------------ the messagedef test_the_delete_message_is_read_line_by_line(): n = parse_delete_notice(removal(message=57)) assert n == DeleteNotice(channel=BLACKM, channel_raw=str(BLACKM), message_id=57, file=FILE, ref="d1") again = parse_delete_notice(" DELETE the Published Post\nchannel : -100123\nmessage:5\nREF: x") assert (again.channel, again.message_id, again.file, again.ref) == (-100123, 5, "", "x")
def test_it_must_begin_with_the_words_and_is_not_an_upload_notice(): assert parse_delete_notice("Please delete the published post\nChannel: -100123\nMessage: 5") is None assert parse_delete_notice("Message received\nDelete the published post") is None assert parse_delete_notice(None) is None and parse_delete_notice("") is None assert parse_delete_notice(notice(post=3)) is None # an upload notice is no deletion ... assert parse_notice(removal(message=3)) is None # ... and a deletion is no upload notice
@pytest.mark.parametrize("message", ["", "abc", "12 34", "-5", "1" * 13])def test_a_message_id_that_is_no_number_is_none(message): assert parse_delete_notice(f"Delete the published post\nChannel: {BLACKM}\nMessage: {message}").message_id is None
# ----------------------------------------------------------------------------------------- the post names its iddef test_the_published_reply_names_the_message_id_of_the_post(tmp_path): async def go(): app, black = await make_series(tmp_path) ev = await handle(app, notice(post=file_post(app).id, ref="p1")) (row,) = await app.db.latest_sent(BLACK) done = ev.replies[-1] assert f"\nMessage: {row.message_id}\n" in done and f"Post: https://t.me/blackclover/{row.message_id}\n" in done assert row.message_id in black.msgs await app.db.close()
run(go())
# ---------------------------------------------------------------------------------------------- the deletiondef test_the_post_is_deleted_in_the_channel_and_in_my_posts(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) assert msg_id in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is not None ev = await handle(app, removal(message=msg_id), mid=2) assert ev.replies[0] == "π₯ Message received - deleting the postβ¦\nRef: d1" assert len(ev.replies) == 2 done = ev.replies[1] assert done.startswith("π Post deleted successfully") for part in ("Channel: Black Clover English", f"Message: {msg_id}", f"File: {FILE}", "Ref: d1"): assert part in done, done assert ev.kw == {"parse_mode": None, "link_preview": False} assert msg_id not in black.msgs and black.delete_requests == [[msg_id]] assert await app.db.find_by_message(BLACK, msg_id) is None assert (await app.db.list_posts(BLACK, None, 0, 10))[1] == 0 # not in My posts any more assert app.tg.delete_requests == [] and app.tg.msgs # the Database Channel was not touched await app.db.close()
run(go())
def test_only_the_named_post_goes(tmp_path): async def go(): app, black = await make_series(tmp_path) first = await publish(app, black, ref="p1", mid=1) second_file = file_post(app, "Black Clover - S2 E06.mkv") await handle(app, notice(post=second_file.id, episode="06", file="Black Clover - S2 E06.mkv", ref="p2"), mid=2) rows = await app.db.latest_sent(BLACK) second = next(r.message_id for r in rows if r.message_id != first) await handle(app, removal(message=first), mid=3) assert first not in black.msgs and second in black.msgs assert [r.message_id for r in await app.db.latest_sent(BLACK)] == [second] await app.db.close()
run(go())
def test_what_hangs_on_the_post_goes_with_it(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) await app.db.schedule_deletes( [dict(channel_id=BLACK, message_id=msg_id, delete_at=utcnow() + datetime.timedelta(days=1), group_id="g", created_by=1)] ) await app.db.ignore_post(BLACK, msg_id) await handle(app, removal(message=msg_id), mid=2) assert await app.db.pending_deletes() == [] and msg_id not in await app.db.ignored_ids(BLACK) await app.db.close()
run(go())
def test_a_post_that_was_deleted_by_hand_is_removed_from_my_posts(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) del black.msgs[msg_id] # deleted in Telegram: My posts does not know yet ev = await handle(app, removal(message=msg_id), mid=2) assert ev.replies[-1].startswith("π Post deleted successfully") assert await app.db.find_by_message(BLACK, msg_id) is None await app.db.close()
run(go())
def test_a_post_that_is_gone_everywhere_counts_as_deleted(tmp_path): """Pressing the button twice, or deleting the post in My posts first, must not end in a failure.""" async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) await handle(app, removal(message=msg_id, ref="a"), mid=2) again = await handle(app, removal(message=msg_id, ref="b"), mid=3) assert again.replies[-1].startswith("π Post deleted successfully") assert "βΉοΈ The post was already gone from the channel and from My posts." in again.replies[-1] assert "Ref: b" in again.replies[-1] and black.delete_requests == [[msg_id]] # nothing was asked of Telegram twice await app.db.close()
run(go())
def test_a_message_that_is_not_in_my_posts_but_still_in_the_channel_is_left_alone(tmp_path): async def go(): app, black = await make_series(tmp_path) by_hand = black._new("somebody's own post", None, None).id ev = await handle(app, removal(message=by_hand)) failed = ev.replies[-1] assert failed.startswith("β Deletion failed: ") and f"Message {by_hand} of βBlack Clover Englishβ is not one of the posts" in failed assert "so I did not delete it" in failed and f"File: {FILE}" in failed and "Ref: d1" in failed assert by_hand in black.msgs and black.delete_requests == [] await app.db.close()
run(go())
@pytest.mark.parametrize("fields", [dict(created_by=1, source="bot"), dict(created_by=0, source="adopted")])def test_a_post_that_was_not_published_automatically_is_left_alone(tmp_path, fields): """A post somebody made with the bot (or one it adopted) is deleted from My posts, never by a message in the chat.""" async def go(): app, black = await make_series(tmp_path) mid = black._new("a post made by hand", None, None).id row = await app.db.create_post( channel_id=BLACK, message_id=mid, status="sent", text="a post made by hand", entities=[], buttons=[], **fields ) ev = await handle(app, removal(message=mid)) assert "was not published automatically, so I did not delete it" in ev.replies[-1] and ev.replies[-1].startswith("β Deletion failed") assert mid in black.msgs and black.delete_requests == [] and (await app.db.get_post(row.id)) is not None await app.db.close()
run(go())
def test_a_post_the_bot_may_not_delete_stays_and_the_reason_is_given(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) black.undeletable = {msg_id} # like a post older than 48 hours ev = await handle(app, removal(message=msg_id)) failed = ev.replies[-1] assert failed.startswith("β Deletion failed: Telegram did not delete the post in βBlack Clover Englishβ.") assert "/userbot" in failed and "still in My posts" in failed and "Ref: d1" in failed assert msg_id in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is not None await app.db.close()
run(go())
def test_telegrams_refusal_is_named(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) black.delete_error = rpc("ChatAdminRequiredError") ev = await handle(app, removal(message=msg_id)) assert "Telegram refused the bot (ChatAdminRequiredError)" in ev.replies[-1] assert msg_id in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is not None await app.db.close()
run(go())
def test_the_userbot_deletes_what_the_bot_may_not(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) black.undeletable = {msg_id} deleter = FakeDeleter(black) app.ctx.userbot = FakeUserbot(deleter) ev = await handle(app, removal(message=msg_id)) done = ev.replies[-1] assert done.startswith("π Post deleted successfully") and "βΉοΈ The bot was not allowed to delete it, so the userbot did." in done assert deleter.asked == [[msg_id]] and deleter.closed == 1 # the deleter is always closed again assert msg_id not in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is None await app.db.close()
run(go())
def test_the_userbot_is_not_used_when_the_bot_can_delete(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) deleter = FakeDeleter(black) app.ctx.userbot = FakeUserbot(deleter) ev = await handle(app, removal(message=msg_id)) assert ev.replies[-1].startswith("π Post deleted successfully") and "userbot" not in ev.replies[-1] assert deleter.asked == [] and deleter.closed == 1 await app.db.close()
run(go())
def test_a_userbot_that_cannot_delete_is_explained(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) black.undeletable = {msg_id} deleter = FakeDeleter(black, fail=RuntimeError("no right")) app.ctx.userbot = FakeUserbot(deleter) ev = await handle(app, removal(message=msg_id)) assert "The userbot could not help: no right" in ev.replies[-1] and ev.replies[-1].startswith("β Deletion failed") assert deleter.closed == 1 and msg_id in black.msgs and (await app.db.find_by_message(BLACK, msg_id)) is not None await app.db.close()
run(go())
def test_a_userbot_that_is_not_connected_is_named(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) black.undeletable = {msg_id} app.ctx.userbot = FakeUserbot(None, ready=False, last_error="session expired") ev = await handle(app, removal(message=msg_id)) assert "The userbot is not connected: session expired" in ev.replies[-1] await app.db.close()
run(go())
# ------------------------------------------------------------------------------------ what cannot be deleted@pytest.mark.parametrize( "text, complaint", [ (removal(channel=None, message=5), "does not say which channel the post is in: it has no βChannel:β line"), (removal(channel="Black Clover", message=5), "names βBlack Cloverβ as the channel, which is not a channel id"), (removal(channel=DBM, message=5), "is the Database Channel itself - this bot only deletes the posts it made in the channel of the series"), (removal(channel=-1009999999999, message=5), "-1009999999999 is not connected to this bot"), (removal(message=None), "does not say which post to delete: it has no βMessage:β line"), ],)def test_a_message_that_cannot_work_is_refused_with_its_reason_and_nothing_is_touched(tmp_path, text, complaint): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) ev = await handle(app, text, mid=2) assert ev.replies[-1].startswith("β Deletion failed: ") and complaint in ev.replies[-1] and "Ref: d1" in ev.replies[-1] assert msg_id in black.msgs and black.delete_requests == [] and app.tg.delete_requests == [] assert (await app.db.find_by_message(BLACK, msg_id)) is not None await app.db.close()
run(go())
def test_a_channel_that_is_not_connected_any_more_cannot_be_deleted_in(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) await app.db.set_channel_active(BLACK, False) ev = await handle(app, removal(message=msg_id)) 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] assert msg_id in black.msgs await app.db.close()
run(go())
def test_when_telegram_cannot_be_asked_the_reason_is_reported(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) black.fail["GetMessagesRequest"] = rpc("ChannelPrivateError") # the bot cannot read the channel at all ev = await handle(app, removal(message=msg_id, ref="a"), mid=2) assert ev.replies[-1].startswith("β Deletion failed: Telegram refused to look at the post in βBlack Clover Englishβ") assert (await app.db.find_by_message(BLACK, msg_id)) is not None await app.db.delete_post((await app.db.find_by_message(BLACK, msg_id)).id) # (not in My posts any more: the other path) ev = await handle(app, removal(message=msg_id, ref="b"), mid=3) assert ev.replies[-1].startswith("β Deletion failed: I could not look at the post in βBlack Clover Englishβ") await app.db.close()
run(go())
# ---------------------------------------------------------------------------------------- the conversationdef test_something_unexpected_still_gets_an_answer(tmp_path): async def go(): app, black = await make_series(tmp_path)
async def boom(notice): raise RuntimeError("kaput")
app.ctx.publisher.delete = boom ev = await handle(app, removal(message=5)) assert ev.replies[-1].startswith("β Deletion failed: something went wrong inside the bot (RuntimeError: kaput)") assert "Ref: d1" in ev.replies[-1] await app.db.close()
run(go())
def test_the_same_message_is_answered_once(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) first = await handle(app, removal(message=msg_id), mid=7) again = await handle(app, removal(message=msg_id), mid=7) # delivered twice assert len(first.replies) == 2 and again.replies == [] await app.db.close()
run(go())
def test_a_deletion_waits_for_the_post_that_is_being_made(tmp_path): """One thing at a time: the answer "received" comes at once, the deletion when the lock is free.""" async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) pub = app.ctx.publisher await pub.lock.acquire() ev = Comm(removal(message=msg_id), mid=5) task = asyncio.ensure_future(pub.handle(ev)) await asyncio.sleep(0.5) # (the database answers from another thread: that takes real time) assert len(ev.replies) == 1 and ev.replies[0].startswith("π₯ Message received") and msg_id in black.msgs pub.lock.release() await task assert len(ev.replies) == 2 and ev.replies[1].startswith("π Post deleted successfully") and msg_id not in black.msgs await app.db.close()
run(go())
def test_the_listener_deletes_only_for_the_autorename_bot_in_the_communication_chat(tmp_path): async def go(): app, black = await make_series(tmp_path) msg_id = await publish(app, black) fn = notice_handler(app) elsewhere = Comm(removal(message=msg_id), mid=2, chat=-1000000000555) stranger = Comm(removal(message=msg_id), mid=3, sender=12345) await fn(elsewhere) await fn(stranger) assert elsewhere.replies == [] and stranger.replies == [] and msg_id in black.msgs good = Comm(removal(message=msg_id), mid=4) await fn(good) assert len(good.replies) == 2 and good.replies[1].startswith("π Post deleted successfully") and msg_id not in black.msgs assert good.chat_id == COMM await app.db.close()
run(go())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Only the Share URL: the autorename bot asks for the link of a file in the Database Channel; nothing is published."""from app.dbpublish import LinkNotice, parse_link_notice, parse_notice, parse_delete_notice
from .test_dbpublish import FILE_LINK, FakeReader, FakeUserbot, file_post, handle, make_app, notice, run
def ask(post=None, ref="l1"): lines = ["Get the share URL"] if post is not None: lines.append(f"Post: {post}") if ref: lines.append(f"Ref: {ref}") return "\n".join(lines)
def test_the_message_is_read_and_is_nothing_else(): assert parse_link_notice(ask(7)) == LinkNotice(post_id=7, ref="l1") assert parse_link_notice("GET the Share URL\npost : x").post_id is None assert parse_link_notice("please get the share url\nPost: 7") is None and parse_link_notice(None) is None assert parse_notice(ask(7)) is None and parse_delete_notice(ask(7)) is None and parse_link_notice(notice(post=3)) is None
def test_the_link_is_returned_and_nothing_is_posted(tmp_path): async def go(): app = await make_app(tmp_path) post = file_post(app) ev = await handle(app, ask(post.id)) assert ev.replies[0] == "π₯ Message received - looking for the Share URLβ¦\nRef: l1" assert ev.replies[1] == f"π Share URL ready\nURL: {FILE_LINK}\nRef: l1" assert not app.tg.sent and not app.tg.requests await app.db.close()
run(go())
def test_the_userbot_reads_it_when_the_bot_cannot_see_the_button(tmp_path): async def go(): app = await make_app(tmp_path) hidden = file_post(app, buttons=False) seen = file_post(app) reader = FakeReader(app.clock, {hidden.id: seen}) app.ctx.userbot = FakeUserbot(reader) ev = await handle(app, ask(hidden.id)) assert ev.replies[-1].startswith("π Share URL ready") and "read through the userbot" in ev.replies[-1] await app.db.close()
run(go())
def test_failures_are_reported(tmp_path): async def go(): app = await make_app(tmp_path) none = await handle(app, ask(None), mid=2) assert "no βPost:β line" in none.replies[-1] and none.replies[-1].startswith("β Share URL failed: ") bare = file_post(app, buttons=False) no_button = await handle(app, ask(bare.id), mid=3) assert "No π Share URL button" in no_button.replies[-1] and "Ref: l1" in no_button.replies[-1] await app.db.close()
run(go())app/dbpublish.py+204-11
tests/test_dbdelete.pyAdded+429
tests/test_dblink.pyAdded+60