Commit 572652d

benny-dou <60535774+benny-dou@users.noreply.github.com>
2025-03-14 13:03:14
refactor: remove unnecessary cache
1 parent 3e7e6e7
src/asr/voice_recognition.py
@@ -9,7 +9,7 @@ from pyrogram.client import Client
 from pyrogram.types import Message
 
 from asr.tecent_asr import Credential, FlashRecognitionRequest, FlashRecognizer
-from config import ASR_MAX_DURATION, CAPTION_LENGTH, PREFIX, TOKEN, cache
+from config import ASR_MAX_DURATION, CAPTION_LENGTH, PREFIX, TOKEN
 from messages.parser import parse_msg
 from messages.progress import modify_progress
 from messages.sender import send2tg, send_texts
@@ -67,7 +67,6 @@ ENGINE_MAP = {
 BEGINNING = "🗣语音转文字:"
 
 
-@cache.memoize(ttl=30)
 async def voice_to_text(
     client: Client,
     message: Message,
@@ -186,7 +185,6 @@ async def voice_to_text(
             await message.delete()
 
 
-@cache.memoize(ttl=10)
 def get_trigger_message(
     message: Message,
     asr_need_prefix: bool | None = None,
src/bridge/chartimg.py
@@ -13,7 +13,6 @@ from utils import i_am_bot, to_int
 CHART_BOT = "chartImgBot"
 
 
-@cache.memoize(ttl=10)
 async def send_to_chartimg_bridge(client: Client, message: Message, symbol: str, interval: str, target_chat: int | str | None = None, reply_msg_id: int = 0, **kwargs):  # noqa: ARG001
     """This bridge is now deprecated. We use API from https://chart-img.com to get the chart directly.
 
@@ -47,7 +46,6 @@ async def send_to_chartimg_bridge(client: Client, message: Message, symbol: str,
     await client.send_message(chat_id=f"@{CHART_BOT}", text=f"/chart {params['text']}")
 
 
-@cache.memoize(ttl=10)
 async def forward_chartimg_results(client: Client, message: Message):
     """See docs in `bridge/README.md` for details."""
     if message.from_user.username != CHART_BOT or not message.photo:
src/bridge/ocr.py
@@ -7,7 +7,7 @@ from loguru import logger
 from pyrogram.client import Client
 from pyrogram.types import Message, ReplyParameters
 
-from config import PREFIX, cache
+from config import PREFIX
 from messages.parser import parse_msg
 from messages.sender import send2tg
 from messages.utils import equal_prefix, startswith_prefix
@@ -16,7 +16,6 @@ from utils import i_am_bot
 OCR_BOT = "GLBetabot"
 
 
-@cache.memoize(ttl=10)
 async def send_to_ocr_bridge(client: Client, message: Message, **kwargs):
     """Send photo to miaomiao bot for OCR.
 
@@ -56,7 +55,6 @@ async def send_to_ocr_bridge(client: Client, message: Message, **kwargs):
     await client.send_photo(chat_id=f"@{OCR_BOT}", photo=file_id, caption=msg)
 
 
-@cache.memoize(ttl=10)
 async def forward_ocr_results(client: Client, message: Message):
     """See docs in `bridge/README.md` for details."""
     if message.from_user.username != OCR_BOT or not message.reply_to_message:
src/bridge/social.py
@@ -24,7 +24,6 @@ SOCIAL_BOTS = {
 }
 
 
-@cache.memoize(ttl=10)
 async def send_to_social_media_bridge(client: Client, message: Message, url: str, platform: str, **kwargs):
     """See docs in `bridge/README.md` for details."""
     if await i_am_bot(client):  # bot can't send message to other bots
@@ -52,7 +51,6 @@ async def send_to_social_media_bridge(client: Client, message: Message, url: str
             await client.send_message(chat_id=f"@{bot}", text=url)
 
 
-@cache.memoize(ttl=10)
 async def forward_social_media_results(client: Client, message: Message):
     """See docs in `bridge/README.md` for details.
 
src/bridge/utils.py
@@ -1,26 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-from pyrogram.client import Client
-
-from config import cache
-from utils import to_int
-
-
-@cache.memoize(ttl=3)
-async def get_recent_msg_from_me(client: Client, chat_id: int | str, opponent_id: int, idx: int = 1) -> str:
-    """Get the last message from me in the chat.
-
-    Args:
-        client (Client): The Pyrogram client.
-        chat_id (int | str): The chat id.
-        opponent_id (int): The opponent id.
-        idx (int): The index of the message to get. 1 for the last message, 2 for the second last message, etc.
-    """
-    hit = 0
-    async for message in client.get_chat_history(to_int(chat_id), limit=20):  # type: ignore
-        if message.from_user.id != opponent_id:
-            hit += 1
-            if hit == idx:
-                return message.text or message.caption or ""
-    return ""
src/llm/gpt.py
@@ -51,7 +51,6 @@ def is_gpt_conversation(message: Message) -> bool:
     return startswith_prefix(reply_info["text"], prefix=[f"🤖{x}".lower() for x in model_names])
 
 
-@cache.memoize(ttl=60)
 async def gpt_response(client: Client, message: Message, *, gpt_stream: bool = GPT.STREAM_MODE, **kwargs):
     """Get GPT response from Various API.
 
src/llm/summary.py
@@ -7,7 +7,7 @@ from zoneinfo import ZoneInfo
 from pyrogram.client import Client
 from pyrogram.types import Message
 
-from config import GPT, MAX_MESSAGE_SUMMARY, PREFIX, TZ, cache
+from config import GPT, MAX_MESSAGE_SUMMARY, PREFIX, TZ
 from llm.models import get_model_config_with_contexts
 from llm.prompts import refine_prompts
 from llm.response import send_to_gpt
@@ -53,7 +53,6 @@ HELP = f"""🤖**GPT总结历史消息** (最多{MAX_MESSAGE_SUMMARY}条)
 """
 
 
-@cache.memoize(ttl=60)
 async def ai_summary(client: Client, message: Message, **kwargs):
     """GPT summary of the message history.
 
src/messages/chat_history.py
@@ -6,11 +6,10 @@ from zoneinfo import ZoneInfo
 
 from pyrogram.client import Client
 
-from config import MAX_MESSAGE_RETRIEVED, TZ, cache
+from config import MAX_MESSAGE_RETRIEVED, TZ
 from messages.parser import parse_msg
 
 
-@cache.memoize(ttl=10)
 async def get_parsed_chat_history(
     client: Client,
     chat_id: int | str,
src/messages/utils.py
@@ -8,11 +8,10 @@ from pyrogram.parser.markdown import BLOCKQUOTE_EXPANDABLE_DELIM, BLOCKQUOTE_EXP
 from pyrogram.parser.parser import Parser
 from pyrogram.types import ReplyParameters
 
-from config import TEXT_LENGTH, cache
+from config import TEXT_LENGTH
 from utils import readable_size, to_int
 
 
-@cache.memoize(ttl=60)
 def startswith_prefix(text: str | None = None, prefix: list[str] | None = None, ignore_prefix: list[str] | None = None) -> bool:
     """Check if the message text starts with the given command prefixes.
 
@@ -28,7 +27,6 @@ def startswith_prefix(text: str | None = None, prefix: list[str] | None = None,
     return bool(prefix and any(text.strip().lower().startswith(prefix) for prefix in prefix))
 
 
-@cache.memoize(ttl=60)
 def equal_prefix(text: str | None = None, prefix: list[str] | None = None, ignore_prefix: list[str] | None = None) -> bool:
     """Check if the message text equal with the given command prefixes.
 
src/others/extract_audio.py
@@ -6,7 +6,7 @@ from loguru import logger
 from pyrogram.client import Client
 from pyrogram.types import Message
 
-from config import PREFIX, cache
+from config import PREFIX
 from messages.parser import parse_msg
 from messages.progress import modify_progress
 from messages.sender import send2tg
@@ -24,7 +24,6 @@ HELP = f"""
 """
 
 
-@cache.memoize(ttl=60)
 async def extract_audio_file(client: Client, message: Message, **kwargs) -> None:
     """Extract audio from video message."""
     # send docs if message == "/audio", without reply
src/others/subtitle.py
@@ -30,7 +30,6 @@ HELP = f"""📃**提取字幕**
 """
 
 
-@cache.memoize(ttl=30)
 async def get_subtitle(client: Client, message: Message, **kwargs):
     """Get YouTube Subtitle."""
     target_chat = kwargs["target_chat"] if kwargs.get("target_chat") else message.chat.id
src/preview/douyin.py
@@ -11,7 +11,7 @@ from pyrogram.parser.markdown import BLOCKQUOTE_EXPANDABLE_DELIM
 from pyrogram.types import Message
 
 from bridge.social import send_to_social_media_bridge
-from config import API, DB, PROVIDER, PROXY, TOKEN, TZ, cache
+from config import API, DB, PROVIDER, PROXY, TOKEN, TZ
 from database import get_db
 from messages.database import copy_messages_from_db, save_messages
 from messages.progress import modify_progress
@@ -22,7 +22,6 @@ from others.emoji import emojify
 from utils import true
 
 
-@cache.memoize(ttl=10)
 async def preview_douyin(
     client: Client,
     message: Message,
src/preview/instagram.py
@@ -12,7 +12,7 @@ from pyrogram.parser.markdown import BLOCKQUOTE_EXPANDABLE_DELIM
 from pyrogram.types import Message
 
 from bridge.social import send_to_social_media_bridge
-from config import API, DB, DOWNLOAD_DIR, PROVIDER, PROXY, TELEGRAM_UA, TOKEN, TZ, cache
+from config import API, DB, DOWNLOAD_DIR, PROVIDER, PROXY, TELEGRAM_UA, TOKEN, TZ
 from database import get_db
 from messages.database import copy_messages_from_db, save_messages
 from messages.progress import modify_progress
@@ -23,7 +23,6 @@ from networking import download_file, download_media, hx_req
 from utils import true
 
 
-@cache.memoize(ttl=10)
 async def preview_instagram(
     client: Client,
     message: Message,
@@ -105,7 +104,6 @@ async def preview_instagram(
     await save_messages(messages=sent_messages, key=db_key)
 
 
-@cache.memoize(ttl=30)
 async def preview_ddinstagram(client: Client, message: Message, url: str, post_type: str, post_id: str, *, fallback: bool = True, **kwargs):
     """Preview instagram link in the message via DDInstagram.
 
src/preview/twitter.py
@@ -22,7 +22,6 @@ from networking import download_file, download_media, flatten_rediercts, hx_req
 from utils import remove_none_values, split_parts, true
 
 
-@cache.memoize(ttl=10)
 async def preview_twitter(
     client: Client,
     message: Message,
src/preview/weibo.py
@@ -27,7 +27,6 @@ from others.emoji import emojify
 from utils import https_url, rand_string, soup_to_text, split_parts, true, ts_to_dt
 
 
-@cache.memoize(ttl=10)
 async def preview_weibo(
     client: Client,
     message: Message,
src/preview/xiaohongshu.py
@@ -10,7 +10,7 @@ from pyrogram.client import Client
 from pyrogram.types import Message
 
 from bridge.social import send_to_social_media_bridge
-from config import DB, PROXY, TZ, cache
+from config import DB, PROXY, TZ
 from database import get_db
 from messages.database import copy_messages_from_db, save_messages
 from messages.progress import modify_progress
@@ -20,7 +20,6 @@ from networking import download_file, download_first_success_urls, download_medi
 from others.emoji import emojify
 
 
-@cache.memoize(ttl=10)
 async def preview_xhs(client: Client, message: Message, url: str = "", db_key: str = "", xsec: str = "", *, fallback: bool = True, **kwargs):
     """Preview xiaohongshu link in the message.
 
src/preview/ytdlp.py
@@ -37,7 +37,6 @@ class ProxyError(Exception):
     pass
 
 
-@cache.memoize(ttl=30)
 async def preview_ytdlp(
     client: Client,
     message: Message,
src/price/entrypoint.py
@@ -65,7 +65,6 @@ K线Interval (可选):
 """
 
 
-@cache.memoize(ttl=60)
 async def get_asset_price(client: Client, message: Message, **kwargs):
     """Get asset price."""
     info = parse_msg(message)
src/handler.py
@@ -9,7 +9,7 @@ from pyrogram.types import Message
 
 from asr.voice_recognition import voice_to_text
 from bridge.ocr import send_to_ocr_bridge
-from config import ENABLE, PREFIX, PROXY, cache
+from config import ENABLE, PREFIX, PROXY
 from database import del_db
 from llm.gpt import gpt_response
 from llm.summary import ai_summary
@@ -33,7 +33,6 @@ from price.entrypoint import get_asset_price
 from utils import to_int, true
 
 
-@cache.memoize(ttl=60)
 async def handle_utilities(
     client: Client,
     message: Message,
@@ -99,7 +98,6 @@ async def handle_utilities(
         await convert_raw_img_file(client, message, **kwargs)
 
 
-@cache.memoize(ttl=60)
 async def handle_social_media(
     client: Client,
     message: Message,
src/utils.py
@@ -219,14 +219,16 @@ def ts_to_dt(ts: str | float | None) -> datetime | None:
         return None
 
 
-@cache.memoize(ttl=0)
 async def i_am_bot(client: Client) -> bool:
     """Check if this clinet is a bot or not."""
+    if cache.get("i_am_bot"):
+        return cache.get("i_am_bot")
     try:
         me = await client.get_me()
     except Exception as e:
         logger.error(e)
         return False
+    cache.set("i_am_bot", me.is_bot)
     return me.is_bot