app_dongri.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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. myTimeSleep_big()
  180. try:
  181. os.execv(python, [python, script, *new_args, '--reset'])
  182. except Exception as e:
  183. print(f"重启失败: {e}")
  184. subprocess.Popen([python, script, *new_args, '--reset'])
  185. sys.exit(0) # 终止当前进程
  186. @app.route('/restart_game', methods=['POST'])
  187. def http_restart_game():
  188. print("HTTP 触发 restart_game")
  189. socketio.start_background_task(handle_restart_game)
  190. return jsonify({"status": "success", "message": "已重启"})
  191. @socketio.on('close_game')
  192. def handle_close_game():
  193. task_close_game()
  194. send_status("结束2")
  195. GlobalState.event.clear()
  196. @app.route('/close_game', methods=['POST'])
  197. def http_close_game():
  198. print("HTTP 触发 close_game")
  199. handle_close_game()
  200. socketio.start_background_task(handle_reset_script)
  201. return jsonify({"status": "success", "message": "已关闭"})
  202. @socketio.on('read_cfg')
  203. def handle_read_cfg():
  204. cfg = read_cfg()
  205. emit('processing_cfg', cfg)
  206. def restart_game(type=0):
  207. GlobalState.isGameBegin = False
  208. while True:
  209. task_close_game()
  210. if True == task_start_game(type):
  211. break
  212. else:
  213. send_status("启动失败")
  214. GlobalState.isGameBegin = True
  215. send_status("结束")
  216. config = read_cfg()
  217. print("config", config)
  218. auto_task(config)
  219. def auto_participate():
  220. GlobalState.task_queue.appendleft(task_returnAllLine())
  221. timeout = 40 * 60
  222. start_time = time.time() # 记录开始时间
  223. while not GlobalState.event.is_set():
  224. if len(GlobalState.task_queue) < 4:
  225. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  226. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  227. GlobalState.task_queue.appendleft(task_paticipateInTeam())
  228. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  229. GlobalState.task_queue.appendleft(task_paticipateInTeam())
  230. myTimeSleep_big()
  231. # 每次循环检查已用时间
  232. current_time = time.time()
  233. elapsed_time = current_time - start_time
  234. if elapsed_time >= timeout:
  235. handle_restart_game()
  236. break
  237. def auto_palace():
  238. timeout = 180 * 60
  239. start_time = time.time() # 记录开始时间
  240. read_cfg()
  241. while not GlobalState.event.is_set():
  242. GlobalState.g_times += 1
  243. if len(GlobalState.task_queue) < 4:
  244. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum * 5))
  245. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum * 3))
  246. GlobalState.task_queue.appendleft(task_fight_enemy())
  247. myTimeSleep_big()
  248. current_time = time.time()
  249. elapsed_time = current_time - start_time
  250. if elapsed_time >= timeout:
  251. handle_restart_game()
  252. def add_auto_task(isMaxCollect, isJina, isSimple = False, isAddStrengh = False, activity = 'None', isAutoParticipate = True, isDailyConfig = False, train_type = 'None', always = False):
  253. collectArr = [int(x) for x in isMaxCollect.split(",")]
  254. print("collectArr", collectArr)
  255. if len(collectArr) == 1:
  256. collectArr = collectArr[0]
  257. while not GlobalState.event.is_set():
  258. print(f"----第{GlobalState.g_times}次循环-----")
  259. if isSimple == False and is_within_n_minutes(get_todo_time("巨熊行动"), 30, 35):
  260. print("in fight bear")
  261. if len(GlobalState.task_queue) < 5:
  262. if GlobalState.g_firstRunBear:
  263. GlobalState.g_firstRunBear = False
  264. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  265. GlobalState.task_queue.appendleft(task_returnAllLine())
  266. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  267. GlobalState.task_queue.appendleft(task_returnAllLine())
  268. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  269. GlobalState.task_queue.appendleft(task_returnAllLine())
  270. GlobalState.task_queue.appendleft(task_useAnnimalSkill(True))
  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(not GlobalState.g_switch))
  279. GlobalState.task_queue.appendleft(task_paticipateInTeam(False))
  280. myTimeSleep_big()
  281. send_status(f'巨熊行动中')
  282. continue
  283. elif isSimple == False and is_within_n_minutes(get_todo_time("巨熊行动"), 60, 0):
  284. # 设置无尽运行和启动的游戏为0
  285. always = True
  286. if GlobalState.g_switch:
  287. update_rungame_type(0)
  288. send_status(f'巨熊行动:在60min内,切换到无尽模式')
  289. print("add special activity")
  290. # special activity
  291. if activity == 'lianmeng':
  292. GlobalState.task_queue.appendleft(task_activity_lianmeng())
  293. elif activity == 'zhuguang':
  294. GlobalState.task_queue.appendleft(task_zhuguang())
  295. elif activity == 'cure':
  296. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  297. elif activity == 'only_cure':
  298. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  299. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  300. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  301. return
  302. print("add normal activity")
  303. GlobalState.task_queue.appendleft(task_checkActivities())
  304. if GlobalState.g_switch == True:
  305. GlobalState.task_queue.appendleft(task_checkBenifitStatus())
  306. if isSimple == False:
  307. GlobalState.task_queue.appendleft(task_information())
  308. GlobalState.task_queue.appendleft(task_check_Research())
  309. GlobalState.task_queue.appendleft(task_checkStoreRoom())
  310. if not isSimple:
  311. if isJina == 'jina':
  312. GlobalState.task_queue.appendleft(task_fight_jina(isAddStrengh))
  313. elif isJina == 'yongbing':
  314. GlobalState.task_queue.appendleft(task_fight_yongbing(isAddStrengh))
  315. elif isJina == 'monster':
  316. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  317. elif isJina == 'big_monster' or isJina == 'bigMonster_max':
  318. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  319. elif isJina == 'jina_call':
  320. ### 全部聊天记录都是新吉娜
  321. GlobalState.task_queue.appendleft(task_call_jina())
  322. GlobalState.task_queue.appendleft(task_call_jina())
  323. GlobalState.task_queue.appendleft(task_call_jina())
  324. GlobalState.task_queue.appendleft(task_call_jina())
  325. elif isJina == 'jina_onlyFight':
  326. GlobalState.task_queue.appendleft(task_fight_jina_only())
  327. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  328. GlobalState.task_queue.appendleft(task_train(train_type))
  329. if isSimple == False:
  330. if not isAddStrengh: # 如果不是添加体力,则添加一次采集
  331. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  332. if isJina == 'monster' and isAddStrengh:
  333. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, False, isSimple))
  334. else:
  335. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  336. else:
  337. GlobalState.task_queue.appendleft(task_collect(collectArr, isSimple, isAddStrengh))
  338. print("add rare activity")
  339. if GlobalState.g_times % 3 == 0:
  340. GlobalState.task_queue.appendleft(task_useAnnimalSkill())
  341. GlobalState.task_queue.appendleft(task_checkDiamond())
  342. if GlobalState.g_times % 5 == 0:
  343. if GlobalState.g_switch and get_rungame_type() == 0:
  344. GlobalState.task_queue.appendleft(check_buildOrResearch())
  345. GlobalState.task_queue.appendleft(task_cure(True, GlobalState.g_cureNum))
  346. GlobalState.task_queue.appendleft(task_information())
  347. GlobalState.task_queue.appendleft(task_checkDonata())
  348. GlobalState.task_queue.appendleft(task_checkMaster())
  349. GlobalState.task_queue.appendleft(task_checkAdventure())
  350. GlobalState.task_queue.appendleft(task_train(train_type))
  351. GlobalState.task_queue.appendleft(task_read_mails())
  352. GlobalState.task_queue.appendleft(task_getStrength())
  353. if auto_participate:
  354. GlobalState.task_queue.appendleft(task_checkConfilits())
  355. GlobalState.task_queue.appendleft(task_fight_campion())
  356. GlobalState.task_queue.appendleft(task_get_fire_crystal())
  357. GlobalState.task_queue.appendleft(task_checkUnionTreasure())
  358. #GlobalState.task_queue.appendleft(task_checkBenifitStatus())
  359. GlobalState.task_queue.appendleft(task_gotoTree())
  360. GlobalState.task_queue.appendleft(task_checkHelp())
  361. if activity == 'redPackage':
  362. GlobalState.task_queue.appendleft(task_get_redPackage())
  363. if isJina == 'bigMonster_max':
  364. GlobalState.task_queue.appendleft(task_fightMonster(isAddStrengh, True, isSimple))
  365. print("check restart")
  366. GlobalState.g_times += 1
  367. restart_times = 7
  368. if GlobalState.g_switch:
  369. restart_times = 4
  370. if GlobalState.g_times % restart_times == 0 and GlobalState.g_times != 0:
  371. if GlobalState.g_isRestart:
  372. handle_end_game()
  373. if GlobalState.g_switch == False:
  374. if always:
  375. nextTaskTime = random.randint(400, 450)
  376. set_nextTaskTime(nextTaskTime)
  377. myTimeSleep(nextTaskTime, send_status)
  378. else:
  379. nextTaskTime = random.randint(1000, 2000)
  380. set_nextTaskTime(nextTaskTime)
  381. myTimeSleep(nextTaskTime, send_status)
  382. else:
  383. nextTaskTime = random.randint(20, 50)
  384. set_nextTaskTime(nextTaskTime)
  385. myTimeSleep(nextTaskTime, send_status)
  386. if GlobalState.g_isRestart:
  387. handle_restart_game()
  388. else:
  389. nextTaskTime = random.randint(400, 450)
  390. set_nextTaskTime(nextTaskTime)
  391. myTimeSleep(nextTaskTime, send_status)
  392. GlobalState.task_queue.clear()
  393. send_status(f'自动模式结束')
  394. GlobalState.event.clear()
  395. daily_config = {
  396. "login_task": False,
  397. "fight_bigMonster_times": 0
  398. }
  399. def check_daily_config(config):
  400. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  401. print(f"Today: {today}") # 打印当前日期
  402. print(f"Config: {config}") # 打印传入的配置
  403. if "daily" not in config:
  404. print("Daily key not found, creating it.") # 调试信息
  405. config["daily"] = {}
  406. return False
  407. if today not in config["daily"]:
  408. print(f"Today's config not found: {today}") # 调试信息
  409. return False
  410. else:
  411. print(f"Today's config found: {today}") # 调试信息
  412. return True
  413. def update_rungame_type(dstType=None):
  414. config = read_Dailycfg()
  415. runTypeStr = 'runType'
  416. if runTypeStr not in config:
  417. if dstType is not None:
  418. config[runTypeStr] = dstType
  419. else:
  420. config[runTypeStr] = 1
  421. write_Dailycfg(config)
  422. print(f"更新下次启动{config[runTypeStr]}")
  423. return 0
  424. else:
  425. value = config[runTypeStr]
  426. if dstType is not None:
  427. config[runTypeStr] = dstType
  428. else:
  429. config[runTypeStr] = (value + 1) % 2
  430. write_Dailycfg(config)
  431. print(f"更新下次启动{config[runTypeStr]}")
  432. return value
  433. def get_rungame_type():
  434. config = read_Dailycfg()
  435. runTypeStr = 'runType'
  436. if runTypeStr not in config:
  437. return 0
  438. else:
  439. if config[runTypeStr] == 0:
  440. return 1
  441. else:
  442. return 0
  443. # 修改或添加 "login_task" 的值
  444. def set_login_task(config, value):
  445. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  446. if today not in config["daily"]: # 如果当天的配置不存在
  447. config["daily"][today] = {} # 创建当天的配置
  448. config["daily"][today]["login_task"] = value # 设置或更新 "login_task"
  449. return config
  450. # 修改或添加 "fight_bigMonster_times" 的值
  451. def set_fight_big_monster_times(config, value):
  452. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  453. if today not in config["daily"]: # 如果当天的配置不存在
  454. config["daily"][today] = {} # 创建当天的配置
  455. config["daily"][today]["fight_bigMonster_times"] = value # 设置或更新 "fight_bigMonster_times"
  456. return config
  457. def add_today_daily_config(config, daily_config, overwrite=False):
  458. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  459. if today not in config["daily"] or overwrite: # 如果不存在或允许覆盖
  460. config["daily"][today] = daily_config # 添加或更新
  461. return config
  462. # 清理非当天的每日配置
  463. def clean_old_daily_configs(config):
  464. today = datetime.now().strftime('%Y-%m-%d') # 获取当前日期
  465. keys_to_remove = [key for key in config["daily"] if key != today] # 找到非当天的每日配置
  466. for key in keys_to_remove:
  467. del config["daily"][key] # 删除非当天的每日配置
  468. return config
  469. def write_cfg(config):
  470. try:
  471. config_manager = MinIOConfigManager()
  472. localCfg_name = task_getComputerName() + '_config'
  473. config_manager.set_config(localCfg_name, config)
  474. except Exception as e:
  475. print("写入minIO错误, 尝试写入本地")
  476. with open('config.json', 'w') as config_file:
  477. json.dump(config, config_file, indent=4)
  478. def read_cfg():
  479. try:
  480. config_manager = MinIOConfigManager()
  481. localCfg_name = task_getComputerName() + '_config'
  482. localCfg = config_manager.get_config(localCfg_name)
  483. config = json.loads(localCfg)
  484. GlobalState.g_cureNum = int(config['cureNumber'])
  485. return config
  486. except Exception as e:
  487. print("读取minIO错误, 尝试读取本地")
  488. try:
  489. with open('config.json', 'r') as config_file:
  490. config = json.load(config_file)
  491. GlobalState.g_cureNum = int(config['cureNumber'])
  492. return config
  493. except FileNotFoundError:
  494. print("配置文件不存在,请检查文件路径。")
  495. return None
  496. except PermissionError:
  497. print("没有权限读取配置文件。")
  498. return None
  499. except json.JSONDecodeError:
  500. print("配置文件格式错误,请检查文件内容是否为有效的 JSON。")
  501. return None
  502. def write_Dailycfg(config):
  503. try:
  504. config_manager = MinIOConfigManager()
  505. localCfg_name = task_getComputerName() + '_daily'
  506. config_manager.set_config(localCfg_name, config)
  507. except Exception as e:
  508. print("写入minIO错误, 尝试写入本地")
  509. with open('daily.json', 'w') as config_file:
  510. json.dump(config, config_file, indent=4)
  511. def read_Dailycfg():
  512. try:
  513. config_manager = MinIOConfigManager()
  514. localCfg_name = task_getComputerName() + '_daily'
  515. localCfg = config_manager.get_config(localCfg_name)
  516. config = json.loads(localCfg)
  517. return config
  518. except Exception as e:
  519. print("读取minIO错误, 尝试读取本地")
  520. config = {
  521. "daily": {
  522. "2025-07-11": {
  523. "login_task": True,
  524. "fight_bigMonster_times": 0
  525. }
  526. },
  527. "runType": 0
  528. }
  529. return
  530. @socketio.on('begin_auto')
  531. def handle_auto(data):
  532. write_cfg(data)
  533. config = read_cfg()
  534. print("config", config)
  535. auto_task(config)
  536. def auto_task(data):
  537. if data == None:
  538. isMaxCollect = '4,3,2,1'
  539. isSimple = False
  540. isJina = 'jina'
  541. isAddStrengh = False
  542. activity = 'none'
  543. participateJijie = False
  544. auto_daily = False
  545. train_type = 'none'
  546. always = False
  547. cureNumber = 500
  548. lineCheck = False
  549. switch = False
  550. GlobalState.g_isRestart = True
  551. else:
  552. isMaxCollect = data['maxCollect']
  553. isSimple = data['simple']
  554. isJina = data['jina']
  555. isAddStrengh = data['add_strength']
  556. activity = data['activity']
  557. participateJijie = data['participate_jijie']
  558. auto_daily = False
  559. train_type = data['train']
  560. always = data['always']
  561. cureNumber = int(data['cureNumber'])
  562. lineCheck = data['lineCheck']
  563. switch = data['switch']
  564. GlobalState.g_isRestart = data['is_restart']
  565. GlobalState.g_cureNum = cureNumber
  566. GlobalState.g_switch = switch
  567. set_lineCheck(lineCheck)
  568. send_status(f'开始自动模式')
  569. executor.submit(add_auto_task, isMaxCollect, isJina, isSimple, isAddStrengh, activity, participateJijie, auto_daily, train_type, always)
  570. @socketio.on('begin_auto_participate')
  571. def handle_auto_participate():
  572. send_status(f'开始自动集结模式')
  573. executor.submit(auto_participate)
  574. @socketio.on('begin_testNewFun')
  575. def handle_auto_testNewFun():
  576. send_status(f'开始自动测试新功能')
  577. task_testFun().run()
  578. @socketio.on('auto_palace')
  579. def handle_auto_palace():
  580. send_status(f'开始自动王城')
  581. executor.submit(auto_palace)
  582. def monitor_game_runtime():
  583. last_value = GlobalState.g_times
  584. while True:
  585. current_value = GlobalState.g_times
  586. if current_value != last_value:
  587. last_value = current_value
  588. GlobalState.last_change_time = time.time()
  589. print(f"g_times changed to {current_value}")
  590. # 检查是否超过60分钟没有变化
  591. if time.time() - GlobalState.last_change_time > 3600: # 3600秒=60分钟
  592. print("g_times hasn't changed for 60 minutes!")
  593. handle_restart_game()
  594. time.sleep(60)
  595. if __name__ == '__main__':
  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)#关闭自动重载