app_dongri.py 26 KB

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