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