瀏覽代碼

Merge remote-tracking branch 'remote/pydantic2' into FindJade

ChengRanORZ 1 年之前
父節點
當前提交
3adb756f94
共有 38 個文件被更改,包括 409 次插入 和 245 次删除
  1. 3 3
      dev_tools/assets_test.py
  2. 8 6
      module/config/config.py
  3. 34 37
      module/config/config_model.py
  4. 2 1
      module/device/method/nemu_ipc.py
  5. 1 1
      requirements-in.txt
  6. 4 2
      requirements.txt
  7. 37 41
      tasks/AbyssShadows/script_task.py
  8. 53 73
      tasks/Component/config_base.py
  9. 14 36
      tasks/Component/config_scheduler.py
  10. 4 0
      tasks/DemonEncounter/assets.py
  11. 1 1
      tasks/DemonEncounter/config.py
  12. 二進制
      tasks/DemonEncounter/demon/blue_piao.png
  13. 18 0
      tasks/DemonEncounter/demon/image.json
  14. 二進制
      tasks/DemonEncounter/demon/jade_50.png
  15. 21 7
      tasks/DemonEncounter/script_task.py
  16. 1 1
      tasks/Duel/assets.py
  17. 84 2
      tasks/Duel/config.py
  18. 2 2
      tasks/Duel/duel/image.json
  19. 1 1
      tasks/Duel/script_task.py
  20. 7 0
      tasks/Exploration/base.py
  21. 12 9
      tasks/Exploration/solo.py
  22. 7 1
      tasks/Hunt/config.py
  23. 26 9
      tasks/Hunt/script_task.py
  24. 1 1
      tasks/KekkaiActivation/config.py
  25. 1 1
      tasks/KekkaiUtilize/config.py
  26. 1 1
      tasks/Restart/login.py
  27. 1 1
      tasks/RichMan/assets.py
  28. 2 2
      tasks/RichMan/shrine/click.json
  29. 2 0
      tasks/RyouToppa/config.py
  30. 17 5
      tasks/RyouToppa/script_task.py
  31. 1 0
      tasks/Script/config_device.py
  32. 1 1
      tasks/TrueOrochi/config.py
  33. 4 0
      tasks/WantedQuests/assets.py
  34. 9 0
      tasks/WantedQuests/script_task.py
  35. 18 0
      tasks/WantedQuests/wq/se_image.json
  36. 二進制
      tasks/WantedQuests/wq/wq_wq_d1111.png
  37. 二進制
      tasks/WantedQuests/wq/wq_wq_nian.png
  38. 11 0
      tasks/base_task.py

+ 3 - 3
dev_tools/assets_test.py

@@ -34,10 +34,10 @@ def detect_ocr(file: str, target: RuleOcr):
 
 
 
 
 # 图片文件路径 可以是相对路径
 # 图片文件路径 可以是相对路径
-IMAGE_FILE = r"C:\Users\Ryland\Desktop\363385164-41fa341c-3efc-43f8-91b5-0cdd065ed8cf.png"
+IMAGE_FILE = r"D:\Project\OnmyojiAutoScript\log\error\1731668941132\2024-11-15_19-09-00-887294.png"
 if __name__ == '__main__':
 if __name__ == '__main__':
-    from tasks.KekkaiUtilize.assets import KekkaiUtilizeAssets
-    targe = KekkaiUtilizeAssets.I_SHI_CARD
+    from tasks.WantedQuests.assets import WantedQuestsAssets
+    targe = WantedQuestsAssets.I_WQ_BOX
     print(detect_image(IMAGE_FILE, targe))
     print(detect_image(IMAGE_FILE, targe))
 
 
     # ocr demo
     # ocr demo

+ 8 - 6
module/config/config.py

@@ -125,6 +125,13 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
     def lock_config(self) -> Lock:
     def lock_config(self) -> Lock:
         return Lock()
         return Lock()
 
 
+    @cached_property
+    def notifier(self):
+        notifier = Notifier(self.model.script.error.notify_config, enable=self.model.script.error.notify_enable)
+        notifier.config_name = self.config_name.upper()
+        logger.info(f'Notifier: {notifier.config_name}')
+        return notifier
+
     def gui_args(self, task: str) -> str:
     def gui_args(self, task: str) -> str:
         """
         """
         获取给gui显示的参数
         获取给gui显示的参数
@@ -378,12 +385,7 @@ class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
         logger.attr(f'{task}.scheduler.next_run', next_run)
         logger.attr(f'{task}.scheduler.next_run', next_run)
 
 
 
 
-    @cached_property
-    def notifier(self):
-        notifier = Notifier(self.model.script.error.notify_config, enable=self.model.script.error.notify_enable)
-        notifier.config_name = self.config_name.upper()
-        logger.info(f'Notifier: {notifier.config_name}')
-        return notifier
+
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':
     config = Config(config_name='oas1')
     config = Config(config_name='oas1')

+ 34 - 37
module/config/config_model.py

@@ -136,10 +136,6 @@ class ConfigModel(ConfigBase):
     dokan: Dokan = Field(default_factory=Dokan)
     dokan: Dokan = Field(default_factory=Dokan)
     abyss_shadows: AbyssShadows = Field(default_factory=AbyssShadows)
     abyss_shadows: AbyssShadows = Field(default_factory=AbyssShadows)
 
 
-    # @validator('script')
-    # def script_validator(cls, v):
-    #     if v is None:
-    #         return Script()
 
 
     def __init__(self, config_name: str=None) -> None:
     def __init__(self, config_name: str=None) -> None:
         """
         """
@@ -227,7 +223,7 @@ class ConfigModel(ConfigBase):
 
 
         :return:
         :return:
         """
         """
-        self.write_json(self.config_name, self.dict())
+        self.write_json(self.config_name, self.model_dump())
 
 
     @staticmethod
     @staticmethod
     def type(key: str) -> str:
     def type(key: str) -> str:
@@ -245,16 +241,6 @@ class ConfigModel(ConfigBase):
             classname = re.findall(r"'([^']*)'", field_type)[0]
             classname = re.findall(r"'([^']*)'", field_type)[0]
             return classname
             return classname
 
 
-    # @root_validator
-    # def on_on_property_change(cls, values):
-    #     """
-    #     当属性改变时保存
-    #     :param values:
-    #     :return:
-    #     """
-    #     logger.info(f'property change auto save')
-    #     cls.save()
-
     @staticmethod
     @staticmethod
     def deep_get(obj, keys: str, default=None):
     def deep_get(obj, keys: str, default=None):
         """
         """
@@ -300,21 +286,20 @@ class ConfigModel(ConfigBase):
             logger.warning(f'{task} is no inexistence')
             logger.warning(f'{task} is no inexistence')
             return {}
             return {}
 
 
-        def properties_groups(sch) -> dict:
-            properties = {}
-            for key, value in sch["properties"].items():
-                properties[key] = re.search(r"/([^/]+)$", value['$ref']).group(1)
-            return properties
-
         def extract_groups(sch):
         def extract_groups(sch):
             # 从schema 中提取未解析的group的数据
             # 从schema 中提取未解析的group的数据
-            properties = properties_groups(sch)
+            # properties = properties_groups(sch)
+            results = {}
+            properties = {}
+            for key, value in sch["properties"].items():
+                if 'items' in value:
+                    properties[key] = re.search(r"/([^/]+)$", value['items']['$ref']).group(1)
+                else:
+                    properties[key] = re.search(r"/([^/]+)$", value['$ref']).group(1)
 
 
-            result = {}
             for key, value in properties.items():
             for key, value in properties.items():
-                result[key] = sch["definitions"][value]
-
-            return result
+                results[key] = sch["$defs"][value]
+            return results
 
 
         def merge_value(groups, jsons, definitions) -> list[dict]:
         def merge_value(groups, jsons, definitions) -> list[dict]:
             # 将 groups的参数,同导出的json一起合并, 用于前端显示
             # 将 groups的参数,同导出的json一起合并, 用于前端显示
@@ -328,20 +313,26 @@ class ConfigModel(ConfigBase):
                 item["default"] = value["default"]
                 item["default"] = value["default"]
                 item["value"] = jsons[key] if key in jsons else value["default"]
                 item["value"] = jsons[key] if key in jsons else value["default"]
                 item["type"] = value["type"] if "type" in value else "enum"
                 item["type"] = value["type"] if "type" in value else "enum"
-                if 'allOf' in value:
-                    # list
-                    enum_key = re.search(r"/([^/]+)$", value['allOf'][0]['$ref']).group(1)
+                if '$ref' in value:  # list
+                    enum_key = re.search(r"/([^/]+)$", value['$ref']).group(1)
                     item["enumEnum"] = definitions[enum_key]["enum"]
                     item["enumEnum"] = definitions[enum_key]["enum"]
-                # TODO: 最大值最小值
+                # if 'allOf' in value:
+                #     enum_key = re.search(r"/([^/]+)$", value['allOf'][0]['$ref']).group(1)
+                #     item["enumEnum"] = definitions[enum_key]["enum"]
                 result.append(item)
                 result.append(item)
             return result
             return result
 
 
-        schema = task.schema()
+        schema = task.model_json_schema()
         groups = extract_groups(schema)
         groups = extract_groups(schema)
+        groups_value = groups.copy()
 
 
         result: dict[str, list] = {}
         result: dict[str, list] = {}
-        for key, value in task.dict().items():
-            result[key] = merge_value(groups[key], value, schema["definitions"])
+        for key, value in task.model_dump().items():
+            if key not in groups:
+                for group_name in groups.keys():
+                    if group_name in key:
+                        groups_value[key] = groups[group_name]
+            result[key] = merge_value(groups_value[key], value, schema["$defs"])
 
 
         return result
         return result
 
 
@@ -375,9 +366,15 @@ class ConfigModel(ConfigBase):
 
 
         task_object = getattr(self, task, None)
         task_object = getattr(self, task, None)
         group_object = getattr(task_object, group, None)
         group_object = getattr(task_object, group, None)
+        if group_object is None:  # deal list
+            matchs = re.findall(r'\d+', group)
+            index = int(matchs[-1]) - 1 if matchs else None
+            task_object_list = list(dict(task_object))
+            for k, v in dict(task_object).items():
+                if k not in group:
+                    continue
+                group_object = v[index] if group_object is None else None
         argument_object = getattr(group_object, argument, None)
         argument_object = getattr(group_object, argument, None)
-        # print(group_object)
-        # print(argument_object)
 
 
         if argument_object is None:
         if argument_object is None:
             logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
             logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
@@ -428,6 +425,7 @@ class ConfigModel(ConfigBase):
         data = self.read_json(self.config_name)
         data = self.read_json(self.config_name)
         super().__init__(**data)
         super().__init__(**data)
 
 
+
 if __name__ == "__main__":
 if __name__ == "__main__":
     try:
     try:
         c = ConfigModel("oas1")
         c = ConfigModel("oas1")
@@ -435,5 +433,4 @@ if __name__ == "__main__":
         print(e)
         print(e)
         c = ConfigModel()
         c = ConfigModel()
 
 
-    # c.save()
-    print(c.script_task('Orochi'))
+    c.script_set_arg('Duel', 'test_list_2', 'switch_all_soul', 'false')

+ 2 - 1
module/device/method/nemu_ipc.py

@@ -3,6 +3,7 @@ import ctypes
 import os
 import os
 import sys
 import sys
 from functools import partial, wraps
 from functools import partial, wraps
+from pathlib import Path
 
 
 import cv2
 import cv2
 import numpy as np
 import numpy as np
@@ -445,7 +446,7 @@ class NemuIpc():
         """
         """
         # Try existing settings first
         # Try existing settings first
         if self.config.script.device.emulatorinfo_path:
         if self.config.script.device.emulatorinfo_path:
-            folder = os.path.abspath(os.path.join(self.config.script.device.emulatorinfo_path, '../../'))
+            folder = str(Path(self.config.script.device.emulatorinfo_path).parent.parent)
             index = serial_to_id(self.serial)
             index = serial_to_id(self.serial)
             if index is not None:
             if index is not None:
                 try:
                 try:

+ 1 - 1
requirements-in.txt

@@ -11,7 +11,7 @@ anytree==2.8.0
 pywin32==306
 pywin32==306
 zerorpc==0.6.3
 zerorpc==0.6.3
 wrapt==1.15.0
 wrapt==1.15.0
-pydantic==1.10.7
+pydantic==2.10.0
 inflection==0.5.1
 inflection==0.5.1
 tqdm==4.65.0
 tqdm==4.65.0
 ppocr-onnx==0.0.3.9
 ppocr-onnx==0.0.3.9

+ 4 - 2
requirements.txt

@@ -7,6 +7,7 @@
 
 
 
 
 adbutils==0.11.0          # via -r requirements-in.txt, uiautomator2
 adbutils==0.11.0          # via -r requirements-in.txt, uiautomator2
+annotated-types==0.7.0    # via pydantic
 anyio==3.7.1              # via fastapi, starlette
 anyio==3.7.1              # via fastapi, starlette
 anytree==2.8.0            # via -r requirements-in.txt
 anytree==2.8.0            # via -r requirements-in.txt
 apkutils2==1.0.0          # via adbutils
 apkutils2==1.0.0          # via adbutils
@@ -53,7 +54,8 @@ protobuf==4.25.1          # via onnxruntime
 py==1.11.0                # via retry
 py==1.11.0                # via retry
 pyclipper==1.3.0.post5    # via ppocr-onnx
 pyclipper==1.3.0.post5    # via ppocr-onnx
 pycparser==2.21           # via cffi
 pycparser==2.21           # via cffi
-pydantic==1.10.7          # via -r requirements-in.txt, fastapi
+pydantic==2.10.0          # via -r requirements-in.txt, fastapi
+pydantic-core==2.27.0     # via pydantic
 pyelftools==0.30          # via apkutils2
 pyelftools==0.30          # via apkutils2
 pygments==2.17.2          # via rich
 pygments==2.17.2          # via rich
 pyparsing==3.1.1          # via packaging
 pyparsing==3.1.1          # via packaging
@@ -70,7 +72,7 @@ sniffio==1.3.0            # via anyio
 starlette==0.27.0         # via fastapi
 starlette==0.27.0         # via fastapi
 sympy==1.12               # via onnxruntime
 sympy==1.12               # via onnxruntime
 tqdm==4.65.0              # via -r requirements-in.txt
 tqdm==4.65.0              # via -r requirements-in.txt
-typing-extensions==4.9.0  # via fastapi, pydantic, uvicorn
+typing-extensions==4.12.2  # via fastapi, pydantic, pydantic-core, uvicorn
 uiautomator2==2.16.17     # via -r requirements-in.txt
 uiautomator2==2.16.17     # via -r requirements-in.txt
 uiautomator2cache==0.3.0.1  # via -r requirements-in.txt
 uiautomator2cache==0.3.0.1  # via -r requirements-in.txt
 urllib3==2.1.0            # via requests
 urllib3==2.1.0            # via requests

+ 37 - 41
tasks/AbyssShadows/script_task.py

@@ -159,23 +159,18 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AbyssShadowsAssets):
 
 
         # 设置下次运行时间
         # 设置下次运行时间
         if success:
         if success:
-            custom_time = None
             if today == 4:
             if today == 4:
                 # 周五推迟到周六
                 # 周五推迟到周六
                 logger.info(f"The next abyss shadows day is Saturday")
                 logger.info(f"The next abyss shadows day is Saturday")
-                custom_time = cfg.abyss_shadows_time.custom_run_time_saturday
-                target_time = (datetime.now() + timedelta(days=1)).replace(hour=custom_time.hour, minute=custom_time.minute, second=custom_time.second)
+                self.custom_next_run(task='AbyssShadows', custom_time=cfg.abyss_shadows_time.custom_run_time_saturday, time_delta=1)
             elif today == 5:
             elif today == 5:
                 # 周六推迟到周日
                 # 周六推迟到周日
                 logger.info(f"The next abyss shadows day is Sunday")
                 logger.info(f"The next abyss shadows day is Sunday")
-                custom_time = cfg.abyss_shadows_time.custom_run_time_sunday
-                target_time = (datetime.now() + timedelta(days=1)).replace(hour=custom_time.hour, minute=custom_time.minute, second=custom_time.second)
+                self.custom_next_run(task='AbyssShadows', custom_time=cfg.abyss_shadows_time.custom_run_time_sunday, time_delta=1)
             elif today == 6:
             elif today == 6:
                 # 周日推迟到下周五
                 # 周日推迟到下周五
                 logger.info(f"The next abyss shadows day is Friday")
                 logger.info(f"The next abyss shadows day is Friday")
-                custom_time = cfg.abyss_shadows_time.custom_run_time_friday
-                target_time = (datetime.now() + timedelta(days=5)).replace(hour=custom_time.hour, minute=custom_time.minute, second=custom_time.second)
-            self.set_next_run(task='AbyssShadows', target=target_time)
+                self.custom_next_run(task='AbyssShadows', custom_time=cfg.abyss_shadows_time.custom_run_time_friday, time_delta=5)
         else:
         else:
             self.set_next_run(task='AbyssShadows', finish=True, server=True, success=False)
             self.set_next_run(task='AbyssShadows', finish=True, server=True, success=False)
         raise TaskEnd
         raise TaskEnd
@@ -369,44 +364,45 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AbyssShadowsAssets):
                 logger.info(f"Click {self.I_ABYSS_NAVIGATION.name}")
                 logger.info(f"Click {self.I_ABYSS_NAVIGATION.name}")
                 continue
                 continue
             if self.appear(self.I_ABYSS_MAP):
             if self.appear(self.I_ABYSS_MAP):
-                logger.info(f"Find abyss map, exit")
-                break
-        click_times = 0
-        # 点击攻打区域
-        while 1:
-            self.screenshot()
+                logger.info("Find abyss map, exit")
             
             
-            # 如果点3次还没进去就表示目标已死亡,跳过
-            if click_times >= 3:
-                logger.warning(f"Failed to click {click_area}")
-                return 
-            # 出现前往按钮就退出
-            if self.appear(self.I_ABYSS_GOTO_ENEMY):
-                break
-            if self.click(click_area,interval=1.5):
-                click_times += 1
-                continue
-            if self.appear_then_click(self.I_ENSURE_BUTTON,interval=1):
-                continue
-            # TODO 有时出现bug,点了前往之后不动,需要再点一次,带解决
-
+            click_times = 0
+            # 点击攻打区域
+            while 1:
+                self.screenshot()
+                # 如果点3次还没进去就表示目标已死亡,跳过
+                if click_times >= 3:
+                    logger.warning(f"Failed to click {click_area}")
+                    return
+                # 出现前往按钮就退出
+                if self.appear(self.I_ABYSS_GOTO_ENEMY):
+                    break
+                if self.click(click_area,interval=1.5):
+                    click_times += 1
+                    continue
+                if self.appear_then_click(self.I_ENSURE_BUTTON,interval=1):
+                    continue
         
         
-        # 点击前往按钮
-        while 1:
-            self.screenshot()
-            if self.appear_then_click(self.I_ABYSS_GOTO_ENEMY,interval=1):
-                # 点击敌人后,如果是不同区域会确认框,点击确认                
-                if self.appear_then_click(self.I_ENSURE_BUTTON, interval=1):
-                    logger.info(f"Click {self.I_ENSURE_BUTTON.name}")
-                # 跑动画比较花时间
-                sleep(3)
-                continue
-            if self.appear(self.I_ABYSS_FIRE):
+            # 点击前往按钮
+            while 1:
+                self.screenshot()
+                if self.appear_then_click(self.I_ABYSS_GOTO_ENEMY,interval=1):
+                    logger.info(f"Click {self.I_ABYSS_GOTO_ENEMY.name}")
+                    # 点击敌人后,如果是不同区域会确认框,点击确认                
+                    if self.appear_then_click(self.I_ENSURE_BUTTON, interval=1):
+                        logger.info(f"Click {self.I_ENSURE_BUTTON.name}")
+                    # 跑动画比较花时间
+                    sleep(3)
+                    continue
+                else:
+                    break
+            
+            # 如果遇到点击前往按钮后不动的 bug,则再次尝试进入
+            if self.wait_until_appear(self.I_ABYSS_FIRE, wait_time=20):
                 break
                 break
-        logger.info(f"Click {self.I_ABYSS_GOTO_ENEMY.name}")
+            logger.warning("Failed to enter fire")
         
         
         # 点击战斗按钮
         # 点击战斗按钮
-        self.wait_until_appear(self.I_ABYSS_FIRE)
         while 1:
         while 1:
             self.screenshot()
             self.screenshot()
             if self.appear_then_click(self.I_ABYSS_FIRE,interval=1):
             if self.appear_then_click(self.I_ABYSS_FIRE,interval=1):

+ 53 - 73
tasks/Component/config_base.py

@@ -1,13 +1,17 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
+import re
 from typing import Any
 from typing import Any
 from collections.abc import Callable, Generator
 from collections.abc import Callable, Generator
 from datetime import timedelta, time, datetime
 from datetime import timedelta, time, datetime
 
 
-from pydantic import BaseModel, datetime_parse
-from pydantic.fields import ModelField
-
+from typing_extensions import Annotated
+from pydantic import (BeforeValidator,
+                      PlainSerializer,
+                      WithJsonSchema,
+                      TypeAdapter)
+from pydantic import BaseModel
 
 
 
 
 def format_timedelta(tdelta: timedelta):
 def format_timedelta(tdelta: timedelta):
@@ -16,76 +20,52 @@ def format_timedelta(tdelta: timedelta):
     minutes, seconds = divmod(rem, 60)
     minutes, seconds = divmod(rem, 60)
     return f"{days:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"
     return f"{days:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"
 
 
-
-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'
-
-class TimeDelta(timedelta):
-    def __str__(self):
-        return format_timedelta(self)
-
-    def __repr__(self):
-        return format_timedelta(self)
-
-    @classmethod
-    def __modify_schema__(
-            cls, field_schema: dict[str, Any], field: ModelField | None
-    ):
-        if field:
-            field_schema['type'] = 'time_delta'
-
-class DateTime(datetime):
-    @classmethod
-    def __modify_schema__(
-            cls, field_schema: dict[str, Any], field: ModelField | None
-    ):
-        if field:
-            field_schema['type'] = 'date_time'
-
-
-class Time(time):
-    """
-    尝试将字符串转换为time对象, 但是不生效
-    """
-    @classmethod
-    def __get_validators__(cls):
-        yield cls.validate
-
-    @classmethod
-    def validate(cls, value):
-        # print(f' Time validate: {value} type: {type(value)}')
-        if isinstance(value, str):
-            hour, minute, second = map(int, value.split(":"))
-            return cls(hour, minute, second)
-        elif isinstance(value, time):
-            return value
-        else:
-            raise ValueError("Invalid time format")
-
-    @classmethod
-    def __modify_schema__(
-            cls, field_schema: dict[str, Any], field: ModelField | None
-    ):
-        if field:
-            field_schema['type'] = 'time'
+def datadelta_validator(v: Any) -> timedelta:
+    if isinstance(v, str):
+        try:
+            pattern = r'(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})'
+            match = re.match(pattern, v)
+            if match:
+                days = int(match.group(1))
+                hours = int(match.group(2))
+                minutes = int(match.group(3))
+                seconds = int(match.group(4))
+                return TimeDelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
+            return TimeDelta(days=1, hours=0, minutes=0, seconds=0)
+        except ValueError:
+            raise ValueError('Invalid interval value. Expected format: seconds')
+    return v
+
+def datetime_validator(v: Any) -> datetime:
+    if isinstance(v, str):
+        return datetime.fromisoformat(v)
+    return v
+
+def time_validator(v: Any) -> time:
+    if isinstance(v, str):
+        return time.fromisoformat(v)
+    return v
+
+
+MultiLine = Annotated[str,
+                      WithJsonSchema({'type': 'multi_line'}),]
+
+
+TimeDelta = Annotated[timedelta,
+                      BeforeValidator(datadelta_validator),
+                      PlainSerializer(format_timedelta, return_type=str),
+                      WithJsonSchema({'type': 'time_delta'}),]
+
+DateTime = Annotated[datetime,
+                     BeforeValidator(datetime_validator),
+                     PlainSerializer(lambda v: v.isoformat(), return_type=str),
+                     WithJsonSchema({'type': 'date_time'}),]
+
+Time = Annotated[time,
+                 BeforeValidator(time_validator),
+                 PlainSerializer(lambda v: v.isoformat(), return_type=str),
+                 WithJsonSchema({'type': 'time'}),]
 
 
 # ---------------------------------------------------------------------------------------------------------------------
 # ---------------------------------------------------------------------------------------------------------------------
 class ConfigBase(BaseModel):
 class ConfigBase(BaseModel):
-    # 这个是导出json时候的配置,但是新的是导出dict,所以的无效
-    class Config:
-        json_encoders = {
-            TimeDelta: format_timedelta
-        }
+    pass

+ 14 - 36
tasks/Component/config_scheduler.py

@@ -1,16 +1,13 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
-import re
-from enum import Enum
-from datetime import datetime, timedelta, time
-from pydantic import BaseModel, ValidationError, validator, Field
+from pydantic import Field
 
 
 from tasks.Component.config_base import ConfigBase, TimeDelta, DateTime, Time
 from tasks.Component.config_base import ConfigBase, TimeDelta, DateTime, Time
 
 
 class Scheduler(ConfigBase):
 class Scheduler(ConfigBase):
     enable: bool = Field(default=False, description='enable_help')
     enable: bool = Field(default=False, description='enable_help')
-    next_run: DateTime = Field(default="2023-01-01 00:00:00", description='next_run_help')
+    next_run: DateTime = Field(default=DateTime.fromisoformat("2023-01-01 00:00:00"), description='next_run_help')
     priority: int = Field(default=5, description='priority_help')
     priority: int = Field(default=5, description='priority_help')
 
 
     success_interval: TimeDelta = Field(default=TimeDelta(days=1), description='success_interval_help')
     success_interval: TimeDelta = Field(default=TimeDelta(days=1), description='success_interval_help')
@@ -18,38 +15,19 @@ class Scheduler(ConfigBase):
     server_update: Time = Field(default=Time(hour=9, minute=0, second=0), description='server_update_help')
     server_update: Time = Field(default=Time(hour=9, minute=0, second=0), description='server_update_help')
     float_time: Time = Field(default=Time(hour=0, minute=0, second=0), description='float_time_help')
     float_time: Time = Field(default=Time(hour=0, minute=0, second=0), description='float_time_help')
 
 
-    @validator('next_run', pre=True, always=True)
-    def parse_next_run(cls, value):
-        if isinstance(value, str):
-            try:
-                return datetime.fromisoformat(value)
-            except ValueError:
-                raise ValueError('Invalid next_run value. Expected format: YYYY-MM-DD HH:MM:SS')
-        return value
-
-    @validator('success_interval', 'failure_interval', pre=True)
-    def parse_interval(cls, value):
-        if isinstance(value, str):
-            try:
-                pattern = r'(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})'
-                match = re.match(pattern, value)
-                if match:
-                    days = int(match.group(1))
-                    hours = int(match.group(2))
-                    minutes = int(match.group(3))
-                    seconds = int(match.group(4))
-                    return TimeDelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
-                return TimeDelta(days=1, hours=0, minutes=0, seconds=0)
-            except ValueError:
-                raise ValueError('Invalid interval value. Expected format: seconds')
-        return value
-
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
-    s = Scheduler(success_interval='00 00:00:10')
-    if isinstance(s.success_interval, TimeDelta):
-        print(s.success_interval.seconds)
-    print(s.json())
-    print(s.dict())
+    dict_s = {
+        "enable": False,
+        "next_run": "2026-07-19T14:15:37",
+        "priority": 5,
+        "success_interval": "10 00:00:01",
+        "failure_interval": "10 00:00:01",
+        "server_update": "09:03:00",
+        "float_time": "02:00:05"
+    }
+    s = Scheduler(**dict_s)
+    print(s.model_dump())
+
 
 
 
 

+ 4 - 0
tasks/DemonEncounter/assets.py

@@ -73,6 +73,10 @@ class DemonEncounterAssets:
 	I_DE_SHI_RECORDS = RuleImage(roi_front=(789,639,48,48), roi_back=(789,639,48,48), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_shi_records.png")
 	I_DE_SHI_RECORDS = RuleImage(roi_front=(789,639,48,48), roi_back=(789,639,48,48), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_shi_records.png")
 	# 左下角小指针 
 	# 左下角小指针 
 	I_DE_LOCATION = RuleImage(roi_front=(26,653,44,47), roi_back=(26,653,44,47), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_location.png")
 	I_DE_LOCATION = RuleImage(roi_front=(26,653,44,47), roi_back=(26,653,44,47), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/demon_de_location.png")
+	# 逢魔蓝票 
+	I_BLUE_PIAO = RuleImage(roi_front=(420,226,444,262), roi_back=(420,226,444,262), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/blue_piao.png")
+	# 50勾玉购买 
+	I_JADE_50 = RuleImage(roi_front=(420,226,444,262), roi_back=(420,226,444,262), threshold=0.8, method="Template matching", file="./tasks/DemonEncounter/demon/jade_50.png")
 
 
 
 
 	# Image Rule Assets
 	# Image Rule Assets

+ 1 - 1
tasks/DemonEncounter/config.py

@@ -37,7 +37,7 @@ class DemonConfig(BaseModel):
 
 
 
 
 class UtilizeScheduler(Scheduler):
 class UtilizeScheduler(Scheduler):
-    priority = Field(default=2, description='priority_help')
+    priority: int = Field(default=2, description='priority_help')
 
 
 class DemonEncounter(ConfigBase):
 class DemonEncounter(ConfigBase):
     scheduler: UtilizeScheduler = Field(default_factory=UtilizeScheduler)
     scheduler: UtilizeScheduler = Field(default_factory=UtilizeScheduler)

二進制
tasks/DemonEncounter/demon/blue_piao.png


+ 18 - 0
tasks/DemonEncounter/demon/image.json

@@ -52,5 +52,23 @@
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "左下角小指针"
     "description": "左下角小指针"
+  },
+  {
+    "itemName": "blue_piao",
+    "imageName": "blue_piao.png",
+    "roiFront": "420,226,444,262",
+    "roiBack": "420,226,444,262",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "逢魔蓝票"
+  },
+  {
+    "itemName": "jade_50",
+    "imageName": "jade_50.png",
+    "roiFront": "420,226,444,262",
+    "roiBack": "420,226,444,262",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "50勾玉购买"
   }
   }
 ]
 ]

二進制
tasks/DemonEncounter/demon/jade_50.png


+ 21 - 7
tasks/DemonEncounter/script_task.py

@@ -200,7 +200,7 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
             lantern_type = self.check_lantern(i)
             lantern_type = self.check_lantern(i)
             match lantern_type:
             match lantern_type:
                 case LanternClass.BOX:
                 case LanternClass.BOX:
-                    self._box()
+                    self._box(match_click[i])
                 case LanternClass.MAIL:
                 case LanternClass.MAIL:
                     self._mail(match_click[i])
                     self._mail(match_click[i])
                 case LanternClass.REALM:
                 case LanternClass.REALM:
@@ -267,9 +267,23 @@ class ScriptTask(GameUi, GeneralBattle, DemonEncounterAssets, SwitchSoul):
             logger.info(f'Lantern {index} is battle')
             logger.info(f'Lantern {index} is battle')
             return LanternClass.BATTLE
             return LanternClass.BATTLE
 
 
-    def _box(self):
-        # 宝箱不领
-        pass
+    def _box(self, target_click):
+        while 1:
+            self.screenshot()
+            if self.appear(self.I_JADE_50):
+                break
+            if self.click(target_click, interval=1):
+                continue
+        while 1:
+            self.screenshot()
+            if self.appear(self.I_BLUE_PIAO):
+                if self.click(self.I_JADE_50):
+                    logger.info('Buy a mystery amulet for 50 jade')
+                    continue
+            if not self.appear(self.I_BLUE_PIAO):
+                if self.appear_then_click(self.I_DE_FIND, interval=2.5):
+                    break
+
 
 
     def _mail(self, target_click):
     def _mail(self, target_click):
         # 答题,还没有碰到过答题的
         # 答题,还没有碰到过答题的
@@ -446,9 +460,9 @@ if __name__ == '__main__':
     from module.device.device import Device
     from module.device.device import Device
     from memory_profiler import profile
     from memory_profiler import profile
 
 
-    c = Config('oas1')
+    c = Config('du')
     d = Device(c)
     d = Device(c)
     t = ScriptTask(c, d)
     t = ScriptTask(c, d)
 
 
-    # t.run()
-    t.battle_wait(True)
+    t.run()
+    # t.battle_wait(True)

+ 1 - 1
tasks/Duel/assets.py

@@ -17,7 +17,7 @@ class DuelAssets:
 
 
 	# Image Rule Assets
 	# Image Rule Assets
 	# 点击阵容 
 	# 点击阵容 
-	I_D_TEAM = RuleImage(roi_front=(813,284,34,74), roi_back=(813,284,34,74), threshold=0.8, method="Template matching", file="./tasks/Duel/duel/duel_d_team.png")
+	I_D_TEAM = RuleImage(roi_front=(813,288,34,74), roi_back=(785,259,115,119), threshold=0.8, method="Template matching", file="./tasks/Duel/duel/duel_d_team.png")
 	# 一键切换所有的御魂 
 	# 一键切换所有的御魂 
 	I_D_TEAM_SWTICH = RuleImage(roi_front=(1082,85,38,41), roi_back=(1082,85,38,41), threshold=0.8, method="Template matching", file="./tasks/Duel/duel/duel_d_team_swtich.png")
 	I_D_TEAM_SWTICH = RuleImage(roi_front=(1082,85,38,41), roi_back=(1082,85,38,41), threshold=0.8, method="Template matching", file="./tasks/Duel/duel/duel_d_team_swtich.png")
 	# 观战 
 	# 观战 

+ 84 - 2
tasks/Duel/config.py

@@ -1,8 +1,14 @@
 # This Python file uses the following encoding: utf-8
 # This Python file uses the following encoding: utf-8
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
-from pydantic import BaseModel, Field
-from datetime import time
+from typing import Any, Dict
+from pydantic import (Field,
+                      model_validator,
+                      ValidationError,
+                      model_serializer,
+                      WithJsonSchema,
+                      SerializerFunctionWrapHandler,
+                      GetJsonSchemaHandler)
 
 
 from tasks.Component.config_scheduler import Scheduler
 from tasks.Component.config_scheduler import Scheduler
 from tasks.Component.config_base import ConfigBase, Time
 from tasks.Component.config_base import ConfigBase, Time
@@ -26,4 +32,80 @@ class DuelConfig(ConfigBase):
 class Duel(ConfigBase):
 class Duel(ConfigBase):
     scheduler: Scheduler = Field(default_factory=Scheduler)
     scheduler: Scheduler = Field(default_factory=Scheduler)
     duel_config: DuelConfig = Field(default_factory=DuelConfig)
     duel_config: DuelConfig = Field(default_factory=DuelConfig)
+    test_list: list[DuelConfig]
 
 
+    @model_validator(mode='before')
+    @classmethod
+    def check_list(cls, data: dict) -> Any:
+        if 'test_list' not in data:
+            data['test_list'] = []
+        for key, value in data.items():
+            if isinstance(value, list):
+                continue
+            if 'test_list' not in key:
+                continue
+            try:
+                DuelConfig(**value)
+                data['test_list'].append(value)
+            except ValidationError as e:
+                pass
+        # 补全list
+        while len(data['test_list']) < data['scheduler']['priority']:
+            data['test_list'].append(DuelConfig())
+        return data
+
+    @model_serializer()
+    def serializer_model(self, value: Any) -> Dict[str, Any]:
+        properties = self.__dict__
+        data = {}
+        for key,value in properties.items():
+            if isinstance(value, list):
+                for index, v in enumerate(value):
+                    data[f'{key}_{index+1}'] = v.model_dump()
+            else:
+                data[key] = value.model_dump()
+        return data
+
+
+if __name__ == "__main__":
+    test_dict = {
+        'scheduler': {'enable': False,
+                      'next_run': '2023-01-01T00:00:00',
+                      'priority': 5,
+                      'success_interval': '01 00:00:00',
+                      'failure_interval': '01 00:00:00',
+                      'server_update': '09:00:00',
+                      'float_time': '00:00:00'
+                      },
+        'duel_config': {'switch_all_soul': False,
+                        'limit_time': '00:30:00',
+                        'target_score': 2000,
+                        'honor_full_exit': False,
+                        'green_enable': False,
+                        'green_mark': 'green_left1'},
+        # 'test_list': [
+        #     {'switch_all_soul': True,
+        #      'limit_time': '00:30:00',
+        #      'target_score': 2000,
+        #      'honor_full_exit': False,
+        #      'green_enable': False,
+        #      'green_mark': 'green_left1'},
+        # ],
+        # 'duel_config1': {'switch_all_soul': False,
+        #                 'limit_time': '00:30:00',
+        #                 'target_score': 2000,
+        #                 'honor_full_exit': False,
+        #                 'green_enable': False,
+        #                 'green_mark': 'green_left1'},
+        # 'duel_config2': {'switch_all_soul': False,
+        #                  'limit_time': '00:30:00',
+        #                  'target_score': 2000,
+        #                  'honor_full_exit': False,
+        #                  'green_enable': False,
+        #                  'green_mark': 'green_left1'},
+
+    }
+    import json
+    c = Duel(**test_dict)
+    # print(c.model_dump_json(indent=2))
+    print(json.dumps(c.model_json_schema(), indent=2))

+ 2 - 2
tasks/Duel/duel/image.json

@@ -2,8 +2,8 @@
   {
   {
     "itemName": "d_team",
     "itemName": "d_team",
     "imageName": "duel_d_team.png",
     "imageName": "duel_d_team.png",
-    "roiFront": "813,284,34,74",
-    "roiBack": "813,284,34,74",
+    "roiFront": "813,288,34,74",
+    "roiBack": "785,259,115,119",
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "点击阵容"
     "description": "点击阵容"

+ 1 - 1
tasks/Duel/script_task.py

@@ -61,7 +61,7 @@ class ScriptTask(GameUi, GeneralBattle, DuelAssets):
         """
         """
         if screenshot:
         if screenshot:
             self.screenshot()
             self.screenshot()
-        return self.appear(self.I_D_HELP)
+        return self.appear(self.I_D_HELP) or self.appear(self.I_D_CELEB_STAR) or self.appear(self.I_D_CELEB_HONOR)
 
 
     def switch_all_soul(self):
     def switch_all_soul(self):
         """
         """

+ 7 - 0
tasks/Exploration/base.py

@@ -23,6 +23,7 @@ from tasks.Utils.config_enum import ShikigamiClass
 from module.logger import logger
 from module.logger import logger
 from module.exception import RequestHumanTakeover, TaskEnd
 from module.exception import RequestHumanTakeover, TaskEnd
 from module.atom.image_grid import ImageGrid
 from module.atom.image_grid import ImageGrid
+from module.atom.animate import RuleAnimate
 from module.base.utils import load_image
 from module.base.utils import load_image
 
 
 class Scene(Enum):
 class Scene(Enum):
@@ -51,6 +52,10 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
         )
         )
         return self.config.model.exploration
         return self.config.model.exploration
 
 
+    @cached_property
+    def _match_end(self):
+        return RuleAnimate(self.I_SWIPE_END)
+
     def get_current_scene(self, reuse_screenshot: bool = True) -> Scene:
     def get_current_scene(self, reuse_screenshot: bool = True) -> Scene:
         if not reuse_screenshot:
         if not reuse_screenshot:
             self.screenshot()
             self.screenshot()
@@ -106,6 +111,8 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
 
 
     def post_process(self):
     def post_process(self):
         self.wait_until_stable(self.I_UI_BACK_RED)
         self.wait_until_stable(self.I_UI_BACK_RED)
+        if self.appear(self.I_UI_BACK_RED):
+            self.ui_click_until_disappear(self.I_UI_BACK_RED)
         self.ui_get_current_page()
         self.ui_get_current_page()
         self.ui_goto(page_main)
         self.ui_goto(page_main)
         con = self._config.exploration_config
         con = self._config.exploration_config

+ 12 - 9
tasks/Exploration/solo.py

@@ -7,10 +7,10 @@ from cached_property import cached_property
 from module.logger import logger
 from module.logger import logger
 from module.base.timer import Timer
 from module.base.timer import Timer
 
 
-
 from tasks.Component.GeneralInvite.config_invite import InviteConfig, InviteNumber, FindMode
 from tasks.Component.GeneralInvite.config_invite import InviteConfig, InviteNumber, FindMode
 from tasks.Exploration.base import BaseExploration, UpType, Scene
 from tasks.Exploration.base import BaseExploration, UpType, Scene
-from tasks.Exploration.config import ChooseRarity, AutoRotate, UserStatus
+from tasks.Exploration.config import ChooseRarity, AutoRotate, UserStatus, ExplorationLevel
+
 
 
 class SoloExploration(BaseExploration):
 class SoloExploration(BaseExploration):
     INVITE_FLAG_OFF = (157, 109, 83)
     INVITE_FLAG_OFF = (157, 109, 83)
@@ -80,7 +80,7 @@ class SoloExploration(BaseExploration):
                 # 向后拉,寻找怪
                 # 向后拉,寻找怪
                 if search_fail_cnt >= 4:
                 if search_fail_cnt >= 4:
                     search_fail_cnt = 0
                     search_fail_cnt = 0
-                    if self.appear(self.I_SWIPE_END):
+                    if (self._config.exploration_config.exploration_level == ExplorationLevel.EXPLORATION_28 and self.appear(self.I_SWIPE_END)) or self._match_end.stable(self.device.image):
                         self.quit_explore()
                         self.quit_explore()
                         continue
                         continue
                     if self.swipe(self.S_SWIPE_BACKGROUND_RIGHT, interval=3):
                     if self.swipe(self.S_SWIPE_BACKGROUND_RIGHT, interval=3):
@@ -210,7 +210,7 @@ class SoloExploration(BaseExploration):
                 # 向后拉,寻找怪
                 # 向后拉,寻找怪
                 if search_fail_cnt >= 4:
                 if search_fail_cnt >= 4:
                     search_fail_cnt = 0
                     search_fail_cnt = 0
-                    if self.appear(self.I_SWIPE_END):
+                    if (self._config.exploration_config.exploration_level == ExplorationLevel.EXPLORATION_28 and self.appear(self.I_SWIPE_END)) or self._match_end.stable(self.device.image):
                         self.quit_explore()
                         self.quit_explore()
                         continue
                         continue
                     if self.swipe(self.S_SWIPE_BACKGROUND_RIGHT, interval=4.5):
                     if self.swipe(self.S_SWIPE_BACKGROUND_RIGHT, interval=4.5):
@@ -443,10 +443,14 @@ class ScriptTask(SoloExploration):
             self.pre_process()
             self.pre_process()
 
 
         match self._config.exploration_config.user_status:
         match self._config.exploration_config.user_status:
-            case UserStatus.ALONE: self.run_solo()
-            case UserStatus.LEADER: self.run_leader()
-            case UserStatus.MEMBER: self.run_member()
-            case _: self.run_solo()
+            case UserStatus.ALONE:
+                self.run_solo()
+            case UserStatus.LEADER:
+                self.run_leader()
+            case UserStatus.MEMBER:
+                self.run_member()
+            case _:
+                self.run_solo()
 
 
         self.post_process()
         self.post_process()
 
 
@@ -459,4 +463,3 @@ if __name__ == "__main__":
     device = Device(config)
     device = Device(config)
     t = ScriptTask(config, device)
     t = ScriptTask(config, device)
     t.run()
     t.run()
-

+ 7 - 1
tasks/Hunt/config.py

@@ -5,7 +5,12 @@ from datetime import timedelta
 from pydantic import BaseModel, Field
 from pydantic import BaseModel, Field
 
 
 from tasks.Component.config_scheduler import Scheduler
 from tasks.Component.config_scheduler import Scheduler
-from tasks.Component.config_base import ConfigBase
+from tasks.Component.config_base import ConfigBase, Time
+
+class HuntTime(ConfigBase):
+    # 自定义运行时间
+    kirin_time: Time = Field(default=Time(hour=19, minute=0, second=0))
+    netherworld_time: Time = Field(default=Time(hour=19, minute=0, second=0))
 
 
 class HuntConfig(BaseModel):
 class HuntConfig(BaseModel):
     kirin_group_team: str = Field(default='-1,-1', description='switch_group_team_help')
     kirin_group_team: str = Field(default='-1,-1', description='switch_group_team_help')
@@ -14,4 +19,5 @@ class HuntConfig(BaseModel):
 
 
 class Hunt(ConfigBase):
 class Hunt(ConfigBase):
     scheduler: Scheduler = Field(default_factory=Scheduler)
     scheduler: Scheduler = Field(default_factory=Scheduler)
+    hunt_time: HuntTime = Field(default_factory=HuntTime)
     hunt_config: HuntConfig = Field(default_factory=HuntConfig)
     hunt_config: HuntConfig = Field(default_factory=HuntConfig)

+ 26 - 9
tasks/Hunt/script_task.py

@@ -19,8 +19,10 @@ from tasks.Hunt.assets import HuntAssets
 
 
 class ScriptTask(GameUi, GeneralBattle, GeneralInvite, SwitchSoul, HuntAssets):
 class ScriptTask(GameUi, GeneralBattle, GeneralInvite, SwitchSoul, HuntAssets):
     kirin_day = True  # 不是麒麟就是阴界之门
     kirin_day = True  # 不是麒麟就是阴界之门
+    tomorrow_kirin_day = True  # 明天是麒麟还是阴界之门
 
 
     def run(self):
     def run(self):
+        self.con_time = self.config.hunt.hunt_time
         if not self.check_datetime():
         if not self.check_datetime():
             # 设置下次运行时间 为今天的晚上七点钟
             # 设置下次运行时间 为今天的晚上七点钟
             raise TaskEnd('Hunt')
             raise TaskEnd('Hunt')
@@ -44,7 +46,7 @@ class ScriptTask(GameUi, GeneralBattle, GeneralInvite, SwitchSoul, HuntAssets):
             self.netherworld()
             self.netherworld()
         sleep(1)
         sleep(1)
 
 
-        self.set_next_run(task='Hunt', success=True, finish=True)
+        self.plan_tomorrow_hunt()
         raise TaskEnd('Hunt')
         raise TaskEnd('Hunt')
 
 
     def check_datetime(self) -> bool:
     def check_datetime(self) -> bool:
@@ -58,23 +60,38 @@ class ScriptTask(GameUi, GeneralBattle, GeneralInvite, SwitchSoul, HuntAssets):
             self.kirin_day = True
             self.kirin_day = True
         elif 4 <= day_of_week <= 6:
         elif 4 <= day_of_week <= 6:
             self.kirin_day = False
             self.kirin_day = False
-
+        
+        if 3 <= day_of_week <= 5:
+            self.tomorrow_kirin_day = False
+        else:
+            self.tomorrow_kirin_day = True
 
 
         now = datetime.now()
         now = datetime.now()
-        # 如果时间在00:00-19:00 之间则设定时间为当天的19:00,返回False
+        # 如果时间在00:00-19:00 之间则设定时间为当天的自定义时间,返回False
         if now.time() < time(19, 0):
         if now.time() < time(19, 0):
-            next_run = datetime.combine(now.date(), time(19, 0))
-            self.set_next_run(task='Hunt', success=False, finish=True, target=next_run)
+            if self.kirin_day:
+                logger.info('Today is the Kirin day')
+                self.custom_next_run(task='Hunt', custom_time=self.con_time.kirin_time, time_delta=0)
+            else:
+                logger.info('Today is the Netherworld day')
+                self.custom_next_run(task='Hunt', custom_time=self.con_time.netherworld_time, time_delta=0)
             raise TaskEnd('Hunt')
             raise TaskEnd('Hunt')
-        # 如果是在21:00-23:59之间则设定时间为明天的19:00,返回False
+        # 如果是在21:00-23:59之间则设定时间为明天的自定义时间,返回False
         elif now.time() > time(21, 0):
         elif now.time() > time(21, 0):
-            next_run = datetime.combine(now.date() + timedelta(days=1), time(19, 0))
-            self.set_next_run(task='Hunt', success=False, finish=True, target=next_run)
+            self.plan_tomorrow_hunt()
             raise TaskEnd('Hunt')
             raise TaskEnd('Hunt')
         # 如果是在19:00-21:00之间则返回True
         # 如果是在19:00-21:00之间则返回True
         else:
         else:
             return True
             return True
 
 
+    def plan_tomorrow_hunt(self):
+        # 安排次日狩猎战,便于复用
+        if self.tomorrow_kirin_day:
+            logger.info('Tomorrow is the Kirin day')
+            self.custom_next_run(task='Hunt', custom_time=self.con_time.kirin_time, time_delta=1)
+        else:
+            logger.info('Tomorrow is the Netherworld day')
+            self.custom_next_run(task='Hunt', custom_time=self.con_time.netherworld_time, time_delta=1)
 
 
     def kirin(self):
     def kirin(self):
         logger.hr('kirin', 2)
         logger.hr('kirin', 2)
@@ -85,7 +102,7 @@ class ScriptTask(GameUi, GeneralBattle, GeneralInvite, SwitchSoul, HuntAssets):
             if self.appear(self.I_KIRIN_END):
             if self.appear(self.I_KIRIN_END):
                 # 你的阴阳寮已经打过的麒麟了
                 # 你的阴阳寮已经打过的麒麟了
                 logger.warning('Your guild have already challenged the Kirin')
                 logger.warning('Your guild have already challenged the Kirin')
-                self.set_next_run(task='Hunt', success=True, finish=True)
+                self.plan_tomorrow_hunt()
                 raise TaskEnd('Hunt')
                 raise TaskEnd('Hunt')
             if self.appear_then_click(self.I_KIRIN_CHALLAGE, interval=0.9):
             if self.appear_then_click(self.I_KIRIN_CHALLAGE, interval=0.9):
                 break
                 break

+ 1 - 1
tasks/KekkaiActivation/config.py

@@ -12,7 +12,7 @@ from tasks.Component.config_base import ConfigBase, TimeDelta
 from tasks.Utils.config_enum import ShikigamiClass
 from tasks.Utils.config_enum import ShikigamiClass
 
 
 class ActivationScheduler(Scheduler):
 class ActivationScheduler(Scheduler):
-    priority = Field(default=2, description='priority_help')
+    priority: int = Field(default=2, description='priority_help')
     success_interval: TimeDelta = Field(default=TimeDelta(days=1), description='success_interval_help')
     success_interval: TimeDelta = Field(default=TimeDelta(days=1), description='success_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(hours=10), description='failure_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(hours=10), description='failure_interval_help')
 
 

+ 1 - 1
tasks/KekkaiUtilize/config.py

@@ -22,7 +22,7 @@ class UtilizeRule(str, Enum):
 
 
 
 
 class UtilizeScheduler(Scheduler):
 class UtilizeScheduler(Scheduler):
-    priority = Field(default=2, description='priority_help')
+    priority: int = Field(default=2, description='priority_help')
     success_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='success_interval_help')
     success_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='success_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='failure_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(hours=6), description='failure_interval_help')
 
 

+ 1 - 1
tasks/Restart/login.py

@@ -99,7 +99,7 @@ class LoginHandler(BaseTask, RestartAssets):
             if self.appear(self.I_LOGIN_SPECIFIC_SERVE, interval=0.6) \
             if self.appear(self.I_LOGIN_SPECIFIC_SERVE, interval=0.6) \
                     and self.ocr_appear_click(self.O_LOGIN_SPECIFIC_SERVE, interval=0.6):
                     and self.ocr_appear_click(self.O_LOGIN_SPECIFIC_SERVE, interval=0.6):
                 self.ui_click(self.C_LOGIN_ENSURE_LOGIN_CHARACTER_IN_SAME_SVR,
                 self.ui_click(self.C_LOGIN_ENSURE_LOGIN_CHARACTER_IN_SAME_SVR,
-                              stop=self.I_LOGIN_SPECIFIC_SERVE, interval=2)
+                              stop=self.I_LOGIN_SCROOLL_CLOSE, interval=2)
                 logger.info('login specific user')
                 logger.info('login specific user')
                 continue
                 continue
             # 点击’进入游戏‘
             # 点击’进入游戏‘

+ 1 - 1
tasks/RichMan/assets.py

@@ -301,7 +301,7 @@ class RichManAssets:
 
 
 	# Click Rule Assets
 	# Click Rule Assets
 	# description 
 	# description 
-	C_C_SHRINE = RuleClick(roi_front=(1098,261,56,100), roi_back=(1098,261,56,100), name="c_shrine")
+	C_C_SHRINE = RuleClick(roi_front=(1167,303,102,164), roi_back=(1167,303,102,164), name="c_shrine")
 
 
 
 
 	# Image Rule Assets
 	# Image Rule Assets

+ 2 - 2
tasks/RichMan/shrine/click.json

@@ -1,8 +1,8 @@
 [
 [
   {
   {
     "itemName": "c_shrine",
     "itemName": "c_shrine",
-    "roiFront": "1098,261,56,100",
-    "roiBack": "1098,261,56,100",
+    "roiFront": "1167,303,102,164",
+    "roiBack": "1167,303,102,164",
     "description": "description"
     "description": "description"
   }
   }
 ]
 ]

+ 2 - 0
tasks/RyouToppa/config.py

@@ -12,6 +12,8 @@ class RaidConfig(BaseModel):
     limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     limit_time: Time = Field(default=Time(minute=30), description='limit_time_help')
     # 限制次数
     # 限制次数
     limit_count: int = Field(default=50, description='limit_count_help')
     limit_count: int = Field(default=50, description='limit_count_help')
+    # 攻破完成后指定下次运行时间
+    next_ryoutoppa_time: Time = Field(default=Time(hour=7, minute=0, second=0))
     # 是否跳过难度较高的结界,失败后不再攻打该结界
     # 是否跳过难度较高的结界,失败后不再攻打该结界
     skip_difficult: bool = Field(default=True, description='skip_difficult_help')
     skip_difficult: bool = Field(default=True, description='skip_difficult_help')
     # 寮管理开启寮突破
     # 寮管理开启寮突破

+ 17 - 5
tasks/RyouToppa/script_task.py

@@ -2,7 +2,7 @@
 # @author runhey
 # @author runhey
 # github https://github.com/runhey
 # github https://github.com/runhey
 import time
 import time
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, time as dt_time
 import random
 import random
 
 
 from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
 from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
@@ -144,7 +144,8 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, RyouToppaAssets):
 
 
         # 100% 攻破, 第二天再执行
         # 100% 攻破, 第二天再执行
         if ryou_toppa_success_penetration:
         if ryou_toppa_success_penetration:
-            self.set_next_run(task='RyouToppa', finish=True, success=True)
+            logger.info('RyouToppa is 100%')
+            self.plan_tomorrow_ryoutoppa()
             raise TaskEnd
             raise TaskEnd
         if self.config.ryou_toppa.general_battle_config.lock_team_enable:
         if self.config.ryou_toppa.general_battle_config.lock_team_enable:
             logger.info("Lock team.")
             logger.info("Lock team.")
@@ -189,6 +190,16 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, RyouToppaAssets):
             self.set_next_run(task='RyouToppa', finish=True, server=True, success=False)
             self.set_next_run(task='RyouToppa', finish=True, server=True, success=False)
         raise TaskEnd
         raise TaskEnd
 
 
+    def plan_tomorrow_ryoutoppa(self):
+        # 安排下次寮突破,便于复用
+        now = datetime.now()
+        # 如果时间在00:00-5:00之间则设定时间为当天的自定义时间
+        if now.time() < dt_time(5, 0):  # 不确定 time 的使用范围,重命名 datetime 中的 time
+            self.custom_next_run(task='RyouToppa', custom_time=self.config.ryou_toppa.raid_config.next_ryoutoppa_time, time_delta=0)
+        # 如果时间在05:00-23:59之间则设定时间为明天的自定义时间
+        else:
+            self.custom_next_run(task='RyouToppa', custom_time=self.config.ryou_toppa.raid_config.next_ryoutoppa_time, time_delta=1)
+
     def start_ryou_toppa(self):
     def start_ryou_toppa(self):
         """
         """
         开启寮突破
         开启寮突破
@@ -223,8 +234,8 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, RyouToppaAssets):
         如果没有票了,那么就返回False
         如果没有票了,那么就返回False
         :return:
         :return:
         """
         """
-        # 21点后无限进攻机会
-        if datetime.now().hour >= 21:
+        # 21点后、次日5点前无限进攻机会
+        if datetime.now().hour >= 21 or datetime.now().hour <= 5:
             return True
             return True
         self.wait_until_appear(self.I_TOPPA_RECORD)
         self.wait_until_appear(self.I_TOPPA_RECORD)
         self.screenshot()
         self.screenshot()
@@ -245,7 +256,8 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, RyouToppaAssets):
         # 如果该区域已经被攻破则退出
         # 如果该区域已经被攻破则退出
         # Ps: 这时候能打过的都打过了,没有能攻打的结界了, 代表任务已经完成,set_next_run time=1d
         # Ps: 这时候能打过的都打过了,没有能攻打的结界了, 代表任务已经完成,set_next_run time=1d
         if self.appear(f3, threshold=0.8) or self.appear(f4, threshold=0.8):
         if self.appear(f3, threshold=0.8) or self.appear(f4, threshold=0.8):
-            self.set_next_run(task='RyouToppa', finish=True, success=True)
+            logger.info('RyouToppa has tried to attack')
+            self.plan_tomorrow_ryoutoppa()
             raise TaskEnd
             raise TaskEnd
         # 如果该区域攻略失败返回 False
         # 如果该区域攻略失败返回 False
         if self.appear(f1, threshold=0.8) or self.appear(f2, threshold=0.8):
         if self.appear(f1, threshold=0.8) or self.appear(f2, threshold=0.8):

+ 1 - 0
tasks/Script/config_device.py

@@ -12,6 +12,7 @@ class PackageName(str, Enum):
     NETEASE_MI = 'com.netease.onmyoji.mi'  # 小米
     NETEASE_MI = 'com.netease.onmyoji.mi'  # 小米
     NETEASE = 'com.netease.onmyoji'
     NETEASE = 'com.netease.onmyoji'
     NETEASE_HUAWEI = 'com.netease.onmyoji.huawei'
     NETEASE_HUAWEI = 'com.netease.onmyoji.huawei'
+    NETEASE_BILIBILI = 'com.netease.onmyoji.bili'
 
 
 class ScreenshotMethod(str, Enum):
 class ScreenshotMethod(str, Enum):
     AUTO = 'auto'
     AUTO = 'auto'

+ 1 - 1
tasks/TrueOrochi/config.py

@@ -22,7 +22,7 @@ class GreenMarkType(str, Enum):
 
 
 
 
 class TrueOrochiScheduler(Scheduler):
 class TrueOrochiScheduler(Scheduler):
-    priority = Field(default=10, description='priority_help')
+    priority: int = Field(default=10, description='priority_help')
     success_interval: TimeDelta = Field(default=TimeDelta(days=7), description='success_interval_help')
     success_interval: TimeDelta = Field(default=TimeDelta(days=7), description='success_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(days=1), description='failure_interval_help')
     failure_interval: TimeDelta = Field(default=TimeDelta(days=1), description='failure_interval_help')
 
 

+ 4 - 0
tasks/WantedQuests/assets.py

@@ -167,5 +167,9 @@ class WantedQuestsAssets:
 	# Image Rule Assets
 	# Image Rule Assets
 	# 奇怪了之前的不能用 
 	# 奇怪了之前的不能用 
 	I_WQSE_FIRE = RuleImage(roi_front=(1041,556,100,100), roi_back=(1016,534,147,138), threshold=0.8, method="Template matching", file="./tasks/WantedQuests/wq/wq_wqse_fire.png")
 	I_WQSE_FIRE = RuleImage(roi_front=(1041,556,100,100), roi_back=(1016,534,147,138), threshold=0.8, method="Template matching", file="./tasks/WantedQuests/wq/wq_wqse_fire.png")
+	# 妖气封印 
+	I_WQ_D1111 = RuleImage(roi_front=(20,171,99,105), roi_back=(6,148,150,299), threshold=0.8, method="Template matching", file="./tasks/WantedQuests/wq/wq_wq_d1111.png")
+	# 年兽 
+	I_WQ_NIAN = RuleImage(roi_front=(19,176,100,100), roi_back=(0,153,166,273), threshold=0.8, method="Template matching", file="./tasks/WantedQuests/wq/wq_wq_nian.png")
 
 
 
 

+ 9 - 0
tasks/WantedQuests/script_task.py

@@ -63,6 +63,9 @@ class ScriptTask(WQExplore, SecretScriptTask, WantedQuestsAssets):
             if self.appear(self.I_WQ_BOX):
             if self.appear(self.I_WQ_BOX):
                 self.ui_get_reward(self.I_WQ_BOX)
                 self.ui_get_reward(self.I_WQ_BOX)
                 continue
                 continue
+            if self.appear(self.I_TREASURE_BOX_CLICK):
+                self.ui_get_reward(self.I_TREASURE_BOX_CLICK)
+                continue
             if ocr_error_count > 10:
             if ocr_error_count > 10:
                 logger.warning('OCR failed too many times, exit')
                 logger.warning('OCR failed too many times, exit')
                 break
                 break
@@ -97,6 +100,12 @@ class ScriptTask(WQExplore, SecretScriptTask, WantedQuestsAssets):
                     self.execute_mission(self.O_WQ_TEXT_2, min(total, 20), number_challenge)
                     self.execute_mission(self.O_WQ_TEXT_2, min(total, 20), number_challenge)
                 continue
                 continue
 
 
+            # 妖气封印或者年兽,那就四分钟后继续
+            if self.appear(self.I_WQ_D1111) or self.appear(self.I_WQ_NIAN):
+                logger.warning('Tiger is in the way, wait for 4 minutes')
+                logger.info('Time to wait for 4 minutes')
+                self.set_next_run('WantedQuests', target=datetime.now() + timedelta(minutes=4))
+                raise TaskEnd('WantedQuests')
             if self.appear(self.I_WQ_CHECK_TASK):
             if self.appear(self.I_WQ_CHECK_TASK):
                 continue
                 continue
             sleep(1.5)
             sleep(1.5)

+ 18 - 0
tasks/WantedQuests/wq/se_image.json

@@ -7,5 +7,23 @@
     "method": "Template matching",
     "method": "Template matching",
     "threshold": 0.8,
     "threshold": 0.8,
     "description": "奇怪了之前的不能用"
     "description": "奇怪了之前的不能用"
+  },
+  {
+    "itemName": "wq_d1111",
+    "imageName": "wq_wq_d1111.png",
+    "roiFront": "20,171,99,105",
+    "roiBack": "6,148,150,299",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "妖气封印"
+  },
+  {
+    "itemName": "wq_nian",
+    "imageName": "wq_wq_nian.png",
+    "roiFront": "19,176,100,100",
+    "roiBack": "0,153,166,273",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "年兽"
   }
   }
 ]
 ]

二進制
tasks/WantedQuests/wq/wq_wq_d1111.png


二進制
tasks/WantedQuests/wq/wq_wq_nian.png


+ 11 - 0
tasks/base_task.py

@@ -27,6 +27,7 @@ from module.device.device import Device
 from tasks.GlobalGame.assets import GlobalGameAssets
 from tasks.GlobalGame.assets import GlobalGameAssets
 from tasks.GlobalGame.config_emergency import FriendInvitation, WhenNetworkAbnormal, WhenNetworkError
 from tasks.GlobalGame.config_emergency import FriendInvitation, WhenNetworkAbnormal, WhenNetworkError
 from tasks.Component.Costume.costume_base import CostumeBase
 from tasks.Component.Costume.costume_base import CostumeBase
+from tasks.Component.config_base import ConfigBase, Time
 
 
 from module.exception import GameStuckError, ScriptError
 from module.exception import GameStuckError, ScriptError
 
 
@@ -510,6 +511,16 @@ class BaseTask(GlobalGameAssets, CostumeBase):
             start_time = self.start_time
             start_time = self.start_time
         self.config.task_delay(task, start_time=start_time, success=success, server=server, target=target)
         self.config.task_delay(task, start_time=start_time, success=success, server=server, target=target)
 
 
+    def custom_next_run(self, task: str, custom_time: Time = None, time_delta: float = 1) -> None:
+        """
+        设置下次自定义运行时间
+        :param task: 任务名称,大驼峰的
+        :param custom_time: 可以自定义的下次运行时间
+        :param time_delta: 下次运行日期为几天后,默认为第二天
+        :return:
+        """
+        target_time = (datetime.now() + timedelta(days=time_delta)).replace(hour=custom_time.hour, minute=custom_time.minute, second=custom_time.second)
+        self.set_next_run(task, target=target_time)
     #  ---------------------------------------------------------------------------------------------------------------
     #  ---------------------------------------------------------------------------------------------------------------
     #
     #
     #  ---------------------------------------------------------------------------------------------------------------
     #  ---------------------------------------------------------------------------------------------------------------