app_dongri.py 26 KB

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