mirror of
https://github.com/aaPanel/aaPanel.git
synced 2026-09-27 03:44:49 +02:00
Update to v8.7.0
This commit is contained in:
@@ -9,6 +9,7 @@ from .dingding_msg import DingDingMsg
|
||||
from .sms_msg import SMSMsg
|
||||
# from .wx_account_msg import WeChatAccountMsg
|
||||
from .tg_msg import TgMsg
|
||||
from .discord_msg import DiscordMsg
|
||||
from .manager import SenderManager
|
||||
from .util import read_file,write_file
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
# coding: utf-8
|
||||
# -------------------------------------------------------------------
|
||||
# aaPanel
|
||||
# -------------------------------------------------------------------
|
||||
# Copyright (c) 2014-2099 aaPanel(www.aapanel.com) All rights reserved.
|
||||
# -------------------------------------------------------------------
|
||||
# Author: aapanel
|
||||
# -------------------------------------------------------------------
|
||||
# | Discord notification channel module
|
||||
# +-------------------------------------------------------------------
|
||||
|
||||
import json
|
||||
import requests
|
||||
from typing import Optional, Union
|
||||
|
||||
from .util import write_push_log, get_test_msg
|
||||
import public
|
||||
|
||||
# Disable SSL warnings
|
||||
try:
|
||||
from requests.packages import urllib3
|
||||
urllib3.disable_warnings()
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
class DiscordMsg:
|
||||
"""Discord message channel"""
|
||||
|
||||
def __init__(self, discord_data: dict):
|
||||
self.id = discord_data["id"]
|
||||
self.config = discord_data["data"]
|
||||
|
||||
@classmethod
|
||||
def check_args(cls, args: dict) -> Union[dict, str]:
|
||||
"""
|
||||
Validate Discord configuration parameters
|
||||
@param args: Configuration arguments
|
||||
@return: Validated data dict on success, error message string on failure
|
||||
"""
|
||||
if "url" not in args or "title" not in args:
|
||||
return public.lang('Incomplete information')
|
||||
|
||||
title = args["title"]
|
||||
if len(title) > 15:
|
||||
return public.lang('Note names cannot be longer than 15 characters')
|
||||
|
||||
url = args["url"].strip()
|
||||
if not url:
|
||||
return public.lang('Webhook URL cannot be empty')
|
||||
|
||||
# Validate URL format
|
||||
if not url.startswith("https://discord.com/api/webhooks/"):
|
||||
return public.lang('Invalid Discord Webhook URL format')
|
||||
|
||||
data = {
|
||||
"url": url,
|
||||
"title": title
|
||||
}
|
||||
|
||||
# Test send
|
||||
test_obj = cls({"data": data, "id": None})
|
||||
test_msg = {
|
||||
"msg_list": ['>configuration state: Success']
|
||||
}
|
||||
test_task = get_test_msg("Message channel configuration reminders")
|
||||
|
||||
res = test_obj.send_msg(
|
||||
test_task.to_discord_msg(test_msg, test_task.the_push_public_data()),
|
||||
"Message channel configuration reminders"
|
||||
)
|
||||
|
||||
if res is None:
|
||||
return data
|
||||
|
||||
return res
|
||||
|
||||
def send_msg(self, msg: str, title: str) -> Optional[str]:
|
||||
"""
|
||||
Send Discord message
|
||||
@param msg: Message content (Markdown format)
|
||||
@param title: Message title
|
||||
@return: None on success, error message string on failure
|
||||
"""
|
||||
if not self.config:
|
||||
return public.lang('Discord information is not configured correctly')
|
||||
|
||||
url = self.config.get("url", "")
|
||||
if not url:
|
||||
return public.lang('Discord Webhook URL is not configured')
|
||||
|
||||
try:
|
||||
# Simple text message format
|
||||
payload = {
|
||||
"content": msg
|
||||
}
|
||||
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
|
||||
response = requests.post(
|
||||
url=url,
|
||||
data=json.dumps(payload),
|
||||
headers=headers,
|
||||
timeout=10,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if response.status_code in [200, 204]:
|
||||
write_push_log("Discord", True, title)
|
||||
return None
|
||||
else:
|
||||
error_msg = f"HTTP {response.status_code}: {response.text}"
|
||||
write_push_log("Discord", False, title)
|
||||
return error_msg
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Discord send failed: {str(e)}"
|
||||
write_push_log("Discord", False, title)
|
||||
return error_msg
|
||||
|
||||
def test_send_msg(self) -> Optional[str]:
|
||||
"""
|
||||
Test send message
|
||||
@return: None on success, error message string on failure
|
||||
"""
|
||||
test_msg = {
|
||||
"msg_list": ['>configuration state: <font color=#20a53a>Success</font>']
|
||||
}
|
||||
test_task = get_test_msg("Message channel configuration reminders")
|
||||
|
||||
res = self.send_msg(
|
||||
test_task.to_discord_msg(test_msg, test_task.the_push_public_data()),
|
||||
"Message channel configuration reminders"
|
||||
)
|
||||
|
||||
if res is None:
|
||||
return None
|
||||
return res
|
||||
+32
-32
@@ -9,6 +9,7 @@ from .web_hook_msg import WebHookMsg
|
||||
from .feishu_msg import FeiShuMsg
|
||||
from .dingding_msg import DingDingMsg
|
||||
from .sms_msg import SMSMsg
|
||||
from .discord_msg import DiscordMsg
|
||||
# from .wx_account_msg import WeChatAccountMsg
|
||||
import json
|
||||
from mod.base import json_response
|
||||
@@ -24,10 +25,8 @@ class SenderManager:
|
||||
def __init__(self):
|
||||
self.custom_parameter_filename = "/www/server/panel/data/mod_push_data/custom_parameter.pl"
|
||||
self.init_default_sender()
|
||||
|
||||
def set_sender_conf(self, get):
|
||||
|
||||
args = json.loads(get.sender_data.strip())
|
||||
|
||||
try:
|
||||
sender_id = None
|
||||
try:
|
||||
@@ -39,6 +38,7 @@ class SenderManager:
|
||||
args = json.loads(get.sender_data.strip())
|
||||
except (json.JSONDecoder, AttributeError, TypeError):
|
||||
return json_response(status=False, msg=public.lang('The parameter is incorrect'))
|
||||
|
||||
sender_config = SenderConfig()
|
||||
if sender_id is not None:
|
||||
tmp = sender_config.get_by_id(sender_id)
|
||||
@@ -62,18 +62,22 @@ class SenderManager:
|
||||
|
||||
if isinstance(data, str):
|
||||
return json_response(status=False, data=data, msg=data)
|
||||
|
||||
elif sender_type == "webhook":
|
||||
custom_parameter = args.get("custom_parameter", {})
|
||||
if custom_parameter:
|
||||
try:
|
||||
public.writeFile(self.custom_parameter_filename, json.dumps(custom_parameter))
|
||||
except:
|
||||
pass
|
||||
if custom_parameter == "":
|
||||
custom_parameter = {}
|
||||
|
||||
try:
|
||||
if isinstance(custom_parameter, str):
|
||||
custom_parameter = json.loads(custom_parameter)
|
||||
public.writeFile(self.custom_parameter_filename, json.dumps(custom_parameter))
|
||||
except Exception as e:
|
||||
return json_response(status=False, data=str(e), msg=str(e))
|
||||
|
||||
data = WebHookMsg.check_args(args)
|
||||
_, data = WebHookMsg.check_args(args)
|
||||
if isinstance(data, str):
|
||||
return json_response(status=False, data=data, msg=public.lang('Test send failed'))
|
||||
return json_response(status=False, data=data, msg=data)
|
||||
|
||||
# 从文件读取并删除文件
|
||||
try:
|
||||
@@ -93,6 +97,11 @@ class SenderManager:
|
||||
data = DingDingMsg.check_args(args)
|
||||
if isinstance(data, str):
|
||||
return json_response(status=False, data=data, msg=public.lang('Test send failed'))
|
||||
|
||||
elif sender_type == "discord":
|
||||
data = DiscordMsg.check_args(args)
|
||||
if isinstance(data, str):
|
||||
return json_response(status=False, data=data, msg=public.lang('Test send failed'))
|
||||
else:
|
||||
return json_response(status=False, msg=public.lang('A type that is not supported by the current interface'))
|
||||
# Check if the sender configuration already exists
|
||||
@@ -102,25 +111,9 @@ class SenderManager:
|
||||
if conf['sender_type'] == sender_type and 'title' in conf['data'] and conf['data']['title'] == data['title'] and conf['id'] != sender_id
|
||||
)
|
||||
|
||||
|
||||
# for conf in sender_config.config:
|
||||
# if conf['sender_type'] == sender_type and 'title' in conf['data'] and conf['data']['title'] == data[
|
||||
# 'title'] and conf['id'] != sender_id:
|
||||
# public.print_log('000 -{}'.format(conf['sender_type']))
|
||||
# public.print_log('000 -{}'.format(sender_type))
|
||||
#
|
||||
# public.print_log('111 conf -{}'.format(conf['sender_type']))
|
||||
# public.print_log('111 -{}'.format(sender_type))
|
||||
#
|
||||
# public.print_log('222 conf -{}'.format(conf['data']['title']))
|
||||
# public.print_log('222 data -{}'.format(data['title']))
|
||||
#
|
||||
# public.print_log('333 conf -{}'.format(conf['id']))
|
||||
# public.print_log('333 -{}'.format(sender_id))
|
||||
|
||||
if existing_sender:
|
||||
return json_response(status=False, msg=public.lang('The same send configuration already exists and cannot be added repeatedly'))
|
||||
now_sender_id = None
|
||||
|
||||
if not sender_id:
|
||||
now_sender_id = sender_config.nwe_id()
|
||||
sender_config.config.append(
|
||||
@@ -142,8 +135,9 @@ class SenderManager:
|
||||
# conf["original"] = (conf['id'] == now_sender_id)
|
||||
|
||||
sender_config.save_config()
|
||||
if sender_type == "webhook":
|
||||
self.set_default_for_compatible(sender_config.get_by_id(now_sender_id))
|
||||
# 旧系统写入配置 弃用
|
||||
# if sender_type == "webhook":
|
||||
# self.set_default_for_compatible(sender_config.get_by_id(now_sender_id))
|
||||
|
||||
return json_response(status=True, msg=public.lang('Saved successfully'))
|
||||
except:
|
||||
@@ -196,7 +190,7 @@ class SenderManager:
|
||||
|
||||
res = []
|
||||
# WeChatAccountMsg.refresh_config(force=refresh)
|
||||
simple = ("weixin", "mail", "webhook", "feishu", "dingding", "tg")
|
||||
simple = ("weixin", "mail", "webhook", "feishu", "dingding", "tg", "discord")
|
||||
|
||||
for conf in SenderConfig().config:
|
||||
if conf["sender_type"] in simple or conf["sender_type"] == "wx_account":
|
||||
@@ -221,8 +215,8 @@ class SenderManager:
|
||||
return json_response(status=False, msg=public.lang('Corresponding sender not found'))
|
||||
|
||||
sender_type = tmp["sender_type"]
|
||||
|
||||
if sender_type == "weixin":
|
||||
# 这个是企业微信
|
||||
sender_obj = WeiXinMsg(tmp)
|
||||
|
||||
elif sender_type == "mail":
|
||||
@@ -236,16 +230,22 @@ class SenderManager:
|
||||
|
||||
elif sender_type == "dingding":
|
||||
sender_obj = DingDingMsg(tmp)
|
||||
|
||||
elif sender_type == "tg":
|
||||
sender_obj = TgMsg(tmp)
|
||||
|
||||
elif sender_type == "discord":
|
||||
sender_obj = DiscordMsg(tmp)
|
||||
|
||||
# elif sender_type == "wx_account":
|
||||
# sender_obj = WeChatAccountMsg(tmp)
|
||||
|
||||
else:
|
||||
return json_response(status=False, msg=public.lang('A type that is not supported by the current interface'))
|
||||
|
||||
res = sender_obj.test_send_msg()
|
||||
if isinstance(res, str):
|
||||
return json_response(status=False, data=res, msg=public.lang('Test send failed'))
|
||||
return json_response(status=False, data=res, msg=res or public.lang('Test send failed'))
|
||||
return json_response(status=True, msg=public.lang('The sending was successful'))
|
||||
|
||||
@staticmethod
|
||||
|
||||
+100
-48
@@ -8,7 +8,7 @@
|
||||
# | 消息通道HOOK模块
|
||||
# +-------------------------------------------------------------------
|
||||
|
||||
|
||||
import copy
|
||||
import requests
|
||||
from typing import Optional, Union
|
||||
from urllib3.util import parse_url
|
||||
@@ -48,18 +48,9 @@ class WebHookMsg(object):
|
||||
|
||||
def __init__(self, hook_data: dict):
|
||||
self.id = hook_data["id"]
|
||||
self.config = hook_data["data"]
|
||||
self.config = copy.deepcopy(hook_data["data"])
|
||||
|
||||
def _replace_and_parse(self, value, real_data):
|
||||
"""替换占位符并递归解析JSON字符串"""
|
||||
if isinstance(value, str):
|
||||
value = value.replace("$1", json.dumps(real_data, ensure_ascii=False))
|
||||
elif isinstance(value, dict):
|
||||
for k, v in value.items():
|
||||
value[k] = self._replace_and_parse(v, real_data)
|
||||
return value
|
||||
|
||||
def send_msg(self, msg: str, title:str, push_type:str) -> Optional[str]:
|
||||
def send_msg(self, msg: str, title: str) -> Optional[str]:
|
||||
the_url = parse_url(self.config['url'])
|
||||
|
||||
ssl_verify = self.config.get("ssl_verify", None)
|
||||
@@ -68,37 +59,25 @@ class WebHookMsg(object):
|
||||
else:
|
||||
ssl_verify = bool(int(ssl_verify)) # 转换为布尔值
|
||||
|
||||
|
||||
real_data = {
|
||||
"title": title,
|
||||
"msg": msg,
|
||||
"type": push_type,
|
||||
}
|
||||
custom_parameter = self.config.get("custom_parameter", {})
|
||||
if not isinstance(custom_parameter, dict):
|
||||
custom_parameter = {} # 如果 custom_parameter 不是字典,则设置为空字典
|
||||
# 处理custom_parameter,将$1替换为real_data内容并递归解析
|
||||
custom_data = {}
|
||||
for k, v in custom_parameter.items():
|
||||
custom_data[k] = self._replace_and_parse(v, real_data)
|
||||
|
||||
if custom_data:
|
||||
real_data = custom_data
|
||||
real_data = self._build_real_data(msg, title, custom_parameter=custom_parameter)
|
||||
|
||||
|
||||
data = None
|
||||
json_data = None
|
||||
headers = self.DEFAULT_HEADERS.copy()
|
||||
if self.config["body_type"] == "json":
|
||||
json_data = real_data
|
||||
elif self.config["body_type"] == "form_data":
|
||||
data = real_data
|
||||
|
||||
for k, v in self.config.get("headers", {}).items():
|
||||
if not isinstance(v, str):
|
||||
v = str(v)
|
||||
headers[k] = v
|
||||
|
||||
data = None
|
||||
json_data = None
|
||||
if self.config["body_type"] == "json":
|
||||
json_data = real_data
|
||||
elif self.config["body_type"] == "form_data":
|
||||
data = real_data
|
||||
|
||||
status = False
|
||||
error = None
|
||||
timeout = 10
|
||||
@@ -130,57 +109,133 @@ class WebHookMsg(object):
|
||||
verify=ssl_verify,
|
||||
)
|
||||
|
||||
text_lower = res.text.lower()
|
||||
if "error" in text_lower or "invalid" in text_lower or "fail" in text_lower:
|
||||
status = False
|
||||
return res.text
|
||||
|
||||
if "success" in text_lower:
|
||||
status = True
|
||||
error = None
|
||||
break
|
||||
|
||||
if res.status_code == 200:
|
||||
status = True
|
||||
error = None
|
||||
break
|
||||
else:
|
||||
status = False
|
||||
return res.text
|
||||
|
||||
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
|
||||
timeout += 5
|
||||
error = "time out"
|
||||
continue
|
||||
except requests.exceptions.RequestException as e:
|
||||
error = str(e)
|
||||
break
|
||||
|
||||
write_push_log("Web Hook", status, title)
|
||||
return error
|
||||
return error if error else None
|
||||
|
||||
@staticmethod
|
||||
def _build_real_data(msg: str, title:str, push_type:str = None, custom_parameter: dict = None):
|
||||
if not custom_parameter:
|
||||
custom_parameter = {}
|
||||
if not push_type:
|
||||
push_type = title
|
||||
default_data = {
|
||||
"title": title,
|
||||
"msg": msg,
|
||||
"type": push_type,
|
||||
}
|
||||
_build_by_replace = False
|
||||
|
||||
def _replace(tmp_data: Union[str, list, dict,]):
|
||||
nonlocal _build_by_replace
|
||||
if isinstance(tmp_data, str):
|
||||
if "$1" in tmp_data:
|
||||
_build_by_replace = True
|
||||
tmp_data = tmp_data.replace("$1", json.dumps(default_data, ensure_ascii=False))
|
||||
if "$msg" in tmp_data:
|
||||
_build_by_replace = True
|
||||
tmp_data = tmp_data.replace("$msg", msg)
|
||||
if "$title" in tmp_data:
|
||||
_build_by_replace = True
|
||||
tmp_data = tmp_data.replace("$title", title)
|
||||
if "$type" in tmp_data:
|
||||
_build_by_replace = True
|
||||
tmp_data = tmp_data.replace("$type", push_type)
|
||||
return tmp_data
|
||||
elif isinstance(tmp_data, list):
|
||||
new_data = []
|
||||
for i in tmp_data:
|
||||
new_data.append(_replace(i))
|
||||
return new_data
|
||||
elif isinstance(tmp_data, dict):
|
||||
new_data = {}
|
||||
for k, v in tmp_data.items():
|
||||
new_data[k] = _replace(v)
|
||||
return new_data
|
||||
else:
|
||||
return tmp_data
|
||||
|
||||
real_data = _replace(custom_parameter)
|
||||
if _build_by_replace:
|
||||
return real_data
|
||||
else:
|
||||
custom_parameter["title"] = title
|
||||
custom_parameter["msg"] = msg
|
||||
custom_parameter["type"] = push_type
|
||||
return custom_parameter
|
||||
|
||||
@classmethod
|
||||
def check_args(cls, args) -> Union[str, dict]:
|
||||
def check_args(cls, args):
|
||||
"""配置hook"""
|
||||
try:
|
||||
title = args['title']
|
||||
url = args["url"]
|
||||
query = args.get("query", {})
|
||||
|
||||
headers = args.get("headers", {})
|
||||
if headers == "":
|
||||
headers = {}
|
||||
headers = json.loads(headers) if isinstance(headers, str) else headers
|
||||
|
||||
body_type = args.get("body_type", "json")
|
||||
if body_type == "application/json":
|
||||
body_type = "json"
|
||||
|
||||
custom_parameter = args.get("custom_parameter", {})
|
||||
if custom_parameter == "":
|
||||
custom_parameter = {}
|
||||
custom_parameter = json.loads(custom_parameter) if isinstance(custom_parameter, str) else custom_parameter
|
||||
|
||||
method = args.get("method", "POST")
|
||||
ssl_verify = args.get("ssl_verify", None) # null Ture
|
||||
except (ValueError, KeyError):
|
||||
return public.lang('The parameter is incorrect')
|
||||
except Exception as e:
|
||||
return False, str(e)
|
||||
|
||||
the_url = parse_url(url)
|
||||
if the_url.scheme is None or the_url.host is None:
|
||||
return"URL parsing error, which may not be a legitimate URL"
|
||||
return False, "URL parsing error, which may not be a legitimate URL"
|
||||
|
||||
for i in (query, headers, custom_parameter):
|
||||
if not isinstance(i, dict):
|
||||
return public.lang('Parameter format error')
|
||||
return False, public.lang('Parameter format error')
|
||||
|
||||
if body_type not in ('json', 'form_data', 'null'):
|
||||
return public.lang('The body type must be json,form data, or null')
|
||||
return False, public.lang('The body type must be json,form data, or null')
|
||||
|
||||
if method not in ('GET', 'POST', 'PUT', 'PATCH'):
|
||||
return public.lang('The sending method is incorrect')
|
||||
return False, public.lang('The sending method is incorrect')
|
||||
|
||||
if ssl_verify not in (True, False, None):
|
||||
return public.lang('Verify if the SSL option is wrong')
|
||||
return False, public.lang('Verify if the SSL option is wrong')
|
||||
|
||||
title = title.strip()
|
||||
if title == "":
|
||||
return"The name cannot be empty"
|
||||
return False, "The name cannot be empty"
|
||||
|
||||
data = {
|
||||
"title": title,
|
||||
@@ -203,22 +258,19 @@ class WebHookMsg(object):
|
||||
|
||||
res = test_obj.send_msg(
|
||||
test_task.to_web_hook_msg(test_msg, test_task.the_push_public_data()),
|
||||
"Message channel configuration reminders",
|
||||
"Message channel configuration reminders"
|
||||
)
|
||||
if res is None:
|
||||
return data
|
||||
|
||||
return res
|
||||
return True, data
|
||||
return False, res
|
||||
|
||||
def test_send_msg(self) -> Optional[str]:
|
||||
test_msg = {
|
||||
"msg_list": ['>configuration state: <font color=#20a53a> Success </font>\n\n']
|
||||
"msg_list": ['>configuration state: Success \n\n']
|
||||
}
|
||||
test_task = get_test_msg("Message channel configuration reminders")
|
||||
res = self.send_msg(
|
||||
test_task.to_web_hook_msg(test_msg, test_task.the_push_public_data()),
|
||||
"Message channel configuration reminders",
|
||||
"Message channel configuration reminders"
|
||||
)
|
||||
if res is None:
|
||||
|
||||
Reference in New Issue
Block a user