优化关键词过滤器的匹配和删除逻辑

更新了bot_commands.py和link_filter.py,以改进关键词匹配和删除逻辑。现在在添加和删除关键词时,系统会考虑关键词中可能包含空格的情况。此外,处理删除操作时,对于不存在的确切匹配关键词,系统将提示可能相似的关键词供用户选择是否删除。在link_filter.py中,提高了should_filter方法的匹配效率。这些改进增强了关键词过滤器功能的鲁棒性和用户体验。
This commit is contained in:
wood 2024-09-04 17:41:40 +08:00
parent 7aac6c3a23
commit cec72f173c
2 changed files with 16 additions and 10 deletions

View File

@ -49,23 +49,30 @@ async def handle_keyword_command(event, command, args):
keywords = link_filter.keywords
await event.reply("当前关键词列表:\n" + "\n".join(keywords) if keywords else "关键词列表为空。")
elif command == '/add' and args:
keyword = args[0]
normalized_keyword = link_filter.normalize_link(keyword) if link_filter.link_pattern.match(keyword) else keyword.lower()
if normalized_keyword not in link_filter.keywords:
link_filter.add_keyword(normalized_keyword)
keyword = ' '.join(args) # 使用所有参数,以防关键词中含有空格
if keyword not in link_filter.keywords:
link_filter.add_keyword(keyword)
await event.reply(f"关键词 '{keyword}' 已添加。")
else:
await event.reply(f"关键词 '{keyword}' 已存在。")
elif command == '/delete' and args:
keyword = args[0]
normalized_keyword = link_filter.normalize_link(keyword) if link_filter.link_pattern.match(keyword) else keyword.lower()
if link_filter.remove_keyword(normalized_keyword):
keyword = ' '.join(args) # 使用所有参数,以防关键词中含有空格
matching_keywords = [k for k in link_filter.keywords if k.lower() == keyword.lower()]
if matching_keywords:
for k in matching_keywords:
link_filter.remove_keyword(k)
await event.reply(f"关键词 '{keyword}' 已删除。")
else:
await event.reply(f"关键词 '{keyword}' 不存在。")
# 如果没有精确匹配,尝试查找部分匹配的关键词
similar_keywords = [k for k in link_filter.keywords if keyword.lower() in k.lower()]
if similar_keywords:
await event.reply(f"未找到精确匹配的关键词 '{keyword}'\n\n是否要删除以下相似的关键词?\n" + "\n".join(similar_keywords))
else:
await event.reply(f"关键词 '{keyword}' 不存在。")
else:
await event.reply("无效的命令或参数。")
async def handle_whitelist_command(event, command, args):
if command == '/listwhite':
whitelist = link_filter.whitelist

View File

@ -71,14 +71,13 @@ class LinkFilter:
self.save_keywords()
def remove_keyword(self, keyword):
if self.link_pattern.match(keyword):
keyword = self.normalize_link(keyword)
if keyword in self.keywords:
self.keywords.remove(keyword)
self.save_keywords()
return True
return False
def should_filter(self, text):
# 检查是否包含关键词
if any(keyword.lower() in text.lower() for keyword in self.keywords if not self.link_pattern.match(keyword)):