forked from takagisanmie/NIKKEAutoScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
412 lines (326 loc) · 13.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import os
import re
import time
from datetime import datetime, timedelta
from functools import cached_property
import inflection
from module.config.config import NikkeConfig, TaskEnd
from module.config.utils import deep_get, deep_set
from module.exception import (
RequestHumanTakeover,
GameNotRunningError,
GameStuckError,
GameTooManyClickError,
GameServerUnderMaintenance,
GameStart,
)
from module.logger import logger
class NikkeAutoScript:
def __init__(self, config_name="nkas"):
logger.hr("Start", level=0)
self.config_name = config_name
@cached_property
def config(self):
try:
config = NikkeConfig(config_name=self.config_name)
return config
except RequestHumanTakeover:
logger.critical("Request human takeover")
exit(1)
except Exception as e:
logger.exception(e)
exit(1)
@cached_property
def device(self):
try:
from module.device.device import Device
device = Device(config=self.config)
return device
except RequestHumanTakeover:
logger.critical("Request human takeover")
exit(1)
except Exception as e:
logger.exception(e)
exit(1)
def run(self, command):
try:
self.device.screenshot()
self.__getattribute__(command)()
return True
except TaskEnd:
return True
except GameStart:
self.start()
return True
except GameNotRunningError as e:
logger.warning(e)
self.config.task_call("Restart")
return True
except (GameStuckError, GameTooManyClickError) as e:
"""
当一直没有进行操作时或点击同一目标过多时,尝试重启游戏
"""
logger.error(e)
"""
在 Alas 中会将在raise前最后的截图和log写入./log/error
"""
self.save_error_log()
logger.warning(
f"Game stuck, {self.device.package} will be restarted in 10 seconds"
)
logger.warning("If you are playing by hand, please stop NKAS")
self.config.task_call("Restart")
self.device.sleep(10)
return False
except GameServerUnderMaintenance as e:
logger.error(e)
self.device.app_stop()
exit(1)
except RequestHumanTakeover:
logger.critical("Request human takeover")
exit(1)
except Exception as e:
self.save_error_log()
logger.exception(e)
exit(1)
def save_error_log(self):
"""
Save last 60 screenshots in ./log/error/<timestamp>
Save logs to ./log/error/<timestamp>/log.txt
"""
from module.base.utils import save_image
from module.handler.sensitive_info import handle_sensitive_logs
if not os.path.exists("./log/error"):
os.mkdir("./log/error")
folder = f"./log/error/{int(time.time() * 1000)}"
logger.warning(f"Saving error: {folder}")
os.mkdir(folder)
for data in self.device.screenshot_deque:
image_time = datetime.strftime(data["time"], "%Y-%m-%d_%H-%M-%S-%f")
# 遮挡个人消息
# image = handle_sensitive_image(data['image'])
image = data["image"]
save_image(image, f"{folder}/{image_time}.png")
with open(logger.log_file, "r", encoding="utf-8") as f:
lines = f.readlines()
start = 0
for index, line in enumerate(lines):
line = line.strip(" \r\t\n")
# 从最后一个任务截取
if re.match("^═{15,}$", line):
start = index
lines = lines[start - 2:]
# 替换真实路径
lines = handle_sensitive_logs(lines)
with open(f"{folder}/log.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
def restart(self):
from module.handler.login import LoginHandler
LoginHandler(self.config, device=self.device).app_restart()
def start(self):
from module.handler.login import LoginHandler
LoginHandler(self.config, device=self.device).app_start()
def goto_main(self):
from module.handler.login import LoginHandler
from module.ui.ui import UI
if self.device.app_is_running():
logger.info("App is already running, goto main page")
UI(self.config, device=self.device).ui_goto_main()
else:
logger.info("App is not running, start app and goto main page")
LoginHandler(self.config, device=self.device).app_start()
UI(self.config, device=self.device).ui_goto_main()
def reward(self):
from module.reward.reward import Reward
Reward(config=self.config, device=self.device).run()
def destruction(self):
from module.destruction.destruction import Destruction
Destruction(config=self.config, device=self.device).run()
def commission(self):
from module.commission.commission import Commission
Commission(config=self.config, device=self.device).run()
def conversation(self):
from module.conversation.conversation import Conversation
Conversation(config=self.config, device=self.device).run()
def rookie_arena(self):
from module.rookie_arena.rookie_arena import RookieArena
RookieArena(config=self.config, device=self.device).run()
def simulation_room(self):
from module.simulation_room.simulation_room import SimulationRoom
SimulationRoom(config=self.config, device=self.device).run()
def tribe_tower(self):
from module.tribe_tower.tribe_tower import TribeTower
TribeTower(config=self.config, device=self.device).run()
def shop(self):
from module.shop.shop import Shop
Shop(config=self.config, device=self.device).run()
def rubbish_shop(self):
from module.rubbish_shop.rubbish_shop import RubbishShop
RubbishShop(config=self.config, device=self.device).run()
def daily(self):
from module.daily.daily import Daily
Daily(config=self.config, device=self.device).run()
def mission_pass(self):
from module.mission_pass.mission_pass import MissionPass
MissionPass(config=self.config, device=self.device).run()
def liberation(self):
from module.liberation.liberation import Liberation
Liberation(config=self.config, device=self.device).run()
def daily_gift(self):
from module.gift.gift import DailyGift
DailyGift(config=self.config, device=self.device).run()
def weekly_gift(self):
from module.gift.gift import WeeklyGift
WeeklyGift(config=self.config, device=self.device).run()
def monthly_gift(self):
from module.gift.gift import MonthlyGift
MonthlyGift(config=self.config, device=self.device).run()
def mailbox(self):
from module.mailbox.mailbox import Mailbox
Mailbox(config=self.config, device=self.device).run()
def interception(self):
from module.interception.interception import Interception
Interception(config=self.config, device=self.device).run()
def li_pass(self):
from module.lipass.lipass import LIPass
LIPass(config=self.config, device=self.device).run()
def event_daemon(self):
from module.event_daemon.event_daemon import EventDaemon
EventDaemon(config=self.config, device=self.device).run()
def wait_until(self, future):
"""
Wait until a specific time.
Args:
future (datetime):
Returns:
bool: True if wait finished, False if config changed.
"""
future = future + timedelta(seconds=1)
"""
记录开始等待任务时,配置文件的最后更改时间
"""
self.config.start_watching()
while 1:
if datetime.now() > future:
return True
# if self.stop_event is not None:
# if self.stop_event.is_set():
# logger.info("Update event detected")
# logger.info(f"[{self.config_name}] exited. Reason: Update")
# exit(0)
time.sleep(5)
"""
在等待过程中持续对比配置文件的最后更改时间
"""
if self.config.should_reload():
return False
def get_next_task(self):
"""
Returns:
str: Name of the next task.
"""
while 1:
task = self.config.get_next()
self.config.task = task
"""
在 Alas 中每个任务都有共有属性 Scheduler
调度器在运行任务时,是根据任务的 Scheduler.Command 调用对应方法
在那之前,Alas 会调用 config.bind(task)
将该任务的 Scheduler 属性覆盖到类变量
在使用到共有属性时,只会使用该任务的设置
例如在设置任务的下次运行时间时,会使用到 Scheduler.SuccessInterval
interval = (self.Scheduler_SuccessInterval if success else self.Scheduler_FailureInterval)
run.append(datetime.now() + ensure_delta(interval))
"""
self.config.bind(task)
from module.base.resource import release_resources
if self.config.task.command != "NKAS":
release_resources(next_task=task.command)
if task.next_run > datetime.now():
logger.info(f"Wait until {task.next_run} for task `{task.command}`")
method = self.config.Optimization_WhenTaskQueueEmpty
"""
在等待任务的过程中可能会被人为修改运行时间
if not self.wait_until(task.next_run):
del self.__dict__['config']
continue
Returns:
bool: True if wait finished, False if config changed.
"""
if method == "close_game":
logger.info("Close game during wait")
self.device.app_stop()
release_resources()
if not self.wait_until(task.next_run):
del self.__dict__["config"]
continue
self.run("start")
elif method == "goto_main":
logger.info("Goto main page during wait")
self.run("goto_main")
release_resources()
if not self.wait_until(task.next_run):
del self.__dict__["config"]
continue
elif method == "stay_there":
logger.info("Stay there during wait")
release_resources()
if not self.wait_until(task.next_run):
del self.__dict__["config"]
continue
break
return task.command
def loop(self):
logger.set_file_logger(self.config_name)
logger.info(f"Start scheduler loop: {self.config_name}")
is_first = True
failure_record = {}
while 1:
task = self.get_next_task()
_ = self.device
if is_first and task == "Restart":
logger.info("Skip task `Restart` at scheduler start")
self.config.task_delay(server_update=True)
del self.__dict__["config"]
continue
# Run
logger.info(f"Scheduler: Start task `{task}`")
self.device.stuck_record_clear()
self.device.click_record_clear()
logger.hr(task, level=0)
"""
https://inflection.readthedocs.io/en/latest/
inflection.underscore('Restart') => 'restart'
inflection.underscore('DeviceType') => 'device_type'
"""
success = self.run(inflection.underscore(task))
logger.info(f"Scheduler: End task `{task}`")
is_first = False
"""
记录某个任务出错的次数
"""
failed = deep_get(failure_record, keys=task, default=0)
failed = 0 if success else failed + 1
deep_set(failure_record, keys=task, value=failed)
if failed >= 3:
logger.critical(f"Task `{task}` failed 3 or more times.")
logger.critical(
"Possible reason #1: You haven't used it correctly. "
"Please read the help text of the options."
)
logger.critical(
"Possible reason #2: There is a problem with this task. "
"Please contact developer or try to fix it yourself."
)
logger.critical("Request human takeover")
exit(1)
if success:
del self.__dict__["config"]
continue
# 出现错误时
else:
del self.__dict__["config"]
continue
if __name__ == "__main__":
nkas = NikkeAutoScript()
nkas.loop()