From 9726945b25ad6ac4818499b8fb8bdb54c99bc88c Mon Sep 17 00:00:00 2001 From: youpaishidifu Date: Mon, 31 Aug 2026 23:39:38 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=98=B2=E5=BE=A1=E6=80=A7=E7=BC=96?= =?UTF-8?q?=E7=A8=8B=E7=A1=AE=E4=BF=9Dkeyword=5Fscores=E8=A1=A8=E5=AD=98?= =?UTF-8?q?=E5=9C=A8=EF=BC=8C=E8=A7=A3=E5=86=B3no=20such=20table=E9=94=99?= =?UTF-8?q?=E8=AF=AF=20(Task=20#1657)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- _keyword_scorer.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/_keyword_scorer.py b/_keyword_scorer.py index e44bb03..228b83f 100644 --- a/_keyword_scorer.py +++ b/_keyword_scorer.py @@ -56,6 +56,38 @@ class KeywordScorer: conn.close() logger.debug(f"[keyword-scorer] DB初始化完成: {self.db_path}") + def _ensure_keyword_scores_table(self): + """确保keyword_scores表存在(防御性编程)""" + conn = sqlite3.connect(self.db_path, check_same_thread=False) + try: + cursor = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='keyword_scores'") + if not cursor.fetchone(): + logger.warning("[keyword-scorer] keyword_scores表不存在,重新创建") + conn.execute(""" + CREATE TABLE IF NOT EXISTS keyword_scores ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + platform TEXT NOT NULL, + message_text TEXT NOT NULL, + message_hash TEXT NOT NULL, + score INTEGER NOT NULL DEFAULT 0, + matched_keywords TEXT NOT NULL DEFAULT '', + local_time TIMESTAMP NOT NULL, + is_new_message INTEGER NOT NULL DEFAULT 1 + ) + """) + conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_keyword_scores_platform_time + ON keyword_scores(platform, local_time) + """) + conn.execute(""" + CREATE INDEX IF NOT EXISTS idx_keyword_scores_hash + ON keyword_scores(message_hash) + """) + conn.commit() + logger.warning("[keyword-scorer] keyword_scores表已重新创建") + finally: + conn.close() + def extract_keywords(self, text: str) -> List[str]: """提取两字一组的关键词 @@ -110,6 +142,9 @@ class KeywordScorer: if not keywords: return 0, [] + # 防御性编程:确保表存在 + self._ensure_keyword_scores_table() + conn = sqlite3.connect(self.db_path, check_same_thread=False) try: # 获取最近N分钟的bot回复关键词 @@ -168,6 +203,9 @@ class KeywordScorer: matched_keywords: 匹配到的关键词 is_new: 是否为新消息(score<=1为True) """ + # 防御性编程:确保表存在 + self._ensure_keyword_scores_table() + import hashlib message_hash = hashlib.md5(message_text.strip().encode('utf-8')).hexdigest() local_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") @@ -192,6 +230,8 @@ class KeywordScorer: keywords = self.extract_keywords(text) if not keywords: return 0 + # 防御性编程:确保表存在 + self._ensure_keyword_scores_table() conn = sqlite3.connect(self.db_path, check_same_thread=False) try: cursor = conn.execute(""" @@ -272,6 +312,9 @@ class KeywordScorer: exclude_id: 排除刚插入的当前消息记录id(防止自拦截) """ + # 防御性编程:确保表存在 + self._ensure_keyword_scores_table() + import hashlib from datetime import timedelta