app_dongri.py 27 KB

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