app_dongri.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. # -*- coding: utf-8 -*-
  2. from flask import Flask, render_template,jsonify
  3. from flask_socketio import SocketIO, emit
  4. from scriptBase.comon import *
  5. import pyautogui
  6. import base64
  7. import threading
  8. from dongri_task import *
  9. from collections import deque
  10. import json
  11. from concurrent.futures import ThreadPoolExecutor
  12. from flask_caching import Cache
  13. from scriptBase.minio_manage import *
  14. import subprocess
  15. from typing import Optional, Any
  16. # 全局线程池,限制最大线程数为1
  17. executor = ThreadPoolExecutor(max_workers=1)
  18. cache = Cache(config={'CACHE_TYPE': 'null'}) # 使用 null 缓存类型
  19. app = Flask(__name__)
  20. cache.init_app(app)
  21. app.config['TEMPLATES_AUTO_RELOAD'] = True
  22. socketio = SocketIO(app, cors_allowed_origins="*", max_http_buffer_size=1e8)
  23. class GlobalState:
  24. event = threading.Event()
  25. g_status_list = []
  26. last_time = 0.0
  27. task_queue = deque()
  28. last_process = ''
  29. isGameBegin = True
  30. isReset = False
  31. g_times = 0
  32. g_cureNum = 500
  33. g_switch = False
  34. g_isRestart = True
  35. last_change_time = time.time()
  36. g_firstRunBear = True
  37. frp_process: Optional[subprocess.Popen[Any]] = None
  38. def startup_frpc():
  39. GlobalState.frp_process = subprocess.Popen(["tool/frpc.exe", "-c", "tool/frpc-desktop.toml"])
  40. def terminate_frpc():
  41. if GlobalState.frp_process is not None:
  42. proc = GlobalState.frp_process
  43. proc.terminate() # 发送 SIGTERM 信号,尝试优雅终止
  44. try:
  45. proc.wait(timeout=10) # 等待最多10秒
  46. print(f"进程已结束,返回值: {proc.returncode}")
  47. except subprocess.TimeoutExpired:
  48. print("等待超时,进程仍未结束,尝试强制杀死...")
  49. proc.kill() # 强制杀死进程
  50. proc.wait() # 等待杀死操作完成
  51. print("进程已被强制杀死")
  52. @app.after_request
  53. def add_no_cache_header(response):
  54. # 添加禁用缓存的响应头
  55. response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
  56. response.headers["Pragma"] = "no-cache"
  57. response.headers["Expires"] = "0"
  58. return response
  59. def thread_runTask():
  60. while True:
  61. if GlobalState.event.is_set():
  62. GlobalState.task_queue.clear()
  63. if len(GlobalState.task_queue) != 0:
  64. # 初始时间
  65. current_time = time.time()
  66. task = GlobalState.task_queue[-1]
  67. GlobalState.task_queue.pop()
  68. print(f"-----------{GlobalState.g_times} {task.name} 开始执行-----------")
  69. GlobalState.last_process = task.name
  70. try:
  71. task.run()
  72. except Exception as e:
  73. print(f"-----------{GlobalState.g_times} {task.name} 执行失败,错误原因:{e}-----------")
  74. cost_time = int(time.time() - current_time)
  75. send_status(f"{task.name} 执行完成,耗时{cost_time}秒")
  76. print(f"-----------{GlobalState.g_times} {task.name} 执行完成,耗时{cost_time}秒-----------")
  77. myTimeSleep_small()
  78. else:
  79. myTimeSleep_big()
  80. if GlobalState.isReset:
  81. GlobalState.isReset = False
  82. cfg = read_cfg()
  83. if cfg['switch']:
  84. type = update_rungame_type()
  85. print(f'启动游戏{type}')
  86. restart_game(type)
  87. else:
  88. restart_game(0)
  89. @app.route('/')
  90. def index():
  91. return render_template('index_dongri.html')
  92. @socketio.on('connect')
  93. def handle_connect():
  94. print('Client connected')
  95. @socketio.on('disconnect')
  96. def handle_disconnect():
  97. print('Client disconnected')
  98. def send_hint(msg):#数组信息
  99. emit('processing_hint', msg)
  100. def send_todo():
  101. emit('processing_todo', get_todo_msgList())
  102. def send_status(msg):#软件执行状态
  103. try:
  104. if not msg == "":
  105. # 添加新的状态消息和时间到列表
  106. timestamp = datetime.now().strftime('%H:%M:%S') # 获取当前时间
  107. status_entry = {'msg': msg, 'time': timestamp} # 存储消息和时间
  108. GlobalState.g_status_list.append(status_entry)
  109. # 如果列表超过 5 条,移除最早的一条
  110. if len(GlobalState.g_status_list) > 5:
  111. GlobalState.g_status_list.pop(0)
  112. else:
  113. sendStr = ''
  114. for item in GlobalState.g_status_list:
  115. sendStr = f"{GlobalState.g_times}次-{item['time']}-{item['msg']}<br>" + sendStr
  116. emit('processing_status', sendStr)
  117. # 如果消息是 "结束",发送所有状态并清空列表
  118. if msg == "结束":
  119. GlobalState.g_status_list = [] # 清空列表
  120. GlobalState.event.clear()
  121. except Exception as e:
  122. print(f"Error in send_status: {e}")
  123. return
  124. @socketio.on('monitor_begin')
  125. def monitor_begin():
  126. current_time = time.time()
  127. elapsed_time = current_time - GlobalState.last_time
  128. if elapsed_time < 0.5:
  129. return
  130. GlobalState.last_time = current_time
  131. regionRet, regionPos = game_region()
  132. screenshot = pyautogui.screenshot(region=regionPos)
  133. compressed_data = compress_image(screenshot)
  134. image_data_base64 = base64.b64encode(compressed_data).decode('utf-8')
  135. socketio.emit('image_data', image_data_base64)
  136. task_arr = []
  137. if not GlobalState.event.is_set():
  138. task_arr.append(GlobalState.last_process)
  139. for item in reversed(GlobalState.task_queue):
  140. task_arr.append(item.name)
  141. latest_tasks = task_arr[:5] # only show the last 5 tasks
  142. send_hint(json.dumps(latest_tasks, ensure_ascii=False))
  143. send_todo()
  144. send_status('')
  145. #print("send img")
  146. @socketio.on('end_script')
  147. def handle_end_script():
  148. GlobalState.event.set()
  149. @socketio.on('end_game')
  150. def handle_end_game():
  151. GlobalState.event.set()
  152. task_close_game()
  153. send_status("结束2")
  154. GlobalState.event.clear()
  155. @socketio.on('get_title')
  156. def handle_get_title():
  157. str = task_getComputerName()
  158. dst = str + ' machine'
  159. emit('processing_title', dst)
  160. @socketio.on('reset_script')
  161. def handle_reset_script():
  162. python = sys.executable
  163. script = os.path.abspath(sys.argv[0]) # 获取当前脚本的绝对路径
  164. # 构建新的参数列表,移除旧的 --reset 并添加新的
  165. new_args = [arg for arg in sys.argv[1:] if arg != '--reset'] # 排除脚本名和旧的 --reset
  166. print(f"当前 Python 解释器: {python}")
  167. print(f"当前脚本路径: {script}")
  168. print(f"重置参数: {[python, script, *new_args, '']}")
  169. terminate_frpc()
  170. myTimeSleep_big()
  171. try:
  172. os.execv(python, [python, script, *new_args, ''])
  173. except Exception as e:
  174. print(f"重置失败: {e}")
  175. subprocess.Popen([python, script, *new_args, ''])
  176. sys.exit(0) # 终止当前进程
  177. @socketio.on('restart_game')
  178. def handle_restart_game():
  179. python = sys.executable
  180. script = os.path.abspath(sys.argv[0]) # 获取当前脚本的绝对路径
  181. # 构建新的参数列表,移除旧的 --reset 并添加新的
  182. new_args = [arg for arg in sys.argv[1:] if arg != '--reset'] # 排除脚本名和旧的 --reset
  183. print(f"当前 Python 解释器: {python}")
  184. print(f"当前脚本路径: {script}")
  185. print(f"重启参数: {[python, script, *new_args, '--reset']}")
  186. terminate_frpc()
  187. myTimeSleep_big()
  188. try:
  189. os.execv(python, [python, script, *new_args, '--reset'])
  190. except Exception as e:
  191. print(f"重启失败: {e}")
  192. subprocess.Popen([python, script, *new_args, '--reset'])
  193. sys.exit(0) # 终止当前进程
  194. @app.route('/restart_game', methods=['POST'])
  195. def http_restart_game():
  196. print("HTTP 触发 restart_game")
  197. restartTask = threading.Thread(target=handle_restart_game, daemon=True)#启动线程往里面添加任务
  198. restartTask.start()
  199. return jsonify({"status": "success", "message": "已重启"})
  200. @socketio.on('close_game')
  201. def handle_close_game():
  202. task_close_game()
  203. send_status("结束2")
  204. GlobalState.event.clear()
  205. @app.route('/close_game', methods=['POST'])
  206. def http_close_game():
  207. print("HTTP 触发 close_game")
  208. handle_close_game()
  209. resetTask = threading.Thread(target=handle_reset_script, daemon=True)#启动线程往里面添加任务
  210. resetTask.start()
  211. return jsonify({"status": "success", "message": "已关闭"})
  212. @socketio.on('read_cfg')
  213. def handle_read_cfg():
  214. cfg = read_cfg()
  215. emit('processing_cfg', cfg)
  216. def restart_game(type=0):
  217. GlobalState.isGameBegin = False
  218. while True:
  219. task_close_game()
  220. if True == task_start_game(type):
  221. break
  222. else:
  223. send_status("启动失败")
  224. GlobalState.isGameBegin = True
  225. send_status("结束")
  226. config = read_cfg()
  227. print("config", config)
  228. auto_task(config)
  229. def auto_participate():
  230. GlobalState.task_queue.appendleft(task_returnAllLine())
  231. timeout = 40 * 60
  232. start_time = time.time() # 记录开始时间
  233. while not GlobalState.event.is_set():
  234. if len(GlobalState.task_queue) < 4:
  235. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  236. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  237. GlobalState.task_queue.appendleft(task_paticipateInTeam())
  238. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  239. GlobalState.task_queue.appendleft(task_paticipateInTeam())
  240. myTimeSleep_big()
  241. # 每次循环检查已用时间
  242. current_time = time.time()
  243. elapsed_time = current_time - start_time
  244. if elapsed_time >= timeout:
  245. handle_restart_game()
  246. break
  247. def auto_palace():
  248. timeout = 180 * 60
  249. start_time = time.time() # 记录开始时间
  250. read_cfg()
  251. while not GlobalState.event.is_set():
  252. GlobalState.g_times += 1
  253. if len(GlobalState.task_queue) < 4:
  254. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum * 5))
  255. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum * 3))
  256. GlobalState.task_queue.appendleft(task_fight_enemy())
  257. myTimeSleep_big()
  258. current_time = time.time()
  259. elapsed_time = current_time - start_time
  260. if elapsed_time >= timeout:
  261. handle_restart_game()
  262. def add_auto_task(isMaxCollect, isJina, isSimple = False, isAddStrengh = False, activity = 'None', isAutoParticipate = True, isDailyConfig = False, train_type = 'None', always = False):
  263. collectArr = [int(x) for x in isMaxCollect.split(",")]
  264. print("collectArr", collectArr)
  265. if len(collectArr) == 1:
  266. collectArr = collectArr[0]
  267. while not GlobalState.event.is_set():
  268. print(f"----第{GlobalState.g_times}次循环-----")
  269. if isSimple == False and is_within_n_minutes(get_todo_time("巨熊行动"), 30, 35):
  270. print("in fight bear")
  271. if len(GlobalState.task_queue) < 5:
  272. if GlobalState.g_firstRunBear:
  273. GlobalState.g_firstRunBear = False
  274. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  275. GlobalState.task_queue.appendleft(task_returnAllLine())
  276. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  277. GlobalState.task_queue.appendleft(task_returnAllLine())
  278. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  279. GlobalState.task_queue.appendleft(task_returnAllLine())
  280. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  281. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  282. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  283. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  284. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  285. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  286. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  287. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  288. GlobalState.task_queue.appendleft(task_paticipateInTeam(not GlobalState.g_switch))
  289. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  290. myTimeSleep_big()
  291. send_status(f'巨熊行动中')
  292. continue
  293. elif isSimple == False and is_within_n_minutes(get_todo_time("巨熊行动"), 60, 0):
  294. # 设置无尽运行和启动的游戏为0
  295. always = True
  296. if GlobalState.g_switch:
  297. update_rungame_type(0)
  298. send_status(f'巨熊行动:在60min内,切换到无尽模式')
  299. print("add special activity")
  300. # special activity
  301. if activity == 'lianmeng':
  302. GlobalState.task_queue.appendleft(task_activity_lianmeng())
  303. elif activity == 'zhuguang':
  304. GlobalState.task_queue.appendleft(task_zhuguang())
  305. elif activity == 'cure':
  306. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  307. elif activity == 'only_cure':
  308. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  309. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  310. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  311. return
  312. print("add normal activity")
  313. GlobalState.task_queue.appendleft(task_checkActivities())
  314. if GlobalState.g_switch == True:
  315. GlobalState.task_queue.appendleft(task_checkBenifitStatus())
  316. if isSimple == False:
  317. GlobalState.task_queue.appendleft(task_information())
  318. GlobalState.task_queue.appendleft(task_check_Research())
  319. GlobalState.task_queue.appendleft(task_checkStoreRoom())
  320. if not isSimple:
  321. if isJina == 'jina':
  322. GlobalState.task_queue.appendleft(task_fight_jina(isAddStrengh))
  323. elif isJina == 'yongbing':
  324. GlobalState.task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  325. elif isJina == 'monster':
  326. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  327. elif isJina == 'big_monster' or isJina == 'bigMonster_max':
  328. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  329. elif isJina == 'jina_call':
  330. ### 全部聊天记录都是新吉娜
  331. GlobalState.task_queue.appendleft(task_call_jina())
  332. GlobalState.task_queue.appendleft(task_call_jina())
  333. GlobalState.task_queue.appendleft(task_call_jina())
  334. GlobalState.task_queue.appendleft(task_call_jina())
  335. elif isJina == 'jina_onlyFight':
  336. GlobalState.task_queue.appendleft(task_fight_jina_only())
  337. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  338. GlobalState.task_queue.appendleft(task_train(train_type))
  339. if isSimple == False:
  340. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  341. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  342. if isJina == 'monster' and isAddStrengh:
  343. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  344. else:
  345. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  346. else:
  347. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  348. print("add rare activity")
  349. if GlobalState.g_times % 3 == 0:
  350. GlobalState.task_queue.appendleft(task_useAnnimalSkill())
  351. GlobalState.task_queue.appendleft(task_checkDiamond())
  352. if GlobalState.g_times % 5 == 0:
  353. if GlobalState.g_switch and get_rungame_type() == 0:
  354. GlobalState.task_queue.appendleft(check_buildOrResearch())
  355. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  356. GlobalState.task_queue.appendleft(task_information())
  357. GlobalState.task_queue.appendleft(task_checkDonata())
  358. GlobalState.task_queue.appendleft(task_checkMaster())
  359. GlobalState.task_queue.appendleft(task_checkAdventure())
  360. GlobalState.task_queue.appendleft(task_train(train_type))
  361. GlobalState.task_queue.appendleft(task_read_mails())
  362. GlobalState.task_queue.appendleft(task_getStrength())
  363. if auto_participate:
  364. GlobalState.task_queue.appendleft(task_checkConfilits())
  365. GlobalState.task_queue.appendleft(task_fight_campion())
  366. GlobalState.task_queue.appendleft(task_get_fire_crystal())
  367. GlobalState.task_queue.appendleft(task_checkUnionTreasure())
  368. #GlobalState.task_queue.appendleft(task_checkBenifitStatus())
  369. GlobalState.task_queue.appendleft(task_gotoTree())
  370. GlobalState.task_queue.appendleft(task_checkHelp())
  371. if activity == 'redPackage':
  372. GlobalState.task_queue.appendleft(task_get_redPackage())
  373. if isJina == 'bigMonster_max':
  374. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  375. print("check restart")
  376. GlobalState.g_times += 1
  377. restart_times = 7
  378. if GlobalState.g_switch:
  379. restart_times = 4
  380. if GlobalState.g_times % restart_times == 0 and GlobalState.g_times != 0:
  381. if GlobalState.g_isRestart:
  382. handle_end_game()
  383. if GlobalState.g_switch == False:
  384. if always:
  385. nextTaskTime = random.randint(400, 450)
  386. set_nextTaskTime(nextTaskTime)
  387. myTimeSleep(nextTaskTime, send_status)
  388. else:
  389. nextTaskTime = random.randint(1000, 2000)
  390. set_nextTaskTime(nextTaskTime)
  391. myTimeSleep(nextTaskTime, send_status)
  392. else:
  393. nextTaskTime = random.randint(20, 50)
  394. set_nextTaskTime(nextTaskTime)
  395. myTimeSleep(nextTaskTime, send_status)
  396. if GlobalState.g_isRestart:
  397. http_restart_game()
  398. else:
  399. nextTaskTime = random.randint(400, 450)
  400. set_nextTaskTime(nextTaskTime)
  401. myTimeSleep(nextTaskTime, send_status)
  402. GlobalState.task_queue.clear()
  403. send_status(f'自动模式结束')
  404. GlobalState.event.clear()
  405. daily_config = {
  406. "login_task": False,
  407. "fight_bigMonster_times": 0
  408. }
  409. def check_daily_config(config):
  410. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  411. print(f"Today: {today}") # 打印当前日期
  412. print(f"Config: {config}") # 打印传入的配置
  413. if "daily" not in config:
  414. print("Daily key not found, creating it.") # 调试信息
  415. config["daily"] = {}
  416. return False
  417. if today not in config["daily"]:
  418. print(f"Today's config not found: {today}") # 调试信息
  419. return False
  420. else:
  421. print(f"Today's config found: {today}") # 调试信息
  422. return True
  423. def update_rungame_type(dstType=None):
  424. config = read_Dailycfg()
  425. runTypeStr = 'runType'
  426. if runTypeStr not in config:
  427. if dstType is not None:
  428. config[runTypeStr] = dstType
  429. else:
  430. config[runTypeStr] = 1
  431. write_Dailycfg(config)
  432. print(f"更新下次启动{config[runTypeStr]}")
  433. return 0
  434. else:
  435. value = config[runTypeStr]
  436. if dstType is not None:
  437. config[runTypeStr] = dstType
  438. else:
  439. config[runTypeStr] = (value + 1) % 2
  440. write_Dailycfg(config)
  441. print(f"更新下次启动{config[runTypeStr]}")
  442. return value
  443. def get_rungame_type():
  444. config = read_Dailycfg()
  445. runTypeStr = 'runType'
  446. if runTypeStr not in config:
  447. return 0
  448. else:
  449. if config[runTypeStr] == 0:
  450. return 1
  451. else:
  452. return 0
  453. # 修改或添加 "login_task" 的值
  454. def set_login_task(config, value):
  455. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  456. if today not in config["daily"]: # 如果当天的配置不存在
  457. config["daily"][today] = {} # 创建当天的配置
  458. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  459. return config
  460. # 修改或添加 "fight_bigMonster_times" 的值
  461. def set_fight_big_monster_times(config, value):
  462. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  463. if today not in config["daily"]: # 如果当天的配置不存在
  464. config["daily"][today] = {} # 创建当天的配置
  465. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  466. return config
  467. def add_today_daily_config(config, daily_config, overwrite=False):
  468. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  469. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  470. config["daily"][today] = daily_config # 添加或更新
  471. return config
  472. # 清理非当天的每日配置
  473. def clean_old_daily_configs(config):
  474. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  475. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  476. for key in keys_to_remove:
  477. del config["daily"][key] # 删除非当天的每日配置
  478. return config
  479. def write_cfg(config):
  480. try:
  481. config_manager = MinIOConfigManager()
  482. localCfg_name = task_getComputerName() + '_config'
  483. config_manager.set_config(localCfg_name, config)
  484. except Exception as e:
  485. print("写入minIO错误, 尝试写入本地")
  486. with open('config.json', 'w') as config_file:
  487. json.dump(config, config_file, indent=4)
  488. def read_cfg():
  489. try:
  490. config_manager = MinIOConfigManager()
  491. localCfg_name = task_getComputerName() + '_config'
  492. localCfg = config_manager.get_config(localCfg_name)
  493. config = json.loads(localCfg)
  494. GlobalState.g_cureNum = int(config['cureNumber'])
  495. return config
  496. except Exception as e:
  497. print("读取minIO错误, 尝试读取本地")
  498. try:
  499. with open('config.json', 'r') as config_file:
  500. config = json.load(config_file)
  501. GlobalState.g_cureNum = int(config['cureNumber'])
  502. return config
  503. except FileNotFoundError:
  504. print("配置文件不存在,请检查文件路径。")
  505. return None
  506. except PermissionError:
  507. print("没有权限读取配置文件。")
  508. return None
  509. except json.JSONDecodeError:
  510. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  511. return None
  512. def write_Dailycfg(config):
  513. try:
  514. config_manager = MinIOConfigManager()
  515. localCfg_name = task_getComputerName() + '_daily'
  516. config_manager.set_config(localCfg_name, config)
  517. except Exception as e:
  518. print("写入minIO错误, 尝试写入本地")
  519. with open('daily.json', 'w') as config_file:
  520. json.dump(config, config_file, indent=4)
  521. def read_Dailycfg():
  522. try:
  523. config_manager = MinIOConfigManager()
  524. localCfg_name = task_getComputerName() + '_daily'
  525. localCfg = config_manager.get_config(localCfg_name)
  526. config = json.loads(localCfg)
  527. return config
  528. except Exception as e:
  529. print("读取minIO错误, 尝试读取本地")
  530. config = {
  531. "daily": {
  532. "2025-07-11": {
  533. "login_task": True,
  534. "fight_bigMonster_times": 0
  535. }
  536. },
  537. "runType": 0
  538. }
  539. return
  540. @socketio.on('begin_auto')
  541. def handle_auto(data):
  542. write_cfg(data)
  543. config = read_cfg()
  544. print("config", config)
  545. auto_task(config)
  546. def auto_task(data):
  547. if data == None:
  548. isMaxCollect = '4,3,2,1'
  549. isSimple = False
  550. isJina = 'jina'
  551. isAddStrengh = False
  552. activity = 'none'
  553. participateJijie = False
  554. auto_daily = False
  555. train_type = 'none'
  556. always = False
  557. cureNumber = 500
  558. lineCheck = False
  559. switch = False
  560. GlobalState.g_isRestart = True
  561. else:
  562. isMaxCollect = data['maxCollect']
  563. isSimple = data['simple']
  564. isJina = data['jina']
  565. isAddStrengh = data['add_strength']
  566. activity = data['activity']
  567. participateJijie = data['participate_jijie']
  568. auto_daily = False
  569. train_type = data['train']
  570. always = data['always']
  571. cureNumber = int(data['cureNumber'])
  572. lineCheck = data['lineCheck']
  573. switch = data['switch']
  574. GlobalState.g_isRestart = data['is_restart']
  575. GlobalState.g_cureNum = cureNumber
  576. GlobalState.g_switch = switch
  577. set_lineCheck(lineCheck)
  578. send_status(f'开始自动模式')
  579. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie, auto_daily, train_type, always)
  580. @socketio.on('begin_auto_participate')
  581. def handle_auto_participate():
  582. send_status(f'开始自动集结模式')
  583. executor.submit(auto_participate)
  584. @socketio.on('begin_testNewFun')
  585. def handle_auto_testNewFun():
  586. send_status(f'开始自动测试新功能')
  587. task_testFun().run()
  588. @socketio.on('auto_palace')
  589. def handle_auto_palace():
  590. send_status(f'开始自动王城')
  591. executor.submit(auto_palace)
  592. def monitor_game_runtime():
  593. last_value = GlobalState.g_times
  594. while True:
  595. current_value = GlobalState.g_times
  596. if current_value != last_value:
  597. last_value = current_value
  598. GlobalState.last_change_time = time.time()
  599. print(f"g_times changed to {current_value}")
  600. # 检查是否超过60分钟没有变化
  601. if time.time() - GlobalState.last_change_time > 3600: # 3600秒=60分钟
  602. print("g_times hasn't changed for 60 minutes!")
  603. handle_restart_game()
  604. time.sleep(60)
  605. if __name__ == '__main__':
  606. startup_frpc()
  607. print("FRPC已启动,主程序继续运行...")
  608. if '--reset' in sys.argv:
  609. time.sleep(2)
  610. GlobalState.isReset = True
  611. print("需要重启游戏")
  612. runTask = threading.Thread(target=thread_runTask)#启动线程往里面添加任务
  613. runTask.daemon = True
  614. runTask.start()
  615. monitor_thread = threading.Thread(target=monitor_game_runtime, daemon=True)
  616. monitor_thread.start()
  617. socketio.run(app, host= '0.0.0.0', debug=True, use_reloader=False)#关闭自动重载