app_dongri.py 27 KB

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