Просмотр исходного кода

Merge pull request #1766 from runhey/dev

Dev to master
huangrunheng 2 месяцев назад
Родитель
Сommit
8c287fac4f
33 измененных файлов с 332 добавлено и 181 удалено
  1. 43 0
      .github/workflows/auto-merge-pr.yaml
  2. 2 1
      assets/i18n/zh-CN.json
  3. 54 0
      module/config/anti_ban.py
  4. 3 0
      module/device/screenshot.py
  5. 5 44
      script.py
  6. 4 4
      tasks/Component/CostumeShikigami/assets.py
  7. 1 1
      tasks/Component/CostumeShikigami/sk2/image.json
  8. 1 1
      tasks/Component/CostumeShikigami/sk3/image.json
  9. 1 1
      tasks/Component/CostumeShikigami/sk4/image.json
  10. 1 1
      tasks/Component/CostumeShikigami/sk5/image.json
  11. 2 0
      tasks/Component/GeneralInvite/assets.py
  12. 3 0
      tasks/Component/GeneralInvite/general_invite.py
  13. BIN
      tasks/Component/GeneralInvite/gi/gi_gi_speak.png
  14. 9 0
      tasks/Component/GeneralInvite/gi/image.json
  15. 2 0
      tasks/DailyTrifles/assets.py
  16. 10 1
      tasks/DailyTrifles/love/image.json
  17. BIN
      tasks/DailyTrifles/love/love_friend_tab.png
  18. 3 1
      tasks/DailyTrifles/script_task.py
  19. 41 0
      tasks/EternitySea/script_task.py
  20. 1 1
      tasks/GameUi/assets.py
  21. 11 4
      tasks/GameUi/game_ui.py
  22. BIN
      tasks/GameUi/page/page_check_friends.png
  23. 3 3
      tasks/GameUi/page/page_img_3.json
  24. 6 1
      tasks/GuildActivityMonitor/assets.py
  25. 3 3
      tasks/GuildActivityMonitor/config.py
  26. 11 0
      tasks/GuildActivityMonitor/res/ocr.json
  27. 94 96
      tasks/GuildActivityMonitor/script_task.py
  28. 1 1
      tasks/Restart/assets.py
  29. 7 0
      tasks/Restart/login.py
  30. 2 2
      tasks/Restart/login/ocr.json
  31. 2 3
      tasks/RichMan/mall/honor.py
  32. 3 9
      tasks/RichMan/mall/special.py
  33. 3 3
      tasks/RyouToppa/script_task.py

+ 43 - 0
.github/workflows/auto-merge-pr.yaml

@@ -0,0 +1,43 @@
+name: Auto Merge Sync PR
+
+on:
+  schedule:
+    # 每周五北京时间12点触发(UTC时间4点)
+    - cron: '0 4 * * 5'
+  workflow_dispatch:
+
+permissions:
+  contents: write
+  pull-requests: write
+
+jobs:
+  merge-pr:
+    runs-on: ubuntu-latest
+    steps:
+      - name: Find automated sync PR
+        id: pr
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+          GH_REPO: ${{ github.repository }}
+        run: |
+          PR_NUMBER=$(gh pr list \
+            --base master \
+            --head dev \
+            --state open \
+            --label automated \
+            --json number \
+            --jq '.[0].number')
+
+          if [ -z "$PR_NUMBER" ]; then
+            echo "No open automated sync PR found."
+            exit 0
+          fi
+
+          echo "number=$PR_NUMBER" >> "$GITHUB_OUTPUT"
+
+      - name: Merge automated sync PR
+        if: steps.pr.outputs.number != ''
+        env:
+          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+          GH_REPO: ${{ github.repository }}
+        run: gh pr merge "${{ steps.pr.outputs.number }}" --merge

+ 2 - 1
assets/i18n/zh-CN.json

@@ -69,5 +69,6 @@
   "long_rest_duration": "强制休息时长",
   "long_rest_duration_help": "触发累计活跃上限后的强制休息时长。格式:天 时:分:秒。",
   "min_run_interval": "最小再运行间隔",
-  "min_run_interval_help": "防风控:两次蹭卡运行之间的最小间隔,避免蹭卡过于频繁被服务端标记。设为 0(默认)保持原逻辑(按结界卡剩余时间安排下次)。格式:天 时:分:秒。"
+  "min_run_interval_help": "防风控:两次蹭卡运行之间的最小间隔,避免蹭卡过于频繁被服务端标记。设为 0(默认)保持原逻辑(按结界卡剩余时间安排下次)。格式:天 时:分:秒。",
+  "costume_shikigami_11": "花札幕台"
 }

+ 54 - 0
module/config/anti_ban.py

@@ -0,0 +1,54 @@
+# This Python file uses the following encoding: utf-8
+"""防风控作息看守器: 睡眠窗 / 每日活跃上限 / 强制长休息, 由 Script 持有。"""
+from datetime import datetime, timedelta
+
+
+class AntiBanGuard:
+    def __init__(self) -> None:
+        self.reset()
+
+    def reset(self) -> None:
+        self._active_date = None
+        self._active_seconds_today = 0.0
+        self._rest_until = None
+
+    @staticmethod
+    def _in_sleep_window(t, start, end) -> bool:
+        if start == end:
+            return False
+        if start < end:
+            return start <= t < end
+        return t >= start or t < end
+
+    @staticmethod
+    def _next_time_point(now: datetime, end) -> datetime:
+        candidate = now.replace(hour=end.hour, minute=end.minute, second=end.second, microsecond=0)
+        if candidate <= now:
+            candidate += timedelta(days=1)
+        return candidate
+
+    def _roll_day(self, today) -> None:
+        if self._active_date != today:
+            self._active_date = today
+            self._active_seconds_today = 0.0
+
+    def record_active(self, seconds: float) -> None:
+        self._roll_day(datetime.now().date())
+        self._active_seconds_today += seconds
+
+    def wake_time(self, now: datetime, config):
+        if not config.enable:
+            return None
+        wake = None
+        if self._in_sleep_window(now.time(), config.sleep_start, config.sleep_end):
+            wake = self._next_time_point(now, config.sleep_end)
+        limit = config.daily_active_limit.total_seconds()
+        if limit > 0:
+            self._roll_day(now.date())
+            if self._rest_until and now < self._rest_until:
+                wake = max(wake, self._rest_until) if wake else self._rest_until
+            elif self._active_seconds_today >= limit:
+                self._rest_until = now + config.long_rest_duration
+                self._active_seconds_today = 0.0
+                wake = max(wake, self._rest_until) if wake else self._rest_until
+        return wake

+ 3 - 0
module/device/screenshot.py

@@ -232,6 +232,9 @@ class Screenshot(Adb, DroidCast, Scrcpy, Window, NemuIpc):
                 logger.critical('Please set emulator resolution to 1280x720')
                 raise RequestHumanTakeover
 
+    def check_screen_size_sample(self):
+        return self.image.shape  == (720, 1280, 3)
+
     def check_screen_black(self):
         if self._screen_black_checked:
             return True

+ 5 - 44
script.py

@@ -30,6 +30,7 @@ from module.config.utils import convert_to_underscore
 from module.config.config import Config
 from module.config.config_model import ConfigModel
 from module.config.instance_guard import InstanceGuard
+from module.config.anti_ban import AntiBanGuard
 from module.device.device import Device
 from module.device.env import IS_WINDOWS
 from module.base.utils import load_module
@@ -61,6 +62,7 @@ class Script:
         self.loop_thread: Thread = None
         # 跨进程排队管理器(仅在 queue_mode=True 时初始化)
         self.instance_guard: InstanceGuard = None
+        self.anti_ban_guard: AntiBanGuard = AntiBanGuard()
 
     @cached_property
     def config(self) -> "Config":
@@ -318,42 +320,6 @@ class Script:
             if self.config.should_reload():
                 return False
 
-    @staticmethod
-    def _in_sleep_window(t, start, end) -> bool:
-        if start == end:
-            return False
-        if start < end:
-            return start <= t < end
-        return t >= start or t < end
-
-    @staticmethod
-    def _next_time_point(now: datetime, end) -> datetime:
-        candidate = now.replace(hour=end.hour, minute=end.minute, second=end.second, microsecond=0)
-        if candidate <= now:
-            candidate += timedelta(days=1)
-        return candidate
-
-    def _antiban_wake_time(self, now: datetime):
-        ab = self.config.script.anti_ban
-        if not ab.enable:
-            return None
-        wake = None
-        if self._in_sleep_window(now.time(), ab.sleep_start, ab.sleep_end):
-            wake = self._next_time_point(now, ab.sleep_end)
-        limit = ab.daily_active_limit.total_seconds()
-        if limit > 0:
-            if getattr(self, '_active_date', None) != now.date():
-                self._active_date = now.date()
-                self._active_seconds_today = 0
-            rest_until = getattr(self, '_rest_until', None)
-            if rest_until and now < rest_until:
-                wake = max(wake, rest_until) if wake else rest_until
-            elif getattr(self, '_active_seconds_today', 0) >= limit:
-                self._rest_until = now + ab.long_rest_duration
-                self._active_seconds_today = 0
-                wake = max(wake, self._rest_until) if wake else self._rest_until
-        return wake
-
     def get_next_task(self) -> str:
         """
         获取下一个任务的名字, 大驼峰。
@@ -365,7 +331,7 @@ class Script:
             if self.state_queue:
                 self.state_queue.put({"schedule": self.config.get_schedule_data()})
             now = datetime.now()
-            antiban_wake = self._antiban_wake_time(now)
+            antiban_wake = self.anti_ban_guard.wake_time(now, self.config.script.anti_ban)
             if antiban_wake is not None:
                 task.next_run = max(task.next_run, antiban_wake)
             if not self._try_acquire_queue_token():
@@ -664,9 +630,7 @@ class Script:
         start_day = date.today()
         logger.info(f'Start scheduler loop: {self.config_name}')
         self.config.model.running_task = ''
-        self._active_seconds_today = 0
-        self._active_date = date.today()
-        self._rest_until = None
+        self.anti_ban_guard.reset()
 
         # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
         if not self.config.script.device.run_background_only and IS_WINDOWS:
@@ -727,10 +691,7 @@ class Script:
             self.config.model.running_task = ''
             logger.info(f'Scheduler: End task `{task}`')
             self.is_first_task = False
-            if self._active_date != date.today():
-                self._active_date = date.today()
-                self._active_seconds_today = 0
-            self._active_seconds_today += (datetime.now() - _task_start).total_seconds()
+            self.anti_ban_guard.record_active((datetime.now() - _task_start).total_seconds())
 
             # Check failures
             # failed = deep_get(self.failure_record, keys=task, default=0)

+ 4 - 4
tasks/Component/CostumeShikigami/assets.py

@@ -179,7 +179,7 @@ class CostumeShikigamiAssets:
 	# 点击御魂 
 	I_ST_SOULS_2 = RuleImage(roi_front=(1176,227,70,80), roi_back=(1181,234,58,69), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk2/sk2_st_souls_2.png")
 	# 更换 
-	I_ST_REPLACE_2 = RuleImage(roi_front=(861,150,100,100), roi_back=(872,169,78,63), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk2/sk2_st_replace_2.png")
+	I_ST_REPLACE_2 = RuleImage(roi_front=(861,150,100,100), roi_back=(861,150,100,100), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk2/sk2_st_replace_2.png")
 
 
 	# Image Rule Assets
@@ -222,7 +222,7 @@ class CostumeShikigamiAssets:
 	# 点击御魂 
 	I_ST_SOULS_3 = RuleImage(roi_front=(1176,227,70,80), roi_back=(1181,234,58,69), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk3/sk3_st_souls_3.png")
 	# 更换 
-	I_ST_REPLACE_3 = RuleImage(roi_front=(860,168,100,100), roi_back=(872,186,78,63), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk3/sk3_st_replace_3.png")
+	I_ST_REPLACE_3 = RuleImage(roi_front=(860,168,100,100), roi_back=(860,168,100,100), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk3/sk3_st_replace_3.png")
 
 
 	# Image Rule Assets
@@ -265,7 +265,7 @@ class CostumeShikigamiAssets:
 	# 点击御魂 
 	I_ST_SOULS_4 = RuleImage(roi_front=(1176,227,70,80), roi_back=(1181,234,58,69), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk4/sk4_st_souls_4.png")
 	# 更换 
-	I_ST_REPLACE_4 = RuleImage(roi_front=(860,168,100,100), roi_back=(872,186,78,63), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk4/sk4_st_replace_4.png")
+	I_ST_REPLACE_4 = RuleImage(roi_front=(860,168,100,100), roi_back=(860,168,100,100), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk4/sk4_st_replace_4.png")
 
 
 	# Image Rule Assets
@@ -308,7 +308,7 @@ class CostumeShikigamiAssets:
 	# 点击御魂 
 	I_ST_SOULS_5 = RuleImage(roi_front=(1176,227,70,80), roi_back=(1181,234,58,69), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk5/sk5_st_souls_5.png")
 	# 更换 
-	I_ST_REPLACE_5 = RuleImage(roi_front=(860,168,100,100), roi_back=(872,186,78,63), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk5/sk5_st_replace_5.png")
+	I_ST_REPLACE_5 = RuleImage(roi_front=(860,168,100,100), roi_back=(860,168,100,100), threshold=0.8, method="Template matching", file="./tasks/Component/CostumeShikigami/sk5/sk5_st_replace_5.png")
 
 
 	# Image Rule Assets

+ 1 - 1
tasks/Component/CostumeShikigami/sk2/image.json

@@ -174,7 +174,7 @@
     "itemName": "st_replace_2",
     "imageName": "sk2_st_replace_2.png",
     "roiFront": "861,150,100,100",
-    "roiBack": "872,169,78,63",
+    "roiBack": "861,150,100,100",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "更换"

+ 1 - 1
tasks/Component/CostumeShikigami/sk3/image.json

@@ -174,7 +174,7 @@
     "itemName": "st_replace_3",
     "imageName": "sk3_st_replace_3.png",
     "roiFront": "860,168,100,100",
-    "roiBack": "872,186,78,63",
+    "roiBack": "860,168,100,100",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "更换"

+ 1 - 1
tasks/Component/CostumeShikigami/sk4/image.json

@@ -174,7 +174,7 @@
     "itemName": "st_replace_4",
     "imageName": "sk4_st_replace_4.png",
     "roiFront": "860,168,100,100",
-    "roiBack": "872,186,78,63",
+    "roiBack": "860,168,100,100",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "更换"

+ 1 - 1
tasks/Component/CostumeShikigami/sk5/image.json

@@ -174,7 +174,7 @@
     "itemName": "st_replace_5",
     "imageName": "sk5_st_replace_5.png",
     "roiFront": "860,168,100,100",
-    "roiBack": "872,186,78,63",
+    "roiBack": "860,168,100,100",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "更换"

+ 2 - 0
tasks/Component/GeneralInvite/assets.py

@@ -95,6 +95,8 @@ class GeneralInviteAssets:
 	I_BACK_YELLOW_SEA = RuleImage(roi_front=(31,16,42,42), roi_back=(31,16,42,42), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_back_yellow_sea.png")
 	# 识别到寄养邀请 
 	I_I_ACCEPT_JY = RuleImage(roi_front=(248,258,46,25), roi_back=(231,205,75,326), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_i_accept_jy.png")
+	# 房间左下角发言按钮(永生之海房间无表情按钮, 用此图识别) 
+	I_GI_SPEAK = RuleImage(roi_front=(23,503,82,85), roi_back=(23,503,82,85), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_gi_speak.png")
 
 
 	# Image Rule Assets

+ 3 - 0
tasks/Component/GeneralInvite/general_invite.py

@@ -165,6 +165,9 @@ class GeneralInvite(BaseTask, GeneralInviteAssets):
             return True
         if self.appear(self.I_GI_EMOJI_2):
             return True
+        # 永生之海房间没有表情按钮, 用左下角发言按钮识别
+        if self.appear(self.I_GI_SPEAK):
+            return True
         # if self.appear(self.I_MATCHING):
         #     return False
         return False

BIN
tasks/Component/GeneralInvite/gi/gi_gi_speak.png


+ 9 - 0
tasks/Component/GeneralInvite/gi/image.json

@@ -376,5 +376,14 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "识别到寄养邀请"
+  },
+  {
+    "itemName": "gi_speak",
+    "imageName": "gi_gi_speak.png",
+    "roiFront": "23,503,82,85",
+    "roiBack": "23,503,82,85",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "房间左下角发言按钮(永生之海房间无表情按钮, 用此图识别)"
   }
 ]

+ 2 - 0
tasks/DailyTrifles/assets.py

@@ -25,6 +25,8 @@ class DailyTriflesAssets:
 	I_LUCK_TITLE = RuleImage(roi_front=(600,52,131,67), roi_back=(600,52,131,67), threshold=0.8, method="Template matching", file="./tasks/DailyTrifles/love/Screenshots_luck_title.png")
 	# 好友羁绊提升弹窗 
 	I_FRIENDSHIP_UP = RuleImage(roi_front=(1147,80,27,28), roi_back=(1147,80,27,28), threshold=0.8, method="Template matching", file="./tasks/DailyTrifles/love/friendship_up.png")
+	#  
+	I_FRIEND_TAB = RuleImage(roi_front=(143,95,97,49), roi_back=(119,82,151,70), threshold=0.8, method="Template matching", file="./tasks/DailyTrifles/love/love_friend_tab.png")
 
 
 	# Image Rule Assets

+ 10 - 1
tasks/DailyTrifles/love/image.json

@@ -61,5 +61,14 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "好友羁绊提升弹窗"
+  },
+  {
+    "itemName": "friend_tab",
+    "imageName": "love_friend_tab.png",
+    "roiFront": "143,95,97,49",
+    "roiBack": "119,82,151,70",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": ""
   }
-]
+]

BIN
tasks/DailyTrifles/love/love_friend_tab.png


+ 3 - 1
tasks/DailyTrifles/script_task.py

@@ -194,6 +194,8 @@ class ScriptTask(GameUi, Summon, DailyTriflesAssets):
                 continue
             if self.appear_then_click(self.I_L_FRIENDS, interval=1):
                 continue
+            if self.appear_then_click(self.I_FRIEND_TAB, interval=3):
+                continue
         logger.info('Start friend love')
         check_timer = Timer(2)
         check_timer.start()
@@ -307,4 +309,4 @@ if __name__ == '__main__':
     d = Device(c)
     t = ScriptTask(c, d)
 
-    t.check_time()
+    t.run_friend_love()

+ 41 - 0
tasks/EternitySea/script_task.py

@@ -4,6 +4,7 @@
 from datetime import datetime, timedelta
 
 from module.exception import TaskEnd
+from module.base.timer import Timer
 from module.logger import logger
 
 from tasks.GameUi.game_ui import GameUi, Page
@@ -121,6 +122,8 @@ class ScriptTask(
                     is_first = False
                     self.run_general_battle(config=self._task_config.general_battle_config)
 
+        # 战斗奖励动画可能还未结束, 先点掉残留奖励弹窗等界面稳定, 防止exit_room识别不到房间
+        self._wait_room_stable()
         # 当结束或者是失败退出循环的时候只有两个UI的可能,在房间或者是在组队界面
         # 如果在房间就退出
         if self.exit_room():
@@ -129,6 +132,9 @@ class ScriptTask(
         if self.exit_team():
             pass
 
+        # 永生之海选层界面无HOME按钮且页面系统识别不了, 点返回箭头回到御魂副本选择界面
+        self._back_to_soul_zones()
+
         self.ui_get_current_page()
         self.ui_goto(page_main)
 
@@ -136,6 +142,41 @@ class ScriptTask(
             return False
         return True
 
+    def _wait_room_stable(self) -> None:
+        """
+        打完最后一局领取奖励后, 奖励弹窗/金币动画可能遮挡左下角导致房间识别失败, 等待界面稳定
+        """
+        logger.info('Wait room stable')
+        timer = Timer(8).start()
+        while not timer.reached():
+            self.screenshot()
+            if self.appear_then_click(self.I_REWARD, interval=1.5):
+                continue
+            if self.appear_then_click(self.I_REWARD_GOLD, interval=1.5):
+                continue
+            if not self.appear(self.I_REWARD) and not self.appear(self.I_REWARD_GOLD):
+                sleep(1)
+                return
+
+    def _back_to_soul_zones(self) -> None:
+        """
+        点返回箭头直到回到御魂副本选择界面(page_soul_zones可识别)
+        """
+        logger.info('Back to soul zones')
+        timer = Timer(15).start()
+        while not timer.reached():
+            self.screenshot()
+            if self.ui_page_appear(page_soul_zones):
+                return
+            if self.appear_then_click(self.I_GI_SURE, interval=1):
+                continue
+            if self.appear_then_click(self.I_BACK_YELLOW, interval=1):
+                continue
+            if self.appear_then_click(self.I_BACK_YELLOW_SEA, interval=1):
+                continue
+            if self.appear_then_click(self.I_BACK_BOTTOM, interval=1):
+                continue
+
 
     def run_member(self):
         logger.info('Start run member')

+ 1 - 1
tasks/GameUi/assets.py

@@ -167,7 +167,7 @@ class GameUiAssets:
 	# description 
 	I_CHECK_ONMYODO = RuleImage(roi_front=(1166,117,84,547), roi_back=(1166,117,84,547), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_onmyodo.png")
 	# description 
-	I_CHECK_FRIENDS = RuleImage(roi_front=(74,628,58,66), roi_back=(74,628,58,66), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_friends.png")
+	I_CHECK_FRIENDS = RuleImage(roi_front=(27,251,29,47), roi_back=(5,216,86,106), threshold=0.7, method="Template matching", file="./tasks/GameUi/page/page_check_friends.png")
 	# description 
 	I_CHECK_DAILY = RuleImage(roi_front=(28,515,58,62), roi_back=(1,487,154,145), threshold=0.8, method="Template matching", file="./tasks/GameUi/page/page_check_daily.png")
 	# description 

+ 11 - 4
tasks/GameUi/game_ui.py

@@ -282,14 +282,21 @@ class GameUi(BaseTask, GameUiAssets):
             # 跳转页面
             max_wait_timer = Timer(6).start()
             logger.info(f'Wait appear and operate {button} on {current_page}')
+            max_attempts_per_button = 3  # 每个按钮最多尝试 3 次
+            attempts_list = [0] * len(button) if isinstance(button, list) else None
             while not max_wait_timer.reached():
                 if timeout_timer.reached():
                     return False
                 if isinstance(button, list):
-                    exec_operates = [self.appear_then_operate(btn, interval=0.8, skip_first_screenshot=False)
-                                     for btn in button]
-                    if exec_operates[0]:  # 只要第一个成功就跳出
-                        break
+                    for idx, btn in enumerate(button):
+                        if attempts_list[idx] >= max_attempts_per_button:
+                            continue
+                        attempt =  self.appear_then_operate(btn, interval=0.8, skip_first_screenshot=False)
+                        if attempt:
+                            attempts_list[idx] += 1
+                        # 只要第一个成功就跳出
+                        if attempt and idx == 0:
+                            break
                 if self.appear_then_operate(button, interval=0.8, skip_first_screenshot=False):
                     break
             else:

BIN
tasks/GameUi/page/page_check_friends.png


+ 3 - 3
tasks/GameUi/page/page_img_3.json

@@ -92,10 +92,10 @@
   {
     "itemName": "check_friends",
     "imageName": "page_check_friends.png",
-    "roiFront": "74,628,58,66",
-    "roiBack": "74,628,58,66",
+    "roiFront": "27,251,29,47",
+    "roiBack": "5,216,86,106",
     "method": "Template matching",
-    "threshold": 0.8,
+    "threshold": 0.7,
     "description": "description"
   },
   {

+ 6 - 1
tasks/GuildActivityMonitor/assets.py

@@ -8,5 +8,10 @@ from module.atom.list import RuleList
 # This file was automatically generated by ./dev_tools/assets_extract.py.
 # Don't modify it manually.
 class GuildActivityMonitorAssets: 
-	pass
+
+
+	# Ocr Rule Assets
+	# 寮活动通知检测区域 
+	O_GUILD_ACTIVITY_NOTIFY = RuleOcr(roi=(13,213,457,86), area=(13,213,457,86), mode="Full", method="Default", keyword="", name="guild_activity_notify")
+
 

+ 3 - 3
tasks/GuildActivityMonitor/config.py

@@ -1,15 +1,15 @@
-from pydantic import Field
+from pydantic import BaseModel, Field
 
 from tasks.Component.config_scheduler import Scheduler
 from tasks.Component.config_base import ConfigBase
-from pydantic import BaseModel, Field
 
 class GuildActivityMonitorCombatTime(BaseModel):
     # 设置检测时间
-    detection_interval: int = Field(default=30, description="通知检测间隔(秒)\n通过adb检测系统中收到的活动推送,自动拉起对应任务")
+    detection_interval: int = Field(default=30, description="通知检测间隔(秒)\n通过adb/ocr检测收到的活动推送,自动拉起对应任务")
     monitor_duration: int = Field(default=15, description="监控持续时间(分)\n请确保已开启游戏通知权限,游戏设置权限中对应活动推送")
     recheck_interval: int = Field(default=5, description="拉起对应活动后,间隔多久再次开启检测(分)\n若监控时间内未检测到活动,则按调度器设置下次运行时间")
     run_days: str = Field(default="1,2,3,4,5,6,7", description="运行日期,1-7 对应周一到周日;例如 5,6,7")
+    use_ocr: bool = Field(default=False, description="启用OCR检测模式\n勾选: 通过OCR识别屏幕通知区域文字\n不勾选: 通过adb读取系统通知(默认)\n启用此项建议检测间隔改为1-5s左右")
 
 class GuildActivity(BaseModel):
     # 道馆

+ 11 - 0
tasks/GuildActivityMonitor/res/ocr.json

@@ -0,0 +1,11 @@
+[
+  {
+    "itemName": "guild_activity_notify",
+    "roiFront": "13,213,457,86",
+    "roiBack": "13,213,457,86",
+    "mode": "Full",
+    "method": "Default",
+    "keyword": "",
+    "description": "寮活动通知检测区域"
+  }
+]

+ 94 - 96
tasks/GuildActivityMonitor/script_task.py

@@ -1,27 +1,35 @@
 import re
 import time
 from datetime import datetime, timedelta
+
 from module.base.timer import Timer
 from module.exception import TaskEnd
 from module.logger import logger
 from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.page import page_main
+from tasks.GuildActivityMonitor.assets import GuildActivityMonitorAssets
 
 
-class ScriptTask(GameUi):
+class ScriptTask(GameUi, GuildActivityMonitorAssets):
 
     def run(self):
-        """ 阴阳寮活动监控主函数
+        """阴阳寮活动监控主函数"""
+        if not self.check_run_days():
+            raise TaskEnd('GuildActivityMonitor')
+        self.ui_get_current_page()
+        self.ui_goto(page_main)
+        keyword_map = self.build_keyword_map()
+        self.monitor_activities(keyword_map)
 
-        :return:
-        """
+    def check_run_days(self) -> bool:
+        """检查今天是否在运行日期内,设置下次运行时间"""
         monitor_config = self.config.guild_activity_monitor.guild_activity_monitor_combat_time
         now = datetime.now()
         today = now.weekday() + 1
         run_days = sorted({day for day in map(int, re.findall(r'\d+', monitor_config.run_days)) if 1 <= day <= 7})
         if not run_days:
             logger.warning(f"运行日期配置无效: {monitor_config.run_days},跳过 GuildActivityMonitor")
-            raise TaskEnd('GuildActivityMonitor')
+            return False
 
         in_run_days = today in run_days
         candidate_days = [day for day in run_days if day != today] if in_run_days else run_days
@@ -33,122 +41,112 @@ class ScriptTask(GameUi):
         next_target = datetime.combine(next_date.date(), server_update) if use_server_time else next_date
         status = '在' if in_run_days else '不在'
         action = '本次继续执行' if in_run_days else '跳过 GuildActivityMonitor'
-        logger.info(f"今天是周{today},{status}配置运行日期({monitor_config.run_days})内,"f"{action},下次运行时间: {next_target}")
-        self.set_next_run(task='GuildActivityMonitor',success=None,finish=False,server=False,target=next_target)
-        if not in_run_days:
-            raise TaskEnd('GuildActivityMonitor')
+        logger.info(f"今天是周{today},{status}配置运行日期({monitor_config.run_days})内,"
+                    f"{action},下次运行时间: {next_target}")
+        self.set_next_run(task='GuildActivityMonitor', success=None, finish=False, server=False, target=next_target)
+        return in_run_days
 
-        # 构建关键字映射
-        self.ui_get_current_page()
-        self.ui_goto(page_main)
+    def build_keyword_map(self) -> dict:
+        """构建活动关键字到任务名的映射"""
         guild_config = self.config.guild_activity_monitor.guild_activity
-        KEYWORD_MAP = {
+        keyword_map = {
             '道馆': 'Dokan' if guild_config.Dokan else None,
             '狭间': 'AbyssShadows' if guild_config.AbyssShadows else None,
             '宴会': 'GuildBanquet' if guild_config.GuildBanquet else None,
             '退治': 'DemonRetreat' if guild_config.DemonRetreat else None,
         }
-        KEYWORD_MAP = {k: v for k, v in KEYWORD_MAP.items() if v}
-        monitored_activities = list(KEYWORD_MAP.keys())
-        logger.info(f"监控活动: {monitored_activities}")
+        keyword_map = {k: v for k, v in keyword_map.items() if v}
+        logger.info(f"监控活动: {list(keyword_map.keys())}")
+        return keyword_map
 
-        # 初始化监控配置
+    def monitor_activities(self, keyword_map: dict):
+        """启动活动监控循环"""
         monitor_config = self.config.guild_activity_monitor.guild_activity_monitor_combat_time
-        duration_minutes = monitor_config.monitor_duration
         interval = monitor_config.detection_interval
-        logger.info(f"开始阴阳寮活动监控,持续{duration_minutes}分钟,每{interval}秒检测一次")
+        use_ocr = monitor_config.use_ocr
+        keywords = list(keyword_map.keys())
+        logger.info(f"开始阴阳寮活动监控,持续{monitor_config.monitor_duration}分钟,"
+                    f"每{interval}秒检测一次,模式: {'ocr' if use_ocr else 'adb'}")
 
-        # 初始化定时器
         check_timer = Timer(monitor_config.monitor_duration * 60)
         check_timer.start()
         log_timer = Timer(60)
         log_timer.start()
 
-        # 获取初始通知时间
-        init_time, _ = self.get_notification_info()
-
-        # 监控任务属于长等待场景,加入长等待白名单,避免被全局卡死检测误判
-        self.device.stuck_record_add('PAUSE')
-
-        # 主监控循环
-        try:
-            while True:
-                if check_timer.reached():
-                    logger.info("监控时间到,任务结束")
-                    raise TaskEnd('GuildActivityMonitor')
+        if use_ocr:
+            init_keyword = self.get_notification_info_ocr(keywords)
+            logger.info(f"初始通知关键字: {init_keyword or '无'}")
+        else:
+            init_time, _ = self.get_notification_info(keywords)
+
+        stuck_interval = Timer(280)
+        while True:
+            if not stuck_interval.started() or stuck_interval.reached():
+                self.device.stuck_record_clear()
+                self.device.stuck_record_add('PAUSE')
+                stuck_interval.reset()
+
+            if check_timer.reached():
+                logger.info("监控时间到,任务结束")
+                raise TaskEnd('GuildActivityMonitor')
+
+            if log_timer.reached():
+                remaining = int(check_timer.remain() // 60)
+                logger.info(f"监控中... 剩余时间: {remaining}分钟")
+                log_timer.reset()
+
+            self.screenshot()
+
+            if use_ocr:
+                notification_text = self.get_notification_info_ocr(keywords)
+                if notification_text and notification_text != init_keyword:
+                    self.trigger_activity_task(notification_text, keyword_map[notification_text])
+            else:
+                current_time, notification_text = self.get_notification_info(keywords)
+                if current_time > init_time and notification_text:
+                    task_name = keyword_map.get(notification_text)
+                    if task_name:
+                        self.trigger_activity_task(notification_text, task_name)
 
-                if log_timer.reached():
-                    remaining = int(check_timer.remain() // 60)
-                    logger.info(f"监控中... 剩余时间: {remaining}分钟")
-                    log_timer.reset()
+            time.sleep(interval)
 
-                # 处理突发事件
-                self.screenshot()
+    def trigger_activity_task(self, keyword, task_name):
+        """检测到活动关键字后拉起对应任务并结束监控"""
+        logger.info(f"检测到关键字 '{keyword}',启动任务: {task_name}")
+        monitor_config = self.config.guild_activity_monitor.guild_activity_monitor_combat_time
+        self.set_next_run(task=task_name, success=False, finish=False, server=False, target=datetime.now())
+        self.set_next_run(task='GuildActivityMonitor', success=False, finish=False, server=False,
+                          target=datetime.now() + timedelta(minutes=monitor_config.recheck_interval))
+        raise TaskEnd('GuildActivityMonitor')
 
-                # 检测新通知
-                current_time, notification_text = self.get_notification_info()
-                if current_time > init_time and notification_text:
-                    logger.info(f"检测到新通知: {notification_text}")
-                    for keyword, task_name in KEYWORD_MAP.items():
-                        if keyword in notification_text:
-                            logger.info(f"检测到关键字 '{keyword}',启动任务: {task_name}")
-                            self.set_next_run(task=task_name, success=False, finish=False, server=False, target=datetime.now())
-                            recheck_interval = monitor_config.recheck_interval
-                            self.set_next_run(task='GuildActivityMonitor', success=False, finish=False, server=False, target=datetime.now() + timedelta(minutes=recheck_interval))
-                            raise TaskEnd('GuildActivityMonitor')
-
-                time.sleep(interval)
-        finally:
-            self.device.stuck_record_clear()
-
-    def get_notification_info(self) -> tuple:
+    def get_notification_info(self, keywords: list) -> tuple:
+        """通过adb读取系统通知,返回最新活动通知的时间戳和关键字"""
         try:
             output = self.device.adb_shell(['dumpsys', 'notification', '--noredact'])
-
-            # 通知时间提取逻辑 - 只获取最新的通知
-            notification_time = 0
-            notification_text = ""
-
-            # 查找所有通知块,每个块包含时间戳和文本
             notification_blocks = re.findall(r'(when=(\d+)[\s\S]*?(?=when=|\Z))', output)
-            
-            if notification_blocks:
-                # 找到最新的通知块
-                latest_block_time = 0
-                latest_text = ""
-                
-                for block, time_str in notification_blocks:
-                    current_time = float(time_str)
-                    if current_time > latest_block_time:
-                        latest_block_time = current_time
-                        # 在当前块中查找活动类型
-                        if re.search(r'宴会[^\w]', block) or '寮宴会' in block:
-                            latest_text = '宴会'
-                        elif re.search(r'狭间[^\w]', block) or '狭间暗域' in block:
-                            latest_text = '狭间'
-                        elif re.search(r'退治[^\w]', block) or '首领退治' in block:
-                            latest_text = '退治'
-                        elif re.search(r'道馆[^\w]', block) or '道馆突破' in block:
-                            latest_text = '道馆'
-                
-                notification_time = latest_block_time
-                notification_text = latest_text
-
-            return notification_time, notification_text
+            if not notification_blocks:
+                return 0, ""
+            latest_time = 0
+            latest_text = ""
+            for block, time_str in notification_blocks:
+                current_time = float(time_str)
+                for keyword in keywords:
+                    if keyword in block and current_time > latest_time:
+                        latest_time = current_time
+                        latest_text = keyword
+                        break
+            return latest_time, latest_text
         except Exception as e:
             logger.warning(f"获取通知失败: {e}")
             return 0, ""
 
-    '''
-    def clear_notifications(self):
-        """清理系统通知"""
-        try:
-            # 清理所有通知
-            self.device.adb_shell(['cmd', 'notification', 'remove-all'])
-            logger.info("已清理系统通知")
-        except Exception as e:
-            logger.warning(f"清理通知失败: {e}")
-    '''
+    def get_notification_info_ocr(self, keywords: list) -> str:
+        """通过OCR识别屏幕通知区域,返回活动关键字"""
+        for keyword in keywords:
+            result = self.O_GUILD_ACTIVITY_NOTIFY.ocr(self.device.image, keyword=keyword)
+            if result != (0, 0, 0, 0):
+                return keyword
+        return ''
 
 
 if __name__ == '__main__':
@@ -158,4 +156,4 @@ if __name__ == '__main__':
     c = Config('oas1')
     d = Device(c)
     t = ScriptTask(c, d)
-    t.run()
+    t.run()

+ 1 - 1
tasks/Restart/assets.py

@@ -138,7 +138,7 @@ class RestartAssets:
 	# 正在连接服务器 
 	O_LOGIN_NETWORK = RuleOcr(roi=(534,649,189,39), area=(210,492,100,100), mode="Single", method="Default", keyword="正在连接服务器", name="login_network")
 	# Ocr-description 
-	O_LOGIN_ENTER_GAME = RuleOcr(roi=(550,567,176,56), area=(558,574,154,49), mode="Single", method="Default", keyword="进入游戏", name="login_enter_game")
+	O_LOGIN_ENTER_GAME = RuleOcr(roi=(589,544,101,107), area=(558,574,154,49), mode="Single", method="Default", keyword="进入", name="login_enter_game")
 	# 点击屏幕跳过 
 	O_LOGIN_SKIP_1 = RuleOcr(roi=(1046,35,130,37), area=(1046,35,130,37), mode="Single", method="Default", keyword="点击屏幕跳过", name="login_skip_1")
 	# 登录指定角色,默认第一个 

+ 7 - 0
tasks/Restart/login.py

@@ -40,6 +40,10 @@ class LoginHandler(BaseTask, RestartAssets, GameUiAssets, GeneralBuffAssets):
                 orientation_timer.reset()
 
             self.screenshot()
+            # https://github.com/runhey/OnmyojiAutoScript/pull/1761
+            if not self.device.check_screen_size_sample():
+                continue
+
             # 取消继续战斗
             if self.appear_then_click(self.I_CANCEL_BATTLE, interval=0.8):
                 logger.info('Cancel continue battle')
@@ -171,6 +175,9 @@ class LoginHandler(BaseTask, RestartAssets, GameUiAssets, GeneralBuffAssets):
         courtyard_affairs_done = False  # 庭院事务只执行一次
         while 1:
             self.screenshot()
+            # https://github.com/runhey/OnmyojiAutoScript/pull/1761
+            if not self.device.check_screen_size_sample():
+                continue
 
             # 点击'获得奖励'
             if self.ui_reward_appear_click():

+ 2 - 2
tasks/Restart/login/ocr.json

@@ -10,11 +10,11 @@
   },
   {
     "itemName": "login_enter_game",
-    "roiFront": "550,567,176,56",
+    "roiFront": "589,544,101,107",
     "roiBack": "558,574,154,49",
     "mode": "Single",
     "method": "Default",
-    "keyword": "进入游戏",
+    "keyword": "进入",
     "description": "Ocr-description"
   },
   {

+ 2 - 3
tasks/RichMan/mall/honor.py

@@ -70,9 +70,8 @@ class Honor(Special):
         if not self.mall_check_money(4, 1500):
             logger.warning('No enough money')
             return
-        # 使用动态位置点击购买
-        self.appear_then_click(self.I_HONOR_BLUE)
-        time.sleep(1)
+        # 购买: 点商品打开购买弹窗, 点加号拉满数量后确认购买
+        self.buy_more(self.I_HONOR_BLUE)
 
     def _honor_black_daruma_scrap(self, enable: bool=False):
         logger.hr('Buy black daruma scrap', 3)

+ 3 - 9
tasks/RichMan/mall/special.py

@@ -163,15 +163,9 @@ class Special(Buy, MallNavbar):
                   .replace(':', ':').replace('火', '次')
                   .replace('教', '数').replace('刺', '剩')
                   .replace('头', '买'))
-        try:
-            if ':' in result:
-                result = re.findall(r'(?:剩余)?购买次数:(\d+)', result)[0]
-                result = int(result)
-            else:
-                result = re.findall(r'本周剩余数量(\d+)', result)[0]
-                result = int(result)
-        except:
-            result = 0
+        # 冒号可能被漏识别, 如"剩余购买次数2", 所以冒号设为可选
+        matched = re.search(r'(?:剩余)?(?:购买次数|本周剩余数量):?(\d+)', result)
+        result = int(matched.group(1)) if matched else 0
         logger.info(f'Remain [{result}]')
         return result
 

+ 3 - 3
tasks/RyouToppa/script_task.py

@@ -186,9 +186,9 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, RyouToppaAssets):
                 continue
 
 
-        # 回 page_main 失败
-        # self.ui_current = page_ryou_toppa
-        # self.ui_goto(page_main)
+        # 回 page_main
+        self.ui_get_current_page()
+        self.ui_goto(page_main)
         if success:
             self.set_next_run(task='RyouToppa', finish=True, server=True, success=True)
         else: