app_dongri.py 26 KB

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