From 480d201c55ecc610604e43818eeb34edb4f70ef0 Mon Sep 17 00:00:00 2001 From: Haibersut Date: Sat, 4 Mar 2023 21:02:10 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=99=BE=E5=BA=A6=E4=BA=91?= =?UTF-8?q?=E5=86=85=E5=AE=B9=E5=AE=A1=E6=A0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config-template.py | 12 +++++++++++ pkg/qqbot/filter.py | 49 +++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/config-template.py b/config-template.py index fec0a7ef..b73bc871 100644 --- a/config-template.py +++ b/config-template.py @@ -106,6 +106,18 @@ ignore_rules = { # 请在sensitive.json中添加敏感词 sensitive_word_filter = True +#是否启动百度云内容安全审核 +check = False + +#百度云API_KEY 24位英文数字字符串 +baidu_api_key = "" + +#百度云SECRET_KEY 32位的英文数字字符串 +baidu_secret_key ="" + +#不合规消息自定义返回 +illgalmessage = "[百度云]请珍惜机器人,当前返回内容不合规" + # 启动时是否发送赞赏码 # 仅当使用量已经超过2048字时发送 encourage_sponsor_at_start = True diff --git a/pkg/qqbot/filter.py b/pkg/qqbot/filter.py index 7cbca39b..e670aa22 100644 --- a/pkg/qqbot/filter.py +++ b/pkg/qqbot/filter.py @@ -1,19 +1,64 @@ # 敏感词过滤模块 import re +import requests +import json +from config import check, baidu_api_key, baidu_secret_key, illgalmessage +import logging + + +# 然后可以通过config.check, config.baidu_api_key等方式来使用这些变量。 + +def get_access_token(): + """ + 使用 AK,SK 生成鉴权签名(Access Token) + :return: access_token,或是None(如果错误) + """ + url = "https://aip.baidubce.com/oauth/2.0/token" + params = {"grant_type": "client_credentials", "client_id": baidu_api_key, + "client_secret": baidu_secret_key} + return str(requests.post(url, params=params).json().get("access_token")) + + +# 百度云审核URL +baidu_url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" \ + + get_access_token() class ReplyFilter: - sensitive_words = [] def __init__(self, sensitive_words: list): self.sensitive_words = sensitive_words def process(self, message: str) -> str: + # 百度云审核 + if check: + # 百度云审核 + payload = "text=" + message + logging.info("向百度云发送:" + payload) + headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'} + response = requests.request("POST", baidu_url, headers=headers, data=payload.encode('utf-8')) + response_dict = json.loads(response.text) + # 处理百度云审核结果 + if "error_code" in response_dict: + error_msg = response_dict.get("error_msg") + logging.info(f"百度云判定出错,错误信息:{error_msg}") + conclusion = f"百度云判定出错,错误信息:{error_msg}\n以下是原消息:{message}" + else: + conclusion = response_dict["conclusion"] + if conclusion in ("合规"): + logging.info(f"百度云判定结果:{conclusion}") + return message + else: + logging.info(f"百度云判定结果:{conclusion}") + conclusion = illgalmessage + # 返回百度云审核结果 + return conclusion + + # 本地关键词屏蔽 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