app_dongri.py 25 KB

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