forked from fffonion/MAClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaclient.py
1995 lines (1938 loc) · 94.5 KB
/
maclient.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding:utf-8
# maclient!
# Contributor:
# fffonion <[email protected]>
from __future__ import print_function
import math
import os
import os.path as opath
import re
import sys
import time
import locale
import base64
import datetime
from xml2dict import XML2Dict
from xml2dict import object_dict
import random
import threading
import getpass
from cross_platform import *
if PYTHON3:
import configparser as ConfigParser
xrange = range
else:
import ConfigParser
import maclient_player
import maclient_network
import maclient_logging
import maclient_smart
import maclient_plugin
__version__ = 1.64
# CONSTS:
EXPLORE_BATTLE, NORMAL_BATTLE, TAIL_BATTLE, WAKE_BATTLE = 0, 1, 2, 3
GACHA_FRIENNSHIP_POINT, GACHAgacha_TICKET, GACHA_11 = 1, 2, 4
EXPLORE_HAS_BOSS, EXPLORE_NO_FLOOR, EXPLORE_OK, EXPLORE_ERROR, EXPLORE_NO_AP = -2, -1, 0, 1, 2
BC_LIMIT_MAX, BC_LIMIT_CURRENT = -2, -1
SERV_CN, SERV_CN2, SERV_TW = 'cn', 'cn2', 'tw'
# eval dicts
eval_fairy_select = [('LIMIT', 'time_limit'), ('NOT_BATTLED', 'not_battled'), ('.lv', '.fairy.lv'), ('IS_MINE', 'user.id == self.player.id'), ('IS_WAKE_RARE', 'wake_rare'), ('IS_WAKE', 'wake'), ('STILL_ALIVE', "self.player.fairy['alive']")]
eval_fairy_select_carddeck = [('IS_MINE', 'discoverer_id == self.player.id'), ('IS_WAKE_RARE', 'wake_rare'), ('IS_WAKE', 'wake'), ('STILL_ALIVE', "self.player.fairy['alive']"), ('LIMIT', 'time_limit')]
eval_explore_area = [('IS_EVENT', "area_type=='1'"), ('IS_DAILY_EVENT', "id.startswith('5')"), ('NOT_FINNISHED', "prog_area!='100'")]
eval_explore_floor = [('NOT_FINNISHED', 'progress!="100"')]
eval_select_card = [('atk', 'power'), ('mid', 'master_card_id'), ('price', 'sale_price'), ('sid', 'serial_id'), ('holo', 'holography==1')]
eval_task = []
duowan = {'cn':'http://db.duowan.com/ma/cn/card/detail/%s.html', 'tw':'http://db.duowan.com/ma/card/detail/%s.html'}
logging = maclient_logging.Logging('logging') # =sys.modules['logging']
def setT(strt):
if not PYTHON3:
strt = strt.decode('utf-8').encode('cp936', 'ignore')
if sys.platform == 'cli':
import System.Console
System.Console.Title = strt
else:
os.system('TITLE %s' % strt)
class set_title(threading.Thread):
def __init__(self, maInstance):
threading.Thread.__init__(self)
self.maInstance = maInstance
self.flag = 1
def run(self):
if not self.maInstance.settitle:
self.flag = 0
# if os.name == 'nt':
while self.flag == 1:
self.maInstance.player.calc_ap_bc()
strt = '[%s] AP:%d/%d BC:%d/%d G:%d F:%d SP:%d Cards:%d%s' % (
self.maInstance.player.name,
self.maInstance.player.ap['current'], self.maInstance.player.ap['max'],
self.maInstance.player.bc['current'], self.maInstance.player.bc['max'],
self.maInstance.player.gold, self.maInstance.player.friendship_point,
self.maInstance.player.ex_gauge, self.maInstance.player.card.count,
self.maInstance.player.fairy['alive'] and ' 妖精存活' or '')
setT(strt)
time.sleep(28)
# elif os.name == 'posix':
# pass
class conn_ani(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.flag = 1
def run(self):
cnt = 0
while self.flag == 1:
print('Connecting.%s%s%s' % ('.' * cnt, ' ' * (3 - cnt), '\b' * 20), end = '')
cnt = (cnt + 1) % 4
time.sleep(0.15)
class maClient():
global plugin
plugin = maclient_plugin.plugins(logging)
def __init__(self, configfile = '', savesession = False):
if not PYTHON3:
reload(sys)
sys.setdefaultencoding('utf-8')
self.cf = ConfigParser.ConfigParser()
if configfile == '':
if not os.path.exists('%s%sconfig.ini' % (getPATH0, opath.sep)):
print(du8('正在尝试以默认配置文件启动,但该文件(config.ini)不存在'))
self._exit(1)
self.configfile = getPATH0 + opath.sep + 'config.ini'
else:
if not os.path.exists(configfile):
print(du8('正在尝试以配置文件(%s)启动,但该文件不存在' % configfile))
self._exit(1)
self.configfile = configfile
# configuration
self.cf.read(self.configfile)
self.load_config()
# 映射变量
plugin.set_maclient_val(self.__dict__)
# 添加引用
self.plugin = plugin
self.cfg_save_session = savesession
self.settitle = os.name == 'nt'
self.posttime = 0
# self.set_remote(None)
ua = self._read_config('system', 'user-agent')
self.poster = maclient_network.poster(self.loc, logging, ua)
if ua:
logging.debug('system:ua changed to %s' % (self.poster.header['User-Agent']))
self.load_cookie()
if self.cfg_save_traffic:
self.poster.enable_savetraffic()
# eval
etmp = self._read_config('condition', 'fairy_select') or 'True'
self.evalstr_fairy = self._eval_gen(
'(%s) and fairy.put_down in "01"' % etmp,
eval_fairy_select) # 1战斗中 2胜利 3失败
self.evalstr_area = self._eval_gen(self._read_config('condition', 'explore_area'), eval_explore_area)
self.evalstr_floor = self._eval_gen(self._read_config('condition', 'explore_floor'), eval_explore_floor)
self.evalstr_selcard = self._eval_gen(self._read_config('condition', 'select_card_to_sell'), eval_select_card)
self.evalstr_fairy_select_carddeck = self._eval_gen(self._read_config('condition', 'fairy_select_carddeck'),
eval_fairy_select_carddeck)
self.evalstr_factor = self._eval_gen(self._read_config('condition', 'factor'), [])
# tasker须动态生成#self.evalstr_task=self._eval_gen(self._read_config('system','tasker'),[])
logging.debug('system:知识库版本 %s%s' % (maclient_smart.__version__, str(maclient_smart).endswith('pyd\'>') and ' C-Extension' or ''))
logging.debug('system:初始化完成(服务器:%s)' % self.loc)
self.lastposttime = 0
self.lastfairytime = 0
self.errortimes = 0
self.player_initiated = False
def load_config(self):
# configurations
self.loc = self._read_config('system', 'server')
self.uid = self._read_config('account_%s' % self.loc, 'user_id')
self.playerfile = '.%s-%s.playerdata' % (self.loc, self.uid) if self.uid not in '0' else '--PLACE-HOLDER--'
self.username = self._read_config('account_%s' % self.loc, 'username')
self.password = self._read_config('account_%s' % self.loc, 'password')
self.cfg_auto_explore = not self._read_config('tactic', 'auto_explore') == '0'
self.cfg_auto_sell = not self._read_config('tactic', 'auto_sell_cards') == '0'
self.cfg_autogacha = not self._read_config('tactic', 'auto_fpgacha') == '0'
self.cfg_auto_fairy_rewards = not self._read_config('tactic', 'auto_fairy_rewards') == '0'
self.cfg_auto_build = self._read_config('tactic', 'auto_build') == '1' and '1' or '0'
self.cfg_fpgacha_buld = self._read_config('tactic', 'fp_gacha_bulk') == '1' and '1' or '0'
self.cfg_sell_card_warning = int(self._read_config('tactic', 'sell_card_warning') or '1')
self.cfg_auto_rt_level = self._read_config('tactic', 'auto_red_tea_level')
self.cfg_strict_bc = self._read_config('tactic', 'strict_bc') == '1'
self.cfg_fairy_final_kill_hp = int(self._read_config('tactic', 'fairy_final_kill_hp') or '20000')
self.cfg_save_traffic = not self._read_config('system', 'save_traffic') == '0'
self.cfg_greet_words = self._read_config('tactic', 'greet_words') or (
self.loc == 'tw' and random.choice(['大家好.', '問好']) or random.choice(['你好!', '你好!请多指教!']))
self.cfg_factor_getnew = not self._read_config('tactic', 'factor_getnew') == '0'
self.cfg_auto_update = not self._read_config('system', 'auto_update') == '0'
logging.basicConfig(level = self._read_config('system', 'loglevel') or '2')
logging.setlogfile('events_%s.log' % self.loc)
self.cfg_delay = float(self._read_config('system', 'delay'))
self.cfg_display_ani = (self._read_config('system', 'display_ani') or '1') == '1'
self.logger = logging # 映射
global plugin
self.plugin = plugin # 映射
if (self._read_config('system', 'enable_plugin') or '1') == '1':
disabled_plugin = self._read_config('plugin', 'disabled').split(',')
plugin.set_disable(disabled_plugin)
plugin.scan_hooks()
logging.debug('plugin:loaded %s' % (','.join(plugin.plugins.keys())))
else:
plugin.enable = False
def load_cookie(self):
self.cookie = self._read_config('account_%s' % self.loc, 'session')
self.poster.set_cookie(self.cookie)
# def set_remote(self,remoteInstance):
# self.remote=remoteInstance
# self.remoteHdl=(self.remote ==None and (lambda method=None,fairy='':True) or self.remote_Hdl_())
# if self.remote:
# res,msg=self.remote.login()
# if res:
# logging.debug('remote_hdl:%s'%msg)
# return True
# else:
# logging.warning('remote_hdl:%s'%msg)
# return False
def _dopost(self, urikey, postdata = '', usecookie = True, setcookie = True, extraheader = {'Cookie2': '$Version=1'}, xmlresp = True, noencrypt = False, savetraffic = False, no2ndkey=False ):
# self.remoteHdl()
if self.cfg_display_ani:
connani = conn_ani()
connani.setDaemon(True)
connani.start()
if time.time() - self.lastposttime <= self.cfg_delay:
if self.cfg_delay == 0:
logging.warning('post:NO DELAY!')
else:
logging.debug('post:slow down...')
time.sleep(random.randint(int(0.75 * self.cfg_delay), int(1.25 * self.cfg_delay)))
resp, _dec = self.poster.post(urikey, postdata, usecookie, setcookie, extraheader, noencrypt, savetraffic, no2ndkey)
self.lastposttime = time.time()
if self.cfg_display_ani:
connani.flag = 0
connani.join(0.16)
if int(resp['status']) >= 400:
return resp, _dec
if savetraffic and self.cfg_save_traffic:
logging.debug('post:save traffic')
self.lastposttime += 3 # 本来应该过一会才会收到所有信息的
return resp, _dec
resp.update({'error':False, 'errno':0, 'errmsg':''})
if not xmlresp:
dec = _dec
else:
dec = XML2Dict().fromstring(_dec).response
try:
err = dec.header.error
except:
pass
else:
if err.code != '0':
resp['errmsg'] = err.message
# 1050木有BC 1010卖了卡或妖精已被消灭 8000基友点或卡满了 1020维护 1030有新版本
if not err.code in ['1050', '1010']: # ,'8000']:
logging.error('code:%s msg:%s' % (err.code, err.message))
resp.update({'error':True, 'errno':int(err.code)})
if err.code == '9000':
self._write_config('account_%s' % self.loc, 'session', '')
logging.info('A一个新的小饼干……')
self.login(fast = True)
return self._dopost(urikey, postdata, usecookie, setcookie, extraheader, xmlresp, noencrypt)
elif err.code == '1020':
logging.sleep('因为服务器维护,休息约30分钟')
time.sleep(random.randint(28, 32) * 60)
self.player.update_checked = False # 置为未检查
return resp, dec
if not self.player_initiated :
open(self.playerfile, 'w').write(_dec)
else:
# check revision update
if self.player.need_update[0] or self.player.need_update[1]:
if self.cfg_auto_update:
logging.info('更新%s%s数据……' % (
' 卡片' if self.player.need_update[0] else '',
' 道具' if self.player.need_update[1] else ''))
import maclient_update
crev, irev = maclient_update.update_master(self.loc, self.player.need_update, self.poster)
logging.info('%s%s' % (
'卡片数据更新为rev.%s' % crev if crev else '',
'道具数据更新为rev.%s' % irev if irev else ''))
self.player.reload_db()
self.player.need_update = False, False
else:
logging.warning('检测到服务器游戏数据与游戏数据不一致,请手动更新数据库')
if not resp['error']:
# update profile
update_dt = self.player.update_all(dec)
# self.remoteHdl(method='PROFILE')
if self.settitle:
setT('[%s] AP:%d/%d BC:%d/%d G:%d F:%d SP:%d Cards:%d%s' % (
self.player.name,
self.player.ap['current'], self.player.ap['max'],
self.player.bc['current'], self.player.bc['max'],
self.player.gold, self.player.friendship_point,
self.player.ex_gauge, self.player.card.count,
self.player.fairy['alive'] and ' 妖精存活' or ''))
else:
if self.posttime == 5:
logging.sleep('汇报 AP:%d/%d BC:%d/%d G:%d F:%d SP:%d %s' % (
self.player.ap['current'], self.player.ap['max'],
self.player.bc['current'], self.player.bc['max'],
self.player.gold, self.player.friendship_point, self.player.ex_gauge,
self.player.fairy['alive'] and 'FAIRY_ALIVE' or ''))
self.posttime = (self.posttime + 1) % 6
if update_dt[1]:
logging.debug(update_dt[0])
open(self.playerfile, 'w').write(_dec)
logging.debug('post:master cards saved.')
# auto check cards and fp
if not self.auto_check(urikey):
logging.error('由于以上↑的原因,无法继续执行!')
self._exit(1)
if setcookie and 'set-cookie' in resp:
self.cookie = resp['set-cookie'].split(',')[-1].rstrip('path=/').strip()
self._write_config('account_%s' % self.loc, 'session', self.cookie)
return resp, dec
def _read_config(self, sec, key):
if not self.cf.has_section(sec):
self.cf.add_section(sec)
if self.cf.has_option(sec, key):
val = self.cf.get(sec, key)
if sys.platform == 'win32' and not PYTHON3:
val = val.decode('cp936') # .encode('utf-8')
else:
val = ''
if val == '':return ''
else:return val
def _write_config(self, sec, key, val):
if not self.cf.has_section(sec):
self.cf.add_section(sec)
self.cf.set(sec, key, val)
f = open(self.configfile, "w")
self.cf.write(f)
f.flush()
def _list_option(self, sec):
return self.cf.options(sec)
def _del_option(self, sec, key):
f = self.configfile
self.cf.read(f)
self.cf.remove_option(sec, key)
self.cf.write(open(f, "w"))
def _eval_gen(self, streval, repllst = []):
repllst2 = [('HH', "datetime.datetime.now().hour"), ('MM', "datetime.datetime.now().minute"), ('BC', 'self.player.bc["current"]'), ('AP', 'self.player.ap["current"]'), ('SUPER', 'self.player.ex_gauge'), ('G', 'self.player.gold'), ('FP', 'self.friendship_point'), ('FAIRY_ALIVE', 'self.player.fairy["alive"]')]
if streval == '':
return 'True'
for (i, j) in repllst + repllst2:
streval = streval.replace(i, j)
return streval
def tolist(self, obj):
if not isinstance(obj, list):
return [obj]
else:
return obj
@plugin.func_hook
def tasker(self, taskname = '', cmd = ''):
cnt = int(self._read_config('system', 'tasker_times') or '1')
if cnt == 0:
cnt = 9999999
if taskname == '':
taskname = self._read_config('system', 'taskname')
if taskname == '':
logging.info('没有配置任务!')
return
if cmd != '':
tasks = cmd
cnt = 1
taskeval = self._eval_gen(self._read_config('tasker', taskname), eval_task)
for c in xrange(cnt):
logging.debug('tasker:loop %d/%d' % (c + 1, cnt))
if cmd == '':
tasks = eval(taskeval)
logging.debug('tasker:eval result:%s' % (tasks))
for task in tasks.split('|'):
task = (task + ' ').split(' ')
logging.debug('tasker:%s' % task[0])
task[0] = task[0].lower()
if task[0] in plugin.extra_cmd:
plugin.do_extra_cmd(tasks)
elif task[0] == 'set_card' or task[0] == 'sc':
if task[1] == '':
logging.error('set_card need 1 argument')
else:
self.set_card(task[1])
elif task[0] == 'auto_set' or task[0] == 'as':
self.invoke_autoset(' '.join(task[1:]))
elif task[0] == 'explore' or task[0] == 'e':
self.explore(' '.join(task[1:]))
elif task[0] == 'factor_battle' or task[0] == 'fcb':
arg_lake = ''
arg_minbc = 0
if len(task) > 2:
for i in range(len(task) - 2):
if task[i + 1].startswith('lake:') or task[i + 1].startswith('l:'):
arg_lake = task[i + 1].split(':')[1]
else:
arg_minbc = int(task[i + 1])
self.factor_battle(minbc = arg_minbc, sel_lake = arg_lake)
elif task[0] == 'fairy_battle' or task[0] == 'fyb':
self.fairy_battle_loop(task[1])
elif task[0] == 'fairy_select' or task[0] == 'fs':
for i in xrange(1, len(task)):
if task[i].startswith('deck:'):
self.fairy_select(cond = ' '.join(task[1:i]), carddeck = ' '.join(task[i:-1])[5:])
break
if i == len(task) - 1:
self.fairy_select(cond = ' '.join(task[1:]))
elif task[0] == 'green_tea' or task[0] == 'gt':
self.green_tea()
elif task[0] == 'red_tea' or task[0] == 'rt':
self.red_tea()
elif task[0] == 'sell_card' or task[0] == 'slc':
self.select_card_sell(' '.join(task[1:]))
elif task[0] == 'set_server' or task[0] == 'ss':
self._write_config('system', 'server', task[1])
self.loc = task[1]
self.poster.servloc = self.loc
self.load_config()
elif task[0] == 'relogin' or task[0] == 'rl':
self._write_config('account_%s' % self.loc, 'session', '')
self.login()
elif task[0] == 'login' or task[0] == 'l':
if len(task) == 2:
task.append('')
self.initplayer(self.login(uname = task[1], pwd = task[2]))
elif task[0] == 'friend' or task[0] == 'f':
if len(task) == 2:
task = [task[0], '', '']
self.friends(task[1], task[2] == 'True')
elif task[0] == 'point' or task[0] == 'p':
self.point_setting()
elif task[0] == 'rb' or task[0] == 'reward_box':
if len(task) == 2:
task = [task[0], '12345']
self.reward_box(task[1])
elif task[0] == 'gacha' or task[0] == 'g':
if len(task) == 2:
task[1] = GACHA_FRIENNSHIP_POINT
else:
task[1] = int(task[1])
self.gacha(gacha_type = task[1])
elif task[0] in ['greet', 'gr', 'like']:
self.like(words = task[1])
elif task[0] in ['sleep', 'slp']:
slptime = float(eval(self._eval_gen(task[1])))
logging.sleep('睡觉%s分' % slptime)
time.sleep(slptime * 60)
else:
logging.warning('command "%s" not recognized.' % task[0])
if cnt != 1:
logging.sleep('tasker:正在滚床单wwww')
time.sleep(3.15616546511)
resp, ct = self._dopost('mainmenu') # 初始化
def login(self, uname = '', pwd = '', fast = False):
# sessionfile='.%s.session'%self.loc
if os.path.exists(self.playerfile) and self._read_config('account_%s' % self.loc, 'session') != '' and uname == '':
logging.info('加载了保存的账户XD')
dec = open(self.playerfile, 'r').read() # .encode('utf-8')
ct = xmldict = XML2Dict().fromstring(dec).response
else:
self.username = uname or self.username
self.password = pwd or self.password
if self.username == '':
self.username = raw_inputd('Username:')
if self.password == '' or (uname != '' and pwd == ''):
self.password = getpass.getpass('Password:')
if raw_inputd('是否保存密码(y/n)?') == 'y':
self._write_config('account_%s' % self.loc, 'password', self.password)
logging.warning('保存的登录信息没有加密www')
token = self._read_config('system', 'device_token').replace('\\n', '\n') or \
'nuigiBoiNuinuijIUJiubHOhUIbKhuiGVIKIhoNikUGIbikuGBVININihIUniYTdRTdREujhbjhj'
if not fast:
#ct = self._dopost('check_inspection', xmlresp = False, extraheader = {}, usecookie = False, no2ndkey = True)[1]
# self.poster.update_server(ct)
pdata='login_id=%s&password=%s&app=and&token=%s' % (self.username, self.password, token)
if not self.loc=='cn':
pdata='S=nosessionid&%s' % pdata
self._dopost('notification/post_devicetoken', postdata =pdata , xmlresp = False)
resp, ct = self._dopost('login', postdata = 'login_id=%s&password=%s' % (self.username, self.password))
if resp['error']:
logging.info('登录失败しました')
self._exit(1)
else:
pdata = ct.header.your_data
logging.info('[%s] 登录成功!\n' % self.username + \
'AP:%s/%s BC:%s/%s 金:%s 基友点:%s %s\n' % (
pdata.ap.current, pdata.ap.max,
pdata.bc.current, pdata.bc.max,
pdata.gold, pdata.friendship_point,
pdata.fairy_appearance == '1' and '妖精出现中!!' or '') +
'蛋蛋卷:%s 等级:%s 完成度:%s %s%s%s\n' % (
pdata.gacha_ticket,
pdata.town_level,
pdata.percentage,
pdata.free_ap_bc_point != '0' and '有未分配的点数yo~ ' or '',
pdata.friends_invitations != '0' and '收到好友邀请了呢 ' or '',
ct.body.mainmenu.rewards == '1' and '收到礼物了~' or '')
)
self._write_config('account_%s' % self.loc, 'username', self.username)
self._write_config('record', 'last_set_card', '')
self._write_config('record', 'last_set_bc', '0')
return ct
def initplayer(self, xmldict):
if self.player_initiated: # 刷新
self.player.update_all(xmldict)
else: # 第一次
self.player = maclient_player.player(xmldict, self.loc)
if not self.player.success:
logging.error('当前登录的用户(%s)已经运行了一个maClient' % (self.username))
self._exit(2)
self.carddb = self.player.card.db
self.player_initiated = True
if self.player.id != '0':
self._write_config('account_%s' % self.loc, 'user_id', self.player.id)
else:
self.player.id = self._read_config('account_%s' % self.loc, 'user_id')
# for jp server, regenerate
self.poster.gen_2nd_key(self.player.id,self.loc)
if self.settitle:
# 窗口标题线程
self.stitle = set_title(self)
self.stitle.setDaemon(True)
self.stitle.start()
@plugin.func_hook
def auto_check(self, doingwhat):
if doingwhat in ['exploration/fairybattle', 'exploration/explore', 'gacha/buy']:
if int(self.player.card.count) >= getattr(maclient_smart, 'max_card_count_%s' % self.loc):
if self.cfg_auto_sell:
logging.info('卡片放满了,自动卖卡 v( ̄▽ ̄*)')
return self.select_card_sell()
else:
logging.warning('卡片已经放不下了,请自行卖卡www')
return False
if self.player.friendship_point > getattr(maclient_smart, 'max_fp_%s' % self.loc) * 0.9 and \
not doingwhat in ['gacha/buy', 'gacha/select/getcontents']:
if self.cfg_autogacha:
logging.info('绊点有点多,自动转蛋(* ̄▽ ̄)y ')
self.gacha(gacha_type = GACHA_FRIENNSHIP_POINT)
return True
else:
logging.warning('绊点已经很多,请自行转蛋消耗www')
return False
return True
@plugin.func_hook
def check_strict_bc(self, refresh = False):
if not self.cfg_strict_bc:
return False
last_set_bc = self._read_config('record', 'last_set_bc') or '0'
last_set_bc = int(last_set_bc)
if self.player.bc['current'] < last_set_bc:
logging.warning('strict_bc:严格BC模式已触发www')
return True
else:
logging.debug('strict_bc:nothing happened~')
return False
@plugin.func_hook
def invoke_autoset(self, autoset_str, cur_fairy = None):
aim, fairy, maxline, test_mode, delta, includes, bclimit, fast_mode, sel = 'MAX_DMG', None, 1, True, 1, [], BC_LIMIT_CURRENT, True, 'card.lv>45'
if cur_fairy:
fairy = cur_fairy
for arg in autoset_str.split(' '):
if arg.startswith('aim:'):
aim = arg[4:]
elif arg.startswith('fairy:'):
fairy = object_dict()
fairy.lv, fairy.hp, nothing = map(lambda x:int(x), (arg[6:] + ',-325').split(','))
if nothing != -325:
fairy.IS_WAKE = False
else:
fairy.IS_WAKE = True
aim = 'DEFEAT'
elif arg.startswith('line:'):
maxline = int(arg[5:])
elif arg == 'notest':
test_mode = False
elif arg.startswith('sel'):
sel = arg[4:]
elif arg.startswith('bc:'):
_l = arg[3:]
if _l == 'max':
bclimit = BC_LIMIT_MAX
elif _l in ['cur', 'current']:
bclimit = BC_LIMIT_CURRENT
else:
bclimit = int(_l)
elif arg.startswith('delta:'):
delta = float(arg[6:])
elif arg.startswith('nofast'):
fast_mode = False
elif arg.startswith('incl:'):
includes = map(lambda x:int(x), arg[5:].split(','))
elif arg != '':
logging.warning('未识别的参数 %s' % arg)
try:
aim = getattr(maclient_smart, aim.upper())
except AttributeError:
logging.warning('未识别的目标 %s' % aim)
return self.set_card('auto_set', aim = aim, includes = includes, maxline = maxline, seleval = sel, fairy_info = fairy, delta = delta, test_mode = test_mode, bclimit = bclimit, fast_mode = fast_mode)
@plugin.func_hook
def set_card(self, deckkey, **kwargs):
if deckkey == 'no_change':
logging.debug('set_card:no_change!')
return False
elif deckkey.startswith('auto_set'):
if len(deckkey) > 8: # raw string : auto_set(CONDITIONS)
if 'cur_fairy' in kwargs:
cf = kwargs.pop('cur_fairy')
else:
cf = None
return self.invoke_autoset('%s notest' % deckkey[9:-1], cur_fairy = cf)
else:
test_mode = kwargs.pop('test_mode')
bclimit = kwargs.pop('bclimit')
res = maclient_smart.carddeck_gen(
self.player.card,
bclimit = (bclimit == BC_LIMIT_MAX and self.player.bc['max'] or (
bclimit == BC_LIMIT_CURRENT and self.player.bc['current'] or bclimit)),
**kwargs)
if len(res) == 5:
atk, hp, last_set_bc, sid, mid = res
param = map(lambda x:str(x), sid)
# 别看比较好
print(du8('设置卡组为: ATK:%d HP:%d COST:%d\n%s' % (
sum(atk),
hp,
last_set_bc,
'\n'.join(
map(lambda x, y: '%s\tATK:%-5d' % (x, y),
['|'.join(map(
lambda x:' %-12s' % self.carddb[x][0],
mid[i:min(i + 3, len(mid))]
))
for i in range(0, len(mid), 3)
], # 卡组分成一排排
atk
)
)
)
))
else:
logging.error(res[0])
return False
if test_mode:
return False
else:
try:
cardid = self._read_config('carddeck', deckkey)
except AttributeError:
logging.warning('set_card:忘记加引号了?')
return False
if cardid == self._read_config('record', 'last_set_card'):
logging.debug('set_card:card deck satisfied, not changing.')
return False
if cardid == '':
logging.warning('set_card:不存在的卡组名?')
return False
cardid = cardid.split(',')
param = []
last_set_bc = 0
for i in xrange(len(cardid)):
if cardid[i] == 'empty':
param.append('empty')
elif len(cardid[i]) > 4:
try:
mid = self.player.card.sid(cardid[i]).master_card_id
except IndexError:
logging.error('你木有sid为 %s 的卡片' % (cardid[i]))
else:
last_set_bc += int(self.carddb[int(mid)][2])
param.append(str(cardid[i]))
else:
c = self.player.card.cid(cardid[i])
if c != []:
param.append(str(c[-1].serial_id))
last_set_bc += int(self.carddb[int(cardid[i])][2])
else:
logging.error('你木有id为 %s (%s)的卡片' % (cardid[i], self.carddb[int(cardid[i])][0]))
noe = ','.join(param).replace(',empty', '').replace('empty,', '').split(',')
lc = random.choice(noe)
t = 5 + random.random() * len(noe) * 0.7
param = param + ['empty'] * (12 - len(param))
while True:
if param == ['empty'] * 12:
break
if self._dopost('roundtable/edit', postdata = 'move=1')[0]['error']:
break
logging.sleep('休息%d秒,假装在找卡' % t)
time.sleep(t)
postparam = 'C=%s&lr=%s' % (','.join(param), lc)
if self.loc != 'tw':#cn, jp, kr:
postparam = '%s&deck_id=1'%postparam
if self._dopost('cardselect/savedeckcard', postdata = postparam)[0]['error']:
break
logging.info('成功更换卡组为%s cost%d' % (deckkey, last_set_bc))
# 保存
self._write_config('record', 'last_set_card', self._read_config('carddeck', deckkey))
# 记录BC
self._write_config('record', 'last_set_bc', str(last_set_bc))
return True
logging.info('卡组没有改变')
return False
def _use_item(self, itemid):
param = 'item_id=%s' % itemid
resp, ct = self._dopost('item/use', postdata = param)
if resp['error']:
return False
else:
logging.info('使用了道具 %s' % self.player.item.get_name(int(itemid)))
logging.debug('useitem:item %s : %s left' % (itemid, self.player.item.get_count(int(itemid))))
return True
@plugin.func_hook
def red_tea(self, silent = False):
auto = int(self._read_config('tactic', 'auto_red_tea') or '0')
if auto > 0:
self._write_config('tactic', 'auto_red_tea', str(auto - 1))
res = self._use_item('2')
else:
if silent:
logging.debug('red_tea:auto mode, let it go~')
return False
else:
if raw_inputd('来一坨红茶? y/n ') == 'y':
res = self._use_item('2')
else:
res = False
if res:
self.player.bc['current'] = self.player.bc['max']
return res
@plugin.func_hook
def green_tea(self, silent = False):
auto = int(self._read_config('tactic', 'auto_green_tea') or '0')
if auto > 0:
self._write_config('tactic', 'auto_green_tea', str(auto - 1))
res = self._use_item('1')
else:
if silent:
logging.debug('green_tea:auto mode, let it go~')
return False
else:
if raw_inputd('嗑一瓶绿茶? y/n ') == 'y':
res = self._use_item('1')
else:
res = False
if res:
self.player.ap['current'] = self.player.ap['max']
return res
@plugin.func_hook
def explore(self, cond = ''):
# 选择秘境
has_boss = []
while True:
resp, ct = self._dopost('exploration/area')
if resp['error']:
return
areas = ct.body.exploration_area.area_info_list.area_info
if not self.cfg_auto_explore:
for i in xrange(len(areas)):
print('%d.%s(%s%%/%s%%) %s' % \
(i + 1, areas[i].name, areas[i].prog_area, areas[i].prog_item, (areas[i].area_type == '1' and 'EVENT' or '')))
areasel = [areas[int(raw_inputd('选择: ') or '1') - 1]]
else:
logging.info('自动选图www')
areasel = []
cond_area = (cond == '' and self.evalstr_area or self._eval_gen(cond, eval_explore_area)).split('|')
while len(cond_area) > 0:
if cond_area[0] == '':
cond_area[0] = 'True'
logging.debug('explore:eval:%s' % (cond_area[0]))
for area in areas:
if eval(cond_area[0]) and not area.id in has_boss:
areasel.append(area)
cond_area = cond_area[1:]
if areasel != []:
break
if areasel == []:
logging.info('没有符合条件的秘境www')
return
area = random.choice(areasel)
logging.debug('explore:area id:%s' % area.id)
logging.info('选择了秘境 %s' % area.name)
next_floor = 'PLACE-HOLDER'
while next_floor:
next_floor, msg = self._explore_floor(area, next_floor)
if msg == EXPLORE_OK: # 进入过秘境
# 走形式
if self._dopost('exploration/floor', postdata = 'area_id=%s' % (area.id))[0]['error']:
break
elif msg == EXPLORE_NO_AP:
break
elif msg == EXPLORE_HAS_BOSS:
has_boss.append(area.id)
else: # NO_FLOOR or ERROR
break
def _check_floor_eval(self, floors):
sel_floor = []
cond_floor = self.evalstr_floor.split('|')
while len(cond_floor) > 0:
if cond_floor[0] == '':
cond_floor[0] = 'True'
logging.debug('explore:eval:%s' % (cond_floor[0]))
for floor in floors:
floor.cost = int(floor.cost)
if eval(cond_floor[0]):
nofloorselect = False
sel_floor.append(floor)
if len(sel_floor) > 0: # 当前条件选出了地区
break
cond_floor = cond_floor[1:] # 下一条件
return len(sel_floor) == 0, sel_floor and random.choice(sel_floor) or None
@plugin.func_hook
def _explore_floor(self, area, floor = None):
while True:
if floor == None or floor == 'PLACE-HOLDER': # 没有指定
# 选择地区
param = 'area_id=%s' % (area.id)
resp, ct = self._dopost('exploration/floor', postdata = param)
if resp['error']:
return None, EXPLORE_ERROR
floors = self.tolist(ct.body.exploration_floor.floor_info_list.floor_info)
# if 'found_item_list' in floors:#只有一个
# floors=[floors]
# 选择地区,结果在floor中
nofloorselect, floor = self._check_floor_eval(floors)
if nofloorselect:
msg = EXPLORE_NO_FLOOR
break # 更换秘境
logging.info('进♂入地区 %s' % floor.id)
if floor.type == '1':
logging.info('秘境守护者出现,将使用最大卡组干掉之')
param = 'area_id=%s&check=1&floor_id=%s' % (area.id, floor.id)
if self._dopost('exploration/boss_floor', postdata = param)[0]['error']:
return None, EXPLORE_ERROR
self._boss_battle(area_id = area.id, floor_id = floor.id)
# 退出秘境
break
# 进入
param = 'area_id=%s&check=1&floor_id=%s' % (area.id, floor.id)
if self._dopost('exploration/get_floor', postdata = param)[0]['error']:
return None, EXPLORE_ERROR
# 走路
param = 'area_id=%s&auto_build=1&floor_id=%s' % (area.id, floor.id)
while True:
resp, ct = self._dopost('exploration/explore', postdata = param)
if resp['error']:
return None, EXPLORE_ERROR
info = ct.body.explore
logging.debug('explore:event_type:' + info.event_type)
if info.event_type != '6':
logging.info('获得:%sG %sEXP, 进度:%s, 升级剩余:%s' % (info.gold, info.get_exp, info.progress, info.next_exp))
# 已记录1 2 3 4 5 12 13 15 19
if info.event_type == '1':
'''<fairy>
<serial_id>20840184</serial_id>
<master_boss_id>2043</master_boss_id>
<hp_max>753231</hp_max>
<time_limit>7200</time_limit>
<discoverer_id>532554</discoverer_id>
<attacker_history></attacker_history>
<rare_flg>0</rare_flg>
<event_chara_flg>0</event_chara_flg>
</fairy>'''
info.fairy.lv, info.fairy.hp = int(info.fairy.lv), int(info.fairy.hp)
logging.info('碰到只妖精:%s lv%d hp%d' % (info.fairy.name, info.fairy.lv, info.fairy.hp))
logging.debug('sid' + info.fairy.serial_id + ' mid' + info.fairy.master_boss_id + ' uid' + info.fairy.discoverer_id)
self.player.fairy = {'id':info.fairy.serial_id, 'alive':True}
# evalfight=self._eval_gen(self._read_config('condition','encounter_fairy'),\
# {'fairy':'info.fairy'})
# logging.debug('eval:%s result:%s'%(evalfight,eval(evalfight)))
# if eval(evalfight):
logging.sleep('3秒后开始战斗www')
time.sleep(3)
self._fairy_battle(info.fairy, bt_type = EXPLORE_BATTLE)
time.sleep(5.5)
if self._check_floor_eval([floor])[0]: # 若已不符合条件
return None, EXPLORE_OK
# 回到探索界面
if self._dopost('exploration/get_floor',
postdata = 'area_id=%s&check=1&floor_id=%s' % (area.id, floor.id)
)[0]['error']:
return None, EXPLORE_ERROR
elif info.event_type == '2':
logging.info('碰到个傻X:{0} -> {1}'.format(info.encounter.name, info.message).replace('%', '%%'))
time.sleep(1.5)
elif info.event_type == '3':
usercard = info.user_card
logging.debug('explore:cid %s sid %s' % (usercard.master_card_id, usercard.serial_id))
logging.info('获得了 %s ☆%s' % (self.carddb[int(usercard.master_card_id)][0],
self.carddb[int(usercard.master_card_id)][1]))
elif info.event_type == '15':
compcard = info.autocomp_card[-1]
logging.debug('explore:cid %s sid %s' % (
compcard.master_card_id,
compcard.serial_id))
logging.info('合成了 %s lv%s exp%s nextexp%s' % (
self.carddb[int(compcard.master_card_id)][0],
compcard.lv,
compcard.exp,
compcard.next_exp))
elif info.event_type == '5':
logging.info('AREA %s CLEAR -v-' % floor.id)
time.sleep(2)
if 'next_floor' in info:
next_floor = info.next_floor.floor_info
return next_floor, EXPLORE_OK
else:
return None, EXPLORE_OK
elif info.event_type == '12':
logging.info('AP回复~')
elif info.event_type == '13':
logging.info('BC回复~')
elif info.event_type == '19':
try:
itemid = info.special_item.item_id
except KeyError:
logging.debug('explore:item not found?')
else:
itembefore = int(info.special_item.before_count)
itemnow = int(info.special_item.after_count)
logging.debug('explore:itemid:%s' % (itemid))
logging.info('获得收集品[%s] x%d' % (self.player.item.get_name(int(itemid)), itemnow - itembefore))
elif info.event_type == '4':
logging.info('获得了因子碎片 湖:%s 碎片:%s' % (
info.parts_one.lake_id, info.parts_one.parts.parts_num))
if len(ct) > 10000:
logging.info('收集碎片合成了新的骑士卡片!')
else:
logging.warning('AP不够了TUT')
if not self.green_tea(self.cfg_auto_explore):
logging.error('不给喝,不走了o( ̄ヘ ̄o#) ')
return None, EXPLORE_NO_AP
else:
continue
if info.lvup == '1':
logging.info('升级了:↑%s' % self.player.lv)
time.sleep(3)
# if info.progress=='100':
# break
time.sleep(int(self._read_config('system', 'explore_sleep')))
return None, EXPLORE_OK
# print '%s - %s%% cost%s'%\
# (floors[i].id,floors[i].progress,floors[i].cost)
@plugin.func_hook
def _boss_battle(self, area_id = None, floor_id = None):
if not (area_id and floor_id):
return False
self.set_card('auto_set', aim = maclient_smart.MAX_DMG, maxline = 4, seleval = 'card.lv>45', test_mode = False, bclimit = BC_LIMIT_MAX, fast_mode = True)
param = "area_id=%s&floor_id=%s" % (area_id, floor_id)
resp, ct = self._dopost('exploration/battle', postdata = param)
if resp['error']:
return False
if ct.body.battle_result.winner == '1':
logging.info('战斗胜利o(* ̄▽ ̄*)o ')
return True
else:
logging.info('输了呢Σ( ° △ °|||)︴ ')
return False
@plugin.func_hook
def gacha(self, gacha_type = GACHA_FRIENNSHIP_POINT):
if gacha_type == GACHA_FRIENNSHIP_POINT:
ab = self.cfg_auto_build
bulk = self.cfg_fpgacha_buld
else:
ab = '0'
bulk = '0'
if self._dopost('gacha/select/getcontents')[0]['error']:
return
logging.debug("gacha:auto_build:%s bulk:%s product_id:%d" % (ab, bulk, gacha_type))
param = "auto_build=%s&bulk=%s&product_id=%d" % (ab, bulk, gacha_type)
resp, ct = self._dopost('gacha/buy', postdata = param)
if resp['error']:
return
gacha_buy = ct.body.gacha_buy
excards = self.tolist(gacha_buy.final_result.ex_user_card)
excname = []
# if 'is_new_card' in excards:#只有一个
# excards=[excards]
for card in excards:
mid = self.player.card.sid(card.serial_id).master_card_id
if gacha_type > GACHA_FRIENNSHIP_POINT:
rare = ['R', 'R+', 'SR', 'SR+']
rare_str = ' ' + rare[self.carddb[int(mid)][1] - 3]
else:
rare = ['', '', '', 'R+', 'SR', 'SR+']
rare_str = ' %s' % (rare[self.carddb[int(mid)][1] - 1])
excname.append('[%s]%s%s' % (
self.carddb[int(mid)][0],
self.player.card.sid(card.serial_id).holography == '1' and '(闪)' or '',
rare_str
))
logging.info('获得%d张新卡片: %s' % (len(excname), ', '.join(excname)))
self.player.friendship_point = self.player.friendship_point - 200 * len(excname)