mirror of
https://github.com/langbot-app/LangBot.git
synced 2026-06-09 15:26:03 +00:00
feat: 添加敏感词过滤功能
This commit is contained in:
18
pkg/qqbot/filter.py
Normal file
18
pkg/qqbot/filter.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import re
|
||||
|
||||
|
||||
class ReplyFilter:
|
||||
|
||||
sensitive_words = []
|
||||
|
||||
def __init__(self, sensitive_words: list):
|
||||
self.sensitive_words = sensitive_words
|
||||
|
||||
def process(self, message: str) -> str:
|
||||
for word in self.sensitive_words:
|
||||
match = re.findall(word, message)
|
||||
if len(match) > 0:
|
||||
for i in range(len(match)):
|
||||
message = message.replace(match[i], "*" * len(match[i]))
|
||||
|
||||
return message
|
||||
@@ -1,4 +1,6 @@
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
|
||||
import openai.error
|
||||
@@ -10,6 +12,8 @@ from func_timeout import func_set_timeout, FunctionTimedOut
|
||||
import datetime
|
||||
import logging
|
||||
|
||||
import pkg.qqbot.filter
|
||||
|
||||
help_text = config.help_message
|
||||
|
||||
inst = None
|
||||
@@ -24,11 +28,21 @@ class QQBotManager:
|
||||
|
||||
bot = None
|
||||
|
||||
reply_filter = None
|
||||
|
||||
def __init__(self, mirai_http_api_config: dict, timeout: int = 60, retry: int = 3):
|
||||
|
||||
self.timeout = timeout
|
||||
self.retry = retry
|
||||
|
||||
if os.path.exists("sensitive.json") \
|
||||
and config.sensitive_word_filter is not None \
|
||||
and config.sensitive_word_filter:
|
||||
with open("sensitive.json", "r", encoding="utf-8") as f:
|
||||
self.reply_filter = pkg.qqbot.filter.ReplyFilter(json.load(f)['words'])
|
||||
else:
|
||||
self.reply_filter = pkg.qqbot.filter.ReplyFilter([])
|
||||
|
||||
bot = Mirai(
|
||||
qq=mirai_http_api_config['qq'],
|
||||
adapter=WebSocketAdapter(
|
||||
@@ -157,7 +171,7 @@ class QQBotManager:
|
||||
|
||||
logging.info(
|
||||
"回复[{}]消息:{}".format(session_name, reply[:min(100, len(reply))] + ("..." if len(reply) > 100 else "")))
|
||||
|
||||
reply = self.reply_filter.process(reply)
|
||||
return reply
|
||||
|
||||
# 私聊消息处理
|
||||
|
||||
Reference in New Issue
Block a user