script_task.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from cached_property import cached_property
  5. from datetime import datetime
  6. import requests
  7. import re
  8. import json
  9. from pathlib import Path
  10. from module.exception import GameStuckError, TaskEnd
  11. from module.logger import logger
  12. from module.atom.click import RuleClick
  13. from module.atom.image import RuleImage
  14. from module.base.timer import Timer
  15. from tasks.GameUi.game_ui import GameUi
  16. from tasks.GameUi.page import page_main
  17. from tasks.Component.RightActivity.right_activity import RightActivity
  18. from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
  19. from tasks.Component.config_base import TimeDelta
  20. from tasks.FrogBoss.assets import FrogBossAssets
  21. from tasks.FrogBoss.config import Strategy
  22. from tasks.FrogBoss.record_reader import read_record_rows
  23. from tasks.FrogBoss.frog_oas import OasHistory, fetch_predictions, fingerprint
  24. class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
  25. @cached_property
  26. def oas_history(self):
  27. instance = re.sub(r'[^\w.-]', '_', self.config.config_name)
  28. return OasHistory(Path('data/frog_oas') / f'{instance}.jsonl')
  29. def record_oas_history_page(self):
  30. if self.config.model.frog_boss.frog_boss_config.strategy_frog != Strategy.Oas:
  31. return
  32. timer = Timer(10).start()
  33. while not timer.reached():
  34. self.screenshot()
  35. if self.appear(self.I_FROG_LOG_CHECK):
  36. break
  37. self.appear_then_click(self.I_FROG_LOG, interval=2)
  38. else:
  39. raise GameStuckError('FrogBoss record page did not open')
  40. try:
  41. # Read only the currently visible rows; never scroll the record page.
  42. readings = []
  43. for _ in range(2):
  44. self.screenshot()
  45. if not self.appear(self.I_FROG_LOG_CHECK):
  46. break
  47. readings.append(read_record_rows(self.device.image, self))
  48. if len(readings) != 2 or readings[0] != readings[1]:
  49. self.oas_history.append('unverified_result', reason='unstable_record_page')
  50. logger.warning('FrogBoss record page readings were not stable')
  51. else:
  52. for stamp, won, side in dict.fromkeys(readings[0]):
  53. result = self.oas_history.settle_record(stamp, won, selected_side=side)
  54. logger.info(f'frog_oas record result: {result}, time={stamp}, won={won}, selected={side}')
  55. finally:
  56. timer = Timer(10).start()
  57. while not timer.reached():
  58. self.screenshot()
  59. if not self.appear(self.I_FROG_LOG_CHECK) and self.appear(self.I_FROG_CHECK):
  60. break
  61. self.appear_then_click(self.I_FROG_LOG_CLOSE, interval=2)
  62. else:
  63. raise GameStuckError('FrogBoss record page did not close')
  64. def enter_frog_boss(self):
  65. self.screenshot()
  66. if self.appear(self.I_FROG_CHECK) or self.appear(self.I_FROG_LOG_CHECK):
  67. return
  68. self.enter(self.I_FROG_BOSS_ENTER)
  69. if not self.wait_until_appear(self.I_FROG_CHECK, wait_time=10):
  70. raise GameStuckError('FrogBoss page not detected after entering activity')
  71. def _try_next_competition_fallback(self, idle_timer):
  72. if not self.appear(self.I_FROG_CHECK):
  73. idle_timer.reset()
  74. return False
  75. if idle_timer.reached() and self.appear_then_click(self.I_NEXT_COMPETITION, interval=1):
  76. logger.info('FrogBoss idle for 5 seconds; advance via next-competition fallback')
  77. idle_timer.reset()
  78. return True
  79. return False
  80. def run(self):
  81. self.enter_frog_boss()
  82. history_checked = False
  83. idle_timer = Timer(5).start()
  84. # 进入主界面
  85. while 1:
  86. self.screenshot()
  87. if self._try_next_competition_fallback(idle_timer):
  88. continue
  89. if not history_checked and self.config.model.frog_boss.frog_boss_config.strategy_frog == Strategy.Oas:
  90. if (self.appear(self.I_FROG_LOG_CHECK) or self.appear(self.I_BETTED)
  91. or self.appear(self.I_FROG_BOSS_REST)
  92. or (self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT))):
  93. self.record_oas_history_page()
  94. history_checked = True
  95. idle_timer.reset()
  96. continue
  97. # 已经下注
  98. if self.appear(self.I_BETTED):
  99. logger.info('You have betted')
  100. break
  101. # 休息中
  102. if self.appear(self.I_FROG_BOSS_REST):
  103. logger.info('Frog Boss Rest')
  104. break
  105. # 竞猜成功
  106. if self.appear(self.I_BET_SUCCESS):
  107. logger.info('You bet win')
  108. self.detect()
  109. while 1:
  110. self.screenshot()
  111. if self._try_next_competition_fallback(idle_timer):
  112. continue
  113. # 下一局可能直接进入休息中,而不再显示左右投注入口。
  114. if self.appear(self.I_FROG_BOSS_REST):
  115. break
  116. if self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT):
  117. break
  118. if self.appear_then_click(self.I_BET_SUCCESS_BOX, interval=1):
  119. idle_timer.reset()
  120. continue
  121. if self.appear_then_click(self.I_REWARD, interval=2):
  122. idle_timer.reset()
  123. continue
  124. if self.appear_then_click(self.I_NEXT_COMPETITION, interval=4):
  125. idle_timer.reset()
  126. continue
  127. continue
  128. # 竞猜失败
  129. if self.appear(self.I_BET_FAILURE):
  130. logger.info('You bet lose')
  131. if self.ui_click_until_disappear(self.I_NEXT_COMPETITION):
  132. idle_timer.reset()
  133. self.detect()
  134. continue
  135. # 正式竞猜
  136. if self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT):
  137. self.do_bet()
  138. idle_timer.reset()
  139. continue
  140. logger.info('FrogBoss end')
  141. self.next_run()
  142. raise TaskEnd('FrogBoss')
  143. def next_run(self):
  144. time = self.config.model.frog_boss.frog_boss_config.before_end_frog
  145. time_delta = TimeDelta(hours=time.hour, minutes=time.minute, seconds=time.second)
  146. time_now = datetime.now()
  147. time_set = time_now.replace(minute=0, second=0, microsecond=0)
  148. if 10 <= time_now.hour < 12:
  149. time_set = time_set.replace(hour=14)
  150. elif 12 <= time_now.hour < 14:
  151. time_set = time_set.replace(hour=16)
  152. elif 14 <= time_now.hour < 16:
  153. time_set = time_set.replace(hour=18)
  154. elif 16 <= time_now.hour < 18:
  155. time_set = time_set.replace(hour=20)
  156. elif 18 <= time_now.hour < 20:
  157. time_set = time_set.replace(hour=22)
  158. elif 20 <= time_now.hour < 22:
  159. time_set = time_set.replace(hour=0) + TimeDelta(days=1)
  160. elif 22 <= time_now.hour < 24:
  161. time_set = time_set.replace(hour=12) + TimeDelta(days=1)
  162. else:
  163. time_set = time_set.replace(hour=12)
  164. self.set_next_run(task='FrogBoss', target=time_set - time_delta)
  165. def do_bet(self):
  166. logger.hr('do bet', level=2)
  167. self.screenshot()
  168. count_left = self.O_LEFT_COUNT.ocr(self.device.image)
  169. count_right = self.O_RIGHT_COUNT.ocr(self.device.image)
  170. match self.config.model.frog_boss.frog_boss_config.strategy_frog:
  171. case Strategy.Majority:
  172. click_image = self.I_BET_LEFT if count_left > count_right else self.I_BET_RIGHT
  173. case Strategy.Minority:
  174. click_image = self.I_BET_LEFT if count_left < count_right else self.I_BET_RIGHT
  175. case Strategy.Bilibili:
  176. click_image = self.I_BET_LEFT if count_left > count_right else self.I_BET_RIGHT
  177. case Strategy.Dashen:
  178. click_image = self.get_dashen(count_left, count_right)
  179. case Strategy.Oas:
  180. signature = fingerprint(self.device.image)
  181. predictions = fetch_predictions(self.oas_history)
  182. try:
  183. decision = self.oas_history.choose(signature, count_left, count_right, predictions)
  184. except ValueError as exc:
  185. raise GameStuckError(str(exc)) from exc
  186. logger.info(f'frog_oas decision: {decision}')
  187. # Fetching may span a round transition; never click a stale frame.
  188. self.screenshot()
  189. from tasks.FrogBoss.frog_oas import same_lineup
  190. if not same_lineup(signature, fingerprint(self.device.image)):
  191. raise GameStuckError('FrogBoss lineup changed while fetching predictions')
  192. if not (self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT)):
  193. raise GameStuckError('FrogBoss betting closed while fetching predictions')
  194. click_image = self.I_BET_LEFT if decision['side'] == 'LEFT' else self.I_BET_RIGHT
  195. case Strategy.AlwaysRed:
  196. click_image = self.I_BET_LEFT
  197. case Strategy.AlwaysBlue:
  198. click_image = self.I_BET_RIGHT
  199. case _:
  200. raise ValueError(f'Unknown bet mode: {self.config.model.frog_boss.frog_boss_config.strategy_frog}')
  201. logger.info(f'You strategy is {self.config.model.frog_boss.frog_boss_config.strategy_frog} and bet on {click_image}')
  202. self.ui_click_until_disappear(click_image)
  203. self.confirm_bet()
  204. def select_gold_30(self):
  205. if not self.appear(self.I_GOLD_30):
  206. return False
  207. # 袋子下部的奖励图标会打开说明页,只点击匹配位置的上部袋身。
  208. x, y, width, height = self.I_GOLD_30.roi_front
  209. area = (x + width // 4, y + height // 8, width // 2, height // 3)
  210. self.click(RuleClick(
  211. roi_front=area, roi_back=area, name='FB_GOLD_30_SELECT',
  212. ))
  213. return True
  214. def confirm_bet(self):
  215. logger.info('Formal bet')
  216. timer = Timer(20).start()
  217. gold_selected = False
  218. submit_attempts = 0
  219. while not timer.reached():
  220. self.screenshot()
  221. if self.appear(self.I_BETTED):
  222. return
  223. if self.appear(self.I_FROG_BOSS_REST):
  224. return
  225. # 弹窗后方的金额、鼓面仍能匹配,必须先处理弹窗并重新截图。
  226. if self.appear(self.I_GOLD_30_CHECK):
  227. logger.info('Close FrogBoss betting reward information')
  228. self.click(self.C_REWARD_2, interval=2)
  229. continue
  230. if self.appear_then_click(self.I_UI_CONFIRM, interval=2):
  231. continue
  232. if self.appear_then_click(self.I_UI_CONFIRM_SAMLL, interval=2):
  233. continue
  234. if not gold_selected:
  235. if self.select_gold_30():
  236. gold_selected = True
  237. continue
  238. if submit_attempts < 3 and self.appear_then_click(self.I_BET_SURE, interval=3):
  239. submit_attempts += 1
  240. continue
  241. raise GameStuckError(
  242. f'FrogBoss betting confirmation timeout: gold_selected={gold_selected}, '
  243. f'submit_attempts={submit_attempts}'
  244. )
  245. def detect(self) -> bool:
  246. """
  247. 检测是左边赢了还是右边赢的
  248. :return: True 左边赢了
  249. """
  250. if self.appear(self.I_SUCCESS_LEFT) and self.appear(self.I_FAILURE_RIGHT):
  251. result = True
  252. logger.info('Left win')
  253. elif self.appear(self.I_SUCCESS_RIGHT) and self.appear(self.I_FAILURE_LEFT):
  254. result = False
  255. logger.info('Right win')
  256. else:
  257. result = None
  258. return result
  259. def get_bilibili(self) -> RuleImage:
  260. """
  261. 获取博主的策略选择
  262. :return:
  263. """
  264. pass
  265. def get_dashen(self, count_left, count_right) -> RuleImage:
  266. """
  267. 获取博主的策略选择,整合多个博主的投注策略,并返回最终的下注建议
  268. :return: 'left' 或 'right' 的下注目标
  269. """
  270. logger.info('Fetching strategy from multiple Dashen UPer')
  271. # 定义正则表达式
  272. red_regex = re.compile(r'(押红|押左|压红|压左|红方|红色|我红|我左|红优|左|红六|红七|红八|红九|红十|91开|82开|73开|64开)')
  273. blue_regex = re.compile(r'(押蓝|押右|压蓝|压右|蓝方|蓝色|我蓝|我右|蓝优|右|蓝六|蓝七|蓝八|蓝九|蓝十|19开|28开|37开|46开)')
  274. # 获取 feedId 的函数
  275. def get_feed_id(uid):
  276. url = f'https://inf.ds.163.com/v1/web/feed/basic/getSomeOneFeeds?feedTypes=1,2,3,4,6,7,10,11&someOneUid={uid}'
  277. response = requests.get(url)
  278. if response.status_code == 200:
  279. data = response.json()
  280. if 'result' in data and 'feeds' in data['result'] and len(data['result']['feeds']) > 0:
  281. return data['result']['feeds'][0]['id']
  282. return None
  283. # 获取 feed 详细信息的函数
  284. def get_feed_details(feed_id):
  285. url = f'https://inf.ds.163.com/v1/web/feed/basic/facade?feedId={feed_id}'
  286. response = requests.get(url)
  287. if response.status_code == 200:
  288. data = response.json()
  289. try:
  290. user_nick = data['result']['userInfos'][0]['user']['nick']
  291. create_time = data['result']['feed']['createTime']
  292. content_json = data['result']['feed']['content']
  293. content_data = json.loads(content_json)
  294. body_text = content_data['body']['text']
  295. return {
  296. 'user_nick': user_nick,
  297. 'create_time': create_time,
  298. 'body_text': body_text
  299. }
  300. except (KeyError, IndexError, json.JSONDecodeError):
  301. return None
  302. return None
  303. # 检查发布时间是否符合规则
  304. def is_time_valid(create_time):
  305. # 定义时间段
  306. valid_time_ranges = [(10, 12), (12, 14), (14, 16), (16, 18), (18, 20), (20, 22), (22, 24)]
  307. now = datetime.now()
  308. # now = datetime(year=2024, month=10, day=3, hour=19, minute=45, second=0) # 指定时间读取历史文章
  309. # 获取发布时间
  310. post_time = datetime.fromtimestamp(create_time / 1000) # 假设 create_time 是毫秒级时间戳
  311. post_hour = post_time.hour
  312. # 检查发布时间是否在有效时间段内
  313. for start, end in valid_time_ranges:
  314. if start <= post_hour < end and start <= now.hour < end:
  315. return True
  316. return False
  317. # 分析 body_text 来判断投注结果
  318. def analyze_bet(body_text):
  319. red_span=9999
  320. blue_span=9999
  321. if red_regex.search(body_text):
  322. red_span=red_regex.search(body_text).start()
  323. if blue_regex.search(body_text):
  324. blue_span=blue_regex.search(body_text).start()
  325. if red_span < blue_span:
  326. return 'LEFT'
  327. elif red_span > blue_span:
  328. return 'RIGHT'
  329. return 'Unknown'
  330. # 提供的 uid 列表
  331. uids = [
  332. {"name": "面灵气喵", "id": "462382f1127b46c5add1185d88f0ea40"},
  333. {"name": "余岁岁", "id": "54399446d5084a0e8878dac8f6ff56d0"},
  334. {"name": "七面相", "id": "840742d60e4a43208605ae68ca8c3f64"},
  335. {"name": "待机中的徐ok", "id": "c3c989fae4074d04b478b8ba47ae4120"},
  336. {"name": "雯雯", "id": "aaa923436aa440df9ac1ee3f47387b99"},
  337. {"name": "晨时微凉", "id": "72584a679e2f45b6859566b5523400d5"},
  338. {"name": "梅布斯尼", "id": "3d4726d99f2642a485729695b798cb8c"},
  339. {"name": "鸽海成路", "id": "1d2dcbbd7e3d481c8d0f27ba4ff0dc71"},
  340. {"name": "徐清林", "id": "21657a558bdd4ddfb6501298350336e7"},
  341. {"name": "不包邮哦亲", "id": "0e4e0c5a1e494a1fa9a58ac55de689c1"},
  342. {"name": "天真珈百璃", "id": "30e383c884f844a18a7a76fe3c1e888f"},
  343. {"name": "薛定谔家查查尔", "id": "d9dc2a75497c4a91b2db1e909a36544d"},
  344. {"name": "嘤嘤井", "id": "e7107cd3010e418da26672669d8eeb5e"},
  345. {"name": "Prince班崎", "id": "74adeb1bfb2b4cf382edbbb430da2149"},
  346. {"name": "靠脸混饭", "id": "e87f855f36f24b34b9d8f8a4fb2d62b2"},
  347. {"name": "夜神月丶L", "id": "82de68c7672e4b6da65493fb829b57b6"},
  348. {"name": "是大荣啦", "id": "f6d6bb15d6024200a985752e2ab4c373"},
  349. {"name": "炒饭菌", "id": "06e2bba14a914012bc8064601cfa19ea"},
  350. {"name": "清流不加班", "id": "8982241de1844638b4bb455139b8dcc0"},
  351. {"name": "槐夏三十", "id": "a9724e98c1cb4a4e931ebc3f467ea73d"},
  352. {"name": "落沫颜", "id": "e9b0a16325af46628e8dfb9e7942cf1d"},
  353. {"name": "Mico林木森", "id": "b6b5bc8277e34f69aeca018db0081397"},
  354. {"name": "查查尔", "id": "d9dc2a75497c4a91b2db1e909a36544d"},
  355. {"name": "CC南浔", "id": "74db771d92a54c28ae3e98d19aa565a3"},
  356. {"name": "冰七喜Den", "id": "e498e524252041e29999b38e57c4df1d"},
  357. {"name": "行水姑娘", "id": "30b0c2923faa483f95572c324a5bc910"},
  358. {"name": "更慕林", "id": "e32aedbdd8da46a5b5b497a16c4b7658"}
  359. # ... 可以添加更多 uid
  360. ]
  361. # 主函数,遍历这批 uid
  362. count_uper_left = 0 # 统计博主投注左侧红方次数
  363. count_uper_right = 0 # 统计博主投注右侧蓝方次数
  364. for user in uids:
  365. uid = user['id']
  366. name = user['name']
  367. feed_id = get_feed_id(uid)
  368. if feed_id:
  369. details = get_feed_details(feed_id)
  370. # 检查 create_time 和 body_text
  371. if details and is_time_valid(int(details['create_time'])) and details['body_text']:
  372. bet_result = analyze_bet(details['body_text'])
  373. bet_rate = (re.compile(r"([5-9]\d%|\d+开|[一二三四五六七八九十零]+开|([红蓝][一二三四五六七八九十零,0-9])+)")
  374. .search(details.get('body_text')))
  375. if bet_rate:
  376. bet_rate = ',' + bet_rate.group()
  377. else:
  378. bet_rate = ''
  379. # 输出博主结论,可省略
  380. # logger.info(f"{name}({details['user_nick']}) has bet on the {bet_result}{bet_rate}")
  381. # 根据投注结果更新统计
  382. if bet_result == 'LEFT':
  383. count_uper_left += 1
  384. elif bet_result == 'RIGHT':
  385. count_uper_right += 1
  386. # 最终输出决策
  387. if count_uper_left > count_uper_right:
  388. logger.info(f"Final decision: The best bet is LEFT({count_uper_left}:{count_uper_right})")
  389. return self.I_BET_LEFT # 返回下注的目标是左边
  390. elif count_uper_right > count_uper_left:
  391. logger.info(f"Final decision: The best bet is RIGHT({count_uper_right}:{count_uper_left})")
  392. return self.I_BET_RIGHT # 返回下注的目标是右边
  393. else:
  394. logger.info("Final decision:Left and right bets are equal, default bet is minority")
  395. # 若五五开则投注少数博反压奖励
  396. if count_left < count_right:
  397. return self.I_BET_LEFT
  398. else:
  399. return self.I_BET_RIGHT
  400. if __name__ == '__main__':
  401. from module.config.config import Config
  402. from module.device.device import Device
  403. c = Config('oas1')
  404. d = Device(c)
  405. t = ScriptTask(c, d)
  406. t.run()