Commit 59598a0

benny-dou <60535774+benny-dou@users.noreply.github.com>
2025-01-22 09:55:21
feat: add `retry` cmd
1 parent 9cf8900
src/preview/douyin.py
@@ -16,7 +16,7 @@ from networking import download_first_success_urls, download_media, hx_req
 from others.emoji import emojify
 
 
-@cache.memoize(ttl=30)
+@cache.memoize(ttl=10)
 async def preview_douyin(
     client: Client,
     message: Message,
src/preview/instagram.py
@@ -18,7 +18,7 @@ from multimedia import is_valid_video, validate_img
 from networking import download_file, download_media, hx_req
 
 
-@cache.memoize(ttl=30)
+@cache.memoize(ttl=10)
 async def preview_instagram(client: Client, message: Message, url: str = "", db_key: str = "", *, fallback: bool = True, **kwargs):
     """Preview instagram link in the message.
 
src/preview/twitter.py
@@ -17,7 +17,7 @@ from networking import download_file, download_media, flatten_rediercts, hx_req
 from utils import remove_none_values, split_parts, true
 
 
-@cache.memoize(ttl=30)
+@cache.memoize(ttl=10)
 async def preview_twitter(client: Client, message: Message, url: str = "", db_key: str = "", platform: str = "", twitter_extractor: str | None = None, **kwargs):
     """Preview twitter link in the message.
 
src/preview/weibo.py
@@ -23,7 +23,7 @@ from others.emoji import emojify
 from utils import https_url, rand_string, soup_to_text, split_parts, ts_to_dt
 
 
-@cache.memoize(ttl=30)
+@cache.memoize(ttl=10)
 async def preview_weibo(client: Client, message: Message, url: str, post_id: str = "", *, fetch_weibo_comments: bool = True, fallback: bool = True, **kwargs):
     """Preview weibo link in the message.
 
src/preview/xiaohongshu.py
@@ -18,7 +18,7 @@ from networking import download_file, download_first_success_urls, download_medi
 from others.emoji import emojify
 
 
-@cache.memoize(ttl=30)
+@cache.memoize(ttl=10)
 async def preview_xhs(client: Client, message: Message, url: str = "", db_key: str = "", *, fallback: bool = True, **kwargs):
     """Preview xiaohongshu link in the message.
 
src/database.py
@@ -217,8 +217,7 @@ async def del_db(key: str):
 def del_memory_kv(key: str):
     """Delete from memory cache."""
     key = quote_plus(key)
-    if cache.get(key):
-        cache.delete(key)
+    cache.delete(key)
 
 
 async def del_cf_kv(key: str):
src/handler.py
@@ -8,6 +8,7 @@ from pyrogram.types import Message
 from asr.voice_recognition import voice_to_text
 from bridge.miaomiao import ocr_to_miaomiao
 from config import ENABLE, PREFIX, PROXY, cache
+from database import del_db
 from message_utils import equal_prefix, parse_msg, send2tg, startswith_prefix
 from networking import flatten_rediercts, match_social_media_link
 from others.download_external import download_url_in_message
@@ -80,7 +81,7 @@ async def handle_social_media(
     reply_msg_id: int = 0,
     *,
     need_prefix: bool = True,
-    extra_prefix: list[str] | None = None,
+    cmd_prefix: list[str] | None = None,
     ignore_prefix: list[str] | None = None,
     prepend_sender_user: bool = False,
     douyin: bool = True,
@@ -105,28 +106,35 @@ async def handle_social_media(
                                              If set to 0, reply to the trigger message itself.
                                              If set to -1, do not send as a reply message.
         need_prefix (bool, optional): Need to start with PREFIX to call this funciton. Defaults to True.
-        extra_prefix (list[str], optional): Extra prefix to call this function. Defaults to None.
+        cmd_prefix (list[str], optional): Extra prefix to call this function. Defaults to None.
         ignore_prefix (list[str], optional): Ignore prefix to call this function. Defaults to None.
         prepend_sender_user (bool, optional): Prepend the sender's username to the message. Defaults to False.
         show_progress (bool, optional): Show a progress message on Telegram. Defaults to True.
         detail_progress (bool, optional): Show detailed progress (Only if show_proress is set to True). Defaults to False.
     """
     kwargs |= {"target_chat": target_chat, "reply_msg_id": reply_msg_id, "show_progress": show_progress, "detail_progress": detail_progress}
+    if cmd_prefix is None:
+        cmd_prefix = [PREFIX.MAIN]
+    else:
+        cmd_prefix.append(PREFIX.MAIN)
+    ignore_prefix = ignore_prefix or []
     info = parse_msg(message)
-    if need_prefix and not startswith_prefix(message, extra_prefix=extra_prefix, ignore_prefix=ignore_prefix):
-        return
-    # send docs if message only contains prefix command, without reply
-    if equal_prefix(message, extra_prefix=extra_prefix, ignore_prefix=ignore_prefix) and not message.reply_to_message:
-        help_msg = get_social_media_help(extra_prefix=extra_prefix, ignore_prefix=ignore_prefix)
-        await send2tg(client, message, texts=help_msg, **kwargs)
+    this_texts = message.text or message.caption or ""  # texts of the trigger message
+    if need_prefix and not startswith_prefix(this_texts, prefix=[*cmd_prefix, "/retry"], ignore_prefix=ignore_prefix):
         return
 
-    # use /PREFIX to reply a message, treat the reply_msg as the trigger to preview social media link
-    if equal_prefix(message, extra_prefix=extra_prefix, ignore_prefix=ignore_prefix) and message.reply_to_message:
+    # message only contains prefix command
+    if equal_prefix(this_texts, prefix=[*cmd_prefix, "/retry"], ignore_prefix=ignore_prefix):
+        # without reply, send docs if message only contains prefix command
+        if not message.reply_to_message:
+            help_msg = get_social_media_help(cmd_prefix=cmd_prefix, ignore_prefix=ignore_prefix)
+            await send2tg(client, message, texts=help_msg, **kwargs)
+            return
+        # with reply, treat the reply_msg as the trigger to preview social media link
         message = message.reply_to_message
 
     warn_msg = None
-    if need_prefix and startswith_prefix(message):
+    if not need_prefix and startswith_prefix(this_texts, prefix=cmd_prefix, ignore_prefix=ignore_prefix):
         warn_msg = await send2tg(client, message, texts="⚠️本会话中可直接发送链接, 无需添加命令前缀\n⚠️No need to add command prefix in this chat.", **kwargs)
         warn_msg = warn_msg[0]
 
@@ -139,7 +147,8 @@ async def handle_social_media(
         texts = await flatten_rediercts(texts)
         matched = await match_social_media_link(texts)  # match "platform" and "url" (and other info)
         kwargs |= matched
-
+        if startswith_prefix(this_texts, prefix=["/retry"], ignore_prefix=ignore_prefix):
+            await del_db(matched["db_key"])
         if douyin and matched["platform"] == "douyin" and ENABLE.DOUYIN:
             await preview_douyin(client, message, **kwargs)
         if tiktok and matched["platform"] == "tiktok" and ENABLE.TIKTOK:
@@ -169,14 +178,15 @@ async def handle_social_media(
         logger.exception(e)
 
 
-def get_social_media_help(extra_prefix: list[str] | None = None, ignore_prefix: list[str] | None = None):
+def get_social_media_help(cmd_prefix: list[str] | None = None, ignore_prefix: list[str] | None = None):
     """Get the help message for social media preview."""
-    extra_prefix = extra_prefix or []
+    cmd_prefix = cmd_prefix or []
     ignore_prefix = ignore_prefix or []
-    prefixes = {PREFIX.MAIN, *extra_prefix} - set(ignore_prefix)
+    prefixes = set(cmd_prefix) - set(ignore_prefix)
     msg = "🔗**链接解析**"
     if prefixes:
         msg += f"\n🔗命令前缀: {', '.join(prefixes)}"
+        msg += "\n🔄使用 `/retry` 回复消息强制重试"
     if ENABLE.YOUTUBE:
         msg += "\n✅油管"
     if ENABLE.BILIBILI:
@@ -204,5 +214,5 @@ def get_social_media_help(extra_prefix: list[str] | None = None, ignore_prefix:
     if ENABLE.WGET:
         msg += f"\n⏬**下载文件**: `{PREFIX.WGET}` + URL"
     if ENABLE.OCR:
-        msg += f"\n🔁**图片转文字**: `{PREFIX.OCR}` 回复图片消息"
+        msg += f"\n🔤**图片转文字**: `{PREFIX.OCR}` 回复图片消息"
     return msg
src/main.py
@@ -49,10 +49,10 @@ async def main():
         parse_msg(message)
         if TID.GROUP67373 and message.chat.id in [int(x.strip()) for x in TID.GROUP67373.split(",")]:
             await handle_utilities(client, message, detail_progress=False)
-            await handle_social_media(client, message, extra_prefix=["/dl", "!dl", "!dl", "!下载", "!下载"], ignore_prefix=["/dl4dw"], prepend_sender_user=True)
+            await handle_social_media(client, message, cmd_prefix=["/dl", "!dl", "!dl", "!下载", "!下载"], ignore_prefix=["/dl4dw"], prepend_sender_user=True)
         else:
             await handle_utilities(client, message, detail_progress=True)
-            await handle_social_media(client, message, extra_prefix=["/dl", "!dl", "!dl"], detail_progress=True)
+            await handle_social_media(client, message, cmd_prefix=["/dl", "!dl", "!dl"], detail_progress=True)
 
     @app.on_message(filters.channel)
     async def channels(client: Client, message: Message):
@@ -61,7 +61,7 @@ async def main():
 
         parse_msg(message)
         await handle_utilities(client, message, detail_progress=True)
-        await handle_social_media(client, message, extra_prefix=["/dl", "!dl", "!dl"], detail_progress=True)
+        await handle_social_media(client, message, cmd_prefix=["/dl", "!dl", "!dl"], detail_progress=True)
 
     @app.on_message(filters.bot)
     async def bots(client: Client, message: Message):
@@ -71,7 +71,7 @@ async def main():
         await forward_results_from_parsehub(client, message)
         await forward_results_from_miaomiao(client, message)
         await handle_utilities(client, message, detail_progress=True)
-        await handle_social_media(client, message, extra_prefix=["/dl", "!dl", "!dl"], detail_progress=True)
+        await handle_social_media(client, message, cmd_prefix=["/dl", "!dl", "!dl"], detail_progress=True)
 
     # filters.private = {user chats + bot chats}
     # so the private handler should be placed after the bot handler
src/message_utils.py
@@ -13,7 +13,7 @@ from pyrogram.enums import MessageEntityType
 from pyrogram.errors import Flood
 from pyrogram.types import InputMediaPhoto, InputMediaVideo, Message, ReplyParameters
 
-from config import CAPTION_LENGTH, DB, PREFIX, TEXT_LENGTH, cache
+from config import CAPTION_LENGTH, DB, TEXT_LENGTH, cache
 from database import del_db, get_db, set_db
 from multimedia import fix_video_rotation, generate_cover, is_valid_video, parse_media_info, split_large_video, split_long_img, validate_img
 from utils import readable_size, smart_split
@@ -107,37 +107,31 @@ def parse_msg(message: Message, *, verbose: bool = False) -> dict:
 
 
 @cache.memoize(ttl=60)
-def startswith_prefix(message: Message, extra_prefix: list[str] | None = None, ignore_prefix: list[str] | None = None) -> bool:
-    """Check if the message starts with the given command prefixes.
+def startswith_prefix(text: str, prefix: list[str] | None = None, ignore_prefix: list[str] | None = None) -> bool:
+    """Check if the message text starts with the given command prefixes.
 
     Args:
-        message (Message): The message object.
-        extra_prefix (list[str], optional): Extra command prefixes that are effective.
+        text (str): The message text.
+        prefix (list[str], optional): Command prefixes that are effective.
         ignore_prefix (list[str], optional): Ignore these command prefixes.
     """
-    text = message.text or message.caption or ""
     if ignore_prefix and any(text.strip().lower().startswith(prefix) for prefix in ignore_prefix):
         return False
-    if extra_prefix and any(text.strip().lower().startswith(prefix) for prefix in extra_prefix):
-        return True
-    return text.strip().lower().startswith(PREFIX.MAIN)
+    return bool(prefix and any(text.strip().lower().startswith(prefix) for prefix in prefix))
 
 
 @cache.memoize(ttl=60)
-def equal_prefix(message: Message, extra_prefix: list[str] | None = None, ignore_prefix: list[str] | None = None) -> bool:
-    """Check if the message equal with the given command prefixes.
+def equal_prefix(text: str, prefix: list[str] | None = None, ignore_prefix: list[str] | None = None) -> bool:
+    """Check if the message text equal with the given command prefixes.
 
     Args:
-        message (Message): The message object.
-        extra_prefix (list[str], optional): Extra command prefixes that are effective.
+        text (str): The message text.
+        prefix (list[str], optional): Extra command prefixes that are effective.
         ignore_prefix (list[str], optional): Ignore these command prefixes.
     """
-    text = message.text or message.caption or ""
     if ignore_prefix and text.strip().lower() in ignore_prefix:
         return False
-    if extra_prefix and text.strip().lower() in extra_prefix:
-        return True
-    return text.strip().lower() == PREFIX.MAIN
+    return bool(prefix and text.strip().lower() in prefix)
 
 
 def warp_media_group(media: list[dict], caption: str = "") -> list: