Commit 1f72e3a

benny-dou <60535774+benny-dou@users.noreply.github.com>
2025-01-22 17:34:45
feat: add options parsing in message text
1 parent d4b7de9
Changed files (2)
src/handler.py
@@ -1,6 +1,9 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
 
+import contextlib
+import re
+
 from loguru import logger
 from pyrogram.client import Client
 from pyrogram.types import Message
@@ -21,6 +24,7 @@ from preview.twitter import preview_twitter
 from preview.weibo import preview_weibo
 from preview.xiaohongshu import preview_xhs
 from preview.ytdlp import ProxyError, get_ytdlp_proxy, preview_ytdlp
+from utils import true
 
 
 @cache.memoize(ttl=60)
@@ -122,7 +126,10 @@ async def handle_social_media(
     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
-
+    kwargs |= params_from_msg_text(this_texts)  # merge the parameters from the message text
+    if true(kwargs.get("target_chat")):
+        with contextlib.suppress(ValueError):
+            kwargs["target_chat"] = int(kwargs["target_chat"])
     # 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
@@ -178,6 +185,45 @@ async def handle_social_media(
         logger.exception(e)
 
 
+def params_from_msg_text(texts: str | None = None) -> dict:
+    """Get the parameters from the message text.
+
+    Texts can contain some special words to temporarily enable / disable some features.
+    The parsed options will be merged into kwargs.
+
+    Currently, three formats are supported:
+    1. #no_xx: kwargs["xx"] = False
+    2. #with_xx: kwargs["xx"] = True
+    3. #set_xx=var: kwargs["xx"] = var
+
+    Example text: #no_fetch_douyin_comments #set_douyin_extractor=tikhub
+
+    Args:
+        texts (str | None, optional): The message text.
+    """
+    params = {}
+    if not texts:
+        return params
+
+    # Pattern 1: #no_xx -> kwargs["xx"] = False
+    for match in re.findall(r"#no_(\w+)", texts, re.IGNORECASE):
+        params[match.lower()] = False
+
+    # Pattern 2: #with_xx -> kwargs["xx"] = True
+    for match in re.findall(r"#with_(\w+)", texts, re.IGNORECASE):
+        params[match.lower()] = True
+
+    # Pattern 3: #set_xx=var -> kwargs["xx"] = var
+    for match in re.findall(r"#set_(\w+)=([^,,.怂#\s]+)", texts, re.IGNORECASE):  # noqa: RUF001
+        key, value = match
+        if str(value).lower() in ["none", "null"]:
+            value = None
+        params[key.lower()] = value
+    if params:
+        logger.info(f"šŸ”§ę‰‹åŠØč®¾ē½®å‚ę•°: {params}")
+    return params
+
+
 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."""
     cmd_prefix = cmd_prefix or []
@@ -216,3 +262,7 @@ def get_social_media_help(cmd_prefix: list[str] | None = None, ignore_prefix: li
     if ENABLE.OCR:
         msg += f"\nšŸ”¤**图片转文字**: `{PREFIX.OCR}` å›žå¤å›¾ē‰‡ę¶ˆęÆ"
     return msg
+
+
+if __name__ == "__main__":
+    params_from_msg_text("#with_1 #WITH_x #NO_1 #no_2 #set_yy=3, #no_fetch_douyin_comments #set_douyin_extractor=tikhub #set_reply_msg_id=None")
src/message_utils.py
@@ -290,6 +290,8 @@ async def send2tg(
 
     if not target_chat:
         target_chat = kwargs["target_chat"] if kwargs.get("target_chat") else message.chat.id
+    with contextlib.suppress(ValueError):
+        target_chat = int(target_chat)
     if reply_msg_id == 0:
         reply_to = message.id
     elif reply_msg_id == -1: