Explorar el Código

feat(notify): add config

runhey hace 3 años
padre
commit
d8e35c837b

+ 31 - 1
config/template.json

@@ -12,7 +12,9 @@
     "error": {
       "handle_error": true,
       "save_error": true,
-      "screenshot_length": 1
+      "screenshot_length": 1,
+      "notify_enable": false,
+      "notify_config": "provider: null"
     },
     "optimization": {
       "screenshot_interval": 0.3,
@@ -115,6 +117,34 @@
       "raid_mode": "retreat_four_attack_nine",
       "attack_number": "all"
     },
+    "general_battle_config": {
+      "lock_team_enable": false,
+      "preset_enable": false,
+      "preset_group": 1,
+      "preset_team": 1,
+      "green_enable": false,
+      "green_mark": "green_left1",
+      "random_click_swipt_enable": false
+    },
+    "switch_soul_config": {
+      "enable": false,
+      "switch_group_team": "-1,-1"
+    }
+  },
+  "ryou_toppa": {
+    "scheduler": {
+      "enable": false,
+      "next_run": "2023-01-01 00:00:00",
+      "priority": 5,
+      "success_interval": "01 00:00:00",
+      "failure_interval": "01 00:00:00",
+      "server_update": "09:00:00"
+    },
+    "raid_config": {
+      "raid_mode": "attack_all",
+      "attack_number": "all",
+      "ryou_access": "yes"
+    },
     "general_battle_config": {
       "lock_team_enable": false,
       "preset_enable": false,

BIN
module/config/i18n/zh_CN.qm


+ 7 - 1
module/config/i18n/zh_CN.ts

@@ -519,5 +519,11 @@ mode_3策略是刷到五个契灵后开始结契,选择高级、中级盘来
 "1,2"表示第一个预设组,第二个队伍
 请使用英文输入法下的逗号
 预设组支持[1-7], 预设队伍支持[1-4]</translation></message>	
-</context>	
+</context>
+<context>
+    <name>Args</name>
+	<message><source>Notify Enable</source><translation>启用消息推送</translation></message>	
+	<message><source>Notify Config</source><translation>推送配置</translation></message>	
+	<message><source>notify_config_help</source><translation>输入为yaml格式,":"冒号后有一个空格,具体请翻阅文档[消息推送]</translation></message>	
+</context>		
 </TS>

+ 84 - 0
module/gui/qml/Component/Args.qml

@@ -106,6 +106,14 @@ Item {
                         return
                     }
                 }
+                else if(arg.type === "multi_line"){
+                    object = multi_line_item.createObject(group_column)
+                    if(object === null){
+                        console.error("can not create component multi_line_item", arg.title)
+                        return
+                    }
+                }
+
 
                 if(object === null){
                     console.error("can not create component ", arg.title)
@@ -452,7 +460,83 @@ Item {
             }
         }
     }
+    Component{
+        id: multi_line_item
+        Item{
+            id: multiLineItem
+            property var modelData: null
+            width: parent.width
+            implicitHeight: string_title.implicitHeight + string_description.implicitHeight
+            height: if(string_text.height > (string_title.implicitHeight + string_description.implicitHeight)){
+                        return string_text.height
+                    }else{
+                        return string_title.implicitHeight + string_description.implicitHeight
+                    }
+
+            Layout.fillHeight: true
+            FluMultilineTextBox{
+                id: string_text
+                anchors{
+                    top: parent.top
+                    topMargin: 2
+                    right: parent.right
+                }
+                placeholderText: ""
+                onEditingFinished: {
+                    if(set_task(multiLineItem.parent.parent.parent.groupName, modelData.name, text)){
+                        showSuccess( qsTr("Successful setting"))
+                    }
+                }
+//                onTextChanged: {
+//                    if(set_task(multiLineItem.parent.parent.parent.groupName, modelData.name, text)){
+//                        showSuccess( qsTr("Successful setting"))
+//                    }
+//                }
+            }
+
+            FluText{
+                // 设置的名称
+                id: string_title
+                anchors{
+                    top: parent.top
+                    left: parent.left
+                    right: string_text.left
+                }
+                text: ""
+                font: FluTextStyle.BodyStrong
+                wrapMode: Text.WrapAnywhere
+                topPadding: 6
+            }
+            FluText{
+                //描述
+                id: string_description
+                anchors{
+                    top: string_title.bottom
+                    left: parent.left
+                }
+                width: string_title.width
+                text: ""
+                font: FluTextStyle.Caption
+                wrapMode: Text.WordWrap
+                topPadding: 6
+                rightPadding: 6
+            }
+            onModelDataChanged: {
+                if(modelData === null){
+                    console.error("string model is null")
+                    return
+                }
+                string_text.text = modelData.value
+                string_text.placeholderText = modelData["default"]
 
+                string_title.text = qsTr(modelData.title)
+                if( typeof modelData.description === 'undefined'){
+                    return
+                }
+                string_description.text = qsTr(modelData.description.replace("\\n","\n"))
+            }
+        }
+    }
     onArgsDataChanged: {
 
     }

+ 76 - 0
module/notify/notify.py

@@ -1,3 +1,79 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
+
+import onepush.core
+import yaml
+from onepush import get_notifier
+from onepush.core import Provider
+from onepush.exceptions import OnePushException
+from onepush.providers.custom import Custom
+from requests import Response
+
+from module.logger import logger
+
+onepush.core.log = logger
+
+
+def handle_notify(_config: str, **kwargs) -> bool:
+    try:
+        config = {}
+        for item in yaml.safe_load_all(_config):
+            config.update(item)
+    except Exception:
+        logger.error("Fail to load onepush config, skip sending")
+        return False
+    try:
+        provider_name: str = config.pop("provider", None)
+        if provider_name is None:
+            logger.info("No provider specified, skip sending")
+            return False
+        notifier: Provider = get_notifier(provider_name)
+        required: list[str] = notifier.params["required"]
+        config.update(kwargs)
+
+        # pre check
+        for key in required:
+            if key not in config:
+                logger.warning(
+                    f"Notifier {notifier.name} require param '{key}' but not provided"
+                )
+
+        if isinstance(notifier, Custom):
+            if "method" not in config or config["method"] == "post":
+                config["datatype"] = "json"
+            if not ("data" in config or isinstance(config["data"], dict)):
+                config["data"] = {}
+            if "title" in kwargs:
+                config["data"]["title"] = kwargs["title"]
+            if "content" in kwargs:
+                config["data"]["content"] = kwargs["content"]
+
+        if provider_name.lower() == "gocqhttp":
+            access_token = config.get("access_token")
+            if access_token:
+                config["token"] = access_token
+
+        resp = notifier.notify(**config)
+        if isinstance(resp, Response):
+            if resp.status_code != 200:
+                logger.warning("Push notify failed!")
+                logger.warning(f"HTTP Code:{resp.status_code}")
+                return False
+            else:
+                if provider_name.lower() == "gocqhttp":
+                    return_data: dict = resp.json()
+                    if return_data["status"] == "failed":
+                        logger.warning("Push notify failed!")
+                        logger.warning(
+                            f"Return message:{return_data['wording']}")
+                        return False
+    except OnePushException:
+        logger.exception("Push notify failed")
+        return False
+    except Exception as e:
+        logger.exception(e)
+        return False
+
+    logger.info("Push notify success")
+    return True

+ 21 - 1
tasks/Component/config_base.py

@@ -1,9 +1,12 @@
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # github https://github.com/runhey
-
+from typing import Any
+from collections.abc import Callable, Generator
 from datetime import timedelta
+
 from pydantic import BaseModel, datetime_parse
+from pydantic.fields import ModelField
 
 
 
@@ -28,3 +31,20 @@ class ConfigBase(BaseModel):
 
 
 
+class MultiLine(str):
+    # @classmethod
+    # def __get_validators__(cls) -> Generator[Callable, None, None]:
+    #     yield cls.validate
+    #
+    # @classmethod
+    # def validate(cls, value: str, field: ModelField):
+    #     return cls(value)
+
+    @classmethod
+    def __modify_schema__(
+        cls, field_schema: dict[str, Any], field: ModelField | None
+    ):
+        if field:
+            field_schema['type'] = 'multi_line'
+
+

+ 4 - 0
tasks/Script/config_error.py

@@ -2,6 +2,7 @@
 # @author runhey
 # github https://github.com/runhey
 from pydantic import BaseModel, ValidationError, validator, Field
+from tasks.Component.config_base import MultiLine
 
 from module.logger import logger
 
@@ -13,5 +14,8 @@ class Error(BaseModel):
                              description='')
     screenshot_length: int = Field(default=1,
                                    description='')
+    notify_enable: bool = Field(default=False,
+                                description='')
+    notify_config: MultiLine = Field(default='provider: null', description='notify_config_help')