Skip to content

Commit

Permalink
修复 synologychat 交互连接失败的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
liufei-ereach committed Apr 26, 2024
1 parent e04fa06 commit 35aa878
Show file tree
Hide file tree
Showing 5 changed files with 334 additions and 7 deletions.
53 changes: 53 additions & 0 deletions app/conf/moduleconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,59 @@ class ModuleConf(object):
}
}
},
"webhook": {
"name": "Webhook",
"img_url": "../static/img/webhook_icon.png",
"config": {
"url": {
"id": "url",
"required": True,
"title": "URL",
"tooltip": "",
"type": "text",
"placeholder": "https://xxx.com/your_api/"
},
"method": {
"id": "method",
"required": True,
"title": "HTTP方法",
"tooltip": "GET方法中请求体将被忽略,由于查询参数不支持复杂格式,发送列表类消息请使用POST",
"type": "select",
"options": {
"GET": "GET",
"POST": "POST",
"PUT": "PUT",
"PATCH": "PATCH",
"DELETE": "DELETE",
},
"default": "POST"
},
"query_params": {
"id": "query_params",
"required": False,
"title": "额外查询参数",
"tooltip": "JSON字符串",
"type": "text",
"placeholder": """{"search": "keyword"}"""
},
"json_body": {
"id": "json_body",
"required": False,
"title": "额外请求体",
"tooltip": "JSON字符串,GET方法中被忽略,请勿使用title/text/image/url/user_id/medias作为key",
"type": "text",
"placeholder": """{"id": 123, "name": "abcd"}"""
},
"token": {
"id": "token",
"required": False,
"title": "Token",
"tooltip": "会放在Header的Authorization中",
"type": "text",
"placeholder": """Authorization-Token"""
},
}
},
},
"switch": {
"download_start": {
Expand Down
32 changes: 25 additions & 7 deletions app/message/client/synologychat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from app.message.client._base import _IMessageClient
from app.utils import ExceptionUtils, RequestUtils, StringUtils
from config import Config
import log

lock = Lock()

Expand Down Expand Up @@ -72,19 +73,29 @@ def send_msg(self, title, text="", image="", url="", user_id=""):
if url and image:
caption = f"{caption}\n\n<{url}|查看详情>"
payload_data = {'text': quote(caption)}
if image:
payload_data['file_url'] = quote(image)
#if image:
# payload_data['file_url'] = quote(image)
if user_id:
payload_data['user_ids'] = [int(user_id)]
ret, msg = self.__send_request(payload_data)
if not ret:
log.error(f"【Message Err1】%s" % msg)
return ret, msg
else:
userids = self.__get_bot_users()
if not userids:
return False, "机器人没有对任何用户可见"
payload_data['user_ids'] = userids
return self.__send_request(payload_data)
for userid in userids:
payload_data['user_ids'] = [int(userid)]
ret, msg = self.__send_request(payload_data)
if not ret:
log.error(f"【Message Err1】%s" % msg)
return ret, msg
return True, ""

except Exception as msg_e:
ExceptionUtils.exception_traceback(msg_e)
log.error(f"【Message Err2】%x" % str(msg_e))
return False, str(msg_e)

def send_list_msg(self, medias: list, user_id="", title="", **kwargs):
Expand Down Expand Up @@ -123,10 +134,14 @@ def send_list_msg(self, medias: list, user_id="", title="", **kwargs):
user_ids = self.__get_bot_users()
payload_data = {
"text": quote(caption),
"file_url": quote(image),
"user_ids": user_ids
#"file_url": quote(image),
}
return self.__send_request(payload_data)
for userid in user_ids:
payload_data["user_ids"] = [int(userid)]
ret, msg = self.__send_request(payload_data)
if not ret:
return ret, msg
return True, ""
except Exception as msg_e:
ExceptionUtils.exception_traceback(msg_e)
return False, str(msg_e)
Expand All @@ -152,10 +167,13 @@ def __send_request(self, payload_data):
发送消息请求
"""
payload = f"payload={json.dumps(payload_data)}"
#log.error(f"【Message】%s" % payload)
#log.error(f"【url】%s" % self._webhook_url)
ret = self._req.post_res(url=self._webhook_url, data=payload)
if ret and ret.status_code == 200:
result = ret.json()
if result:
# log.error(f"【ret】%s" % result)
errno = result.get('error', {}).get('code')
errmsg = result.get('error', {}).get('errors')
if not errno:
Expand Down
142 changes: 142 additions & 0 deletions app/message/client/webhook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import json
from threading import Lock

import requests

from app.message.client._base import _IMessageClient
from app.utils import ExceptionUtils
from config import Config

lock = Lock()


class Webhook(_IMessageClient):
schema = "webhook"

_client_config = {}
_domain = None
_url = None
_method = None
_query_params = None
_json_body = None
_token = None

def __init__(self, config):
self._config = Config()
self._client_config = config
self.init_config()

@classmethod
def __parse_json(cls, json_str, attr_name):
json_str = json_str.strip()
if not json_str:
return None
try:
return json.loads(json_str)
except json.JSONDecodeError as e:
raise ValueError(f"{attr_name} Json解析失败:{json_str}") from e

def init_config(self):
if self._client_config:
self._url = self._client_config.get("url")
self._method = self._client_config.get("method")
self._query_params = self.__parse_json(self._client_config.get("query_params"), 'query_params')
self._json_body = self.__parse_json(self._client_config.get("json_body"), 'json_body')
self._token = self._client_config.get("token")

@classmethod
def match(cls, ctype):
return True if ctype == cls.schema else False

def send_msg(self, title, text="", image="", url="", user_id=""):
"""
发送web请求
:param title: 消息标题
:param text: 消息内容
:param image: 消息图片地址
:param url: 点击消息转转的URL
:param user_id: 用户ID,如有则只发消息给该用户
:user_id: 发送消息的目标用户ID,为空则发给管理员
"""
if not title and not text:
return False, "标题和内容不能同时为空"
if not self._url:
return False, "url参数未配置"
if not self._method:
return False, "method参数未配置"
try:
media_data = {
'title': title,
'text': text,
'image': image,
'url': url,
'user_id': user_id
}
query_params = self._query_params.copy() if self._query_params else {}
json_body = self._json_body.copy() if self._json_body else {}
if self._method == 'GET':
query_params.update(media_data)
else:
json_body.update(media_data)
return self.__send_request(query_params, json_body)

except Exception as msg_e:
ExceptionUtils.exception_traceback(msg_e)
return False, str(msg_e)

def send_list_msg(self, medias: list, user_id="", title="", **kwargs):
"""
发送列表类消息
"""
if not title:
return False, "title为空"
if not medias or not isinstance(medias, list):
return False, "medias错误"
if not self._url:
return False, "url参数未配置"
if not self._method:
return False, "method参数未配置"
if self._method == 'GET':
return False, "GET不支持发送发送列表类消息"
try:
medias_data = [{
'title': media.get_title_string(),
'url': media.get_detail_url(),
'type': media.get_type_string(),
'vote': media.get_vote_string()
} for media in medias]

query_params = self._query_params.copy() if self._query_params else {}
json_body = self._json_body.copy() if self._json_body else {}
json_body.update({
'title': title,
'user_id': title,
'medias': medias_data,
})
return self.__send_request(query_params, json_body)
except Exception as msg_e:
ExceptionUtils.exception_traceback(msg_e)
return False, str(msg_e)

def __send_request(self, query_params, json_body):
"""
发送消息请求
"""
response = requests.request(self._method,
self._url,
params=query_params,
json=json_body,
headers=self.header)
if not response:
return False, "未获取到返回信息"
if 200 <= response.status_code <= 299:
return True, ""
else:
return False, f"请求失败:{response.status_code}"

@property
def header(self):
r = {"Content-Type": "application/json"}
if self._token:
r['Authorization'] = self._token
return r
Loading

0 comments on commit 35aa878

Please sign in to comment.