@zonemultiwhs/

smon_all

Python

No description

fork
loading
Files
  • main.py
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
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
import json
import requests
import time
from collections import OrderedDict

#=========================
MAX_NUM_CARD_PRINTING = 8
MAX_BATTLE_NUM = 3

INT_CARDS = ['Furious Chicken', 'Beetle Queen', 'Lord Arianthus']

INT_ACCOUNTS = ['tradingideas']
#==========================


CARDS = []
MARKET_REAL_DATA = []
XP_Based_On_Rarity = {1:15, 2:75, 3:175, 4:750}
XP_Based_On_Rarity_GOLD = {1:200, 2:400, 3:800, 4:2000}
MAX_CAP = {1:400000, 2:100000, 3:40000, 4:10000}
SMON_SETTINGS = []
MIN_PRICES = {}
EDITIONS = {0 : 'Alpha', 1 : 'Beta', 2 : 'Promo', 3 : 'Reward'}

CARD_TYPE_NAME = {
    1:"Common",
    2:"Rare",
    3:"Epic",
    4:"Legendary"
}
CARD_ID_NAME = {
"1":["Goblin Shaman",1],
"2":["Giant Roc",1],
"3":["Kobold Miner",1],
"4":["Fire Beetle",1],
"5":["Malric Inferno",2],
"6":["Serpentine Soldier",2],
"7":["Pit Ogre",2],
"8":["Cerberus",2],
"9":["Fire Demon",3],
"10":["Serpent of the Flame",3],
"11":["Elemental Phoenix",4],
"12":["Pirate Captain",1],
"13":["Spineback Turtle",1],
"14":["Crustacean King",1],
"15":["Sabre Shark",1],
"16":["Alric Stormbringer",2],
"17":["Medusa",2],
"18":["Water Elemental",2],
"19":["Frozen Soldier",2],
"20":["Mischievous Mermaid",3],
"21":["Naga Warrior",3],
"22":["Frost Giant",4],
"23":["Flesh Golem",1],
"24":["Goblin Sorcerer",1],
"25":["Rexxie",1],
"26":["Minotaur Warrior",1],
"27":["Lyanna Natura",2],
"28":["Earth Elemental",2],
"29":["Stone Golem",2],
"30":["Stonesplitter Orc",2],
"31":["Magi of the Forest",3],
"32":["Swamp Thing",3],
"33":["Spirit of the Forest",4],
"34":["Divine Healer",1],
"35":["Feral Spirit",1],
"36":["Silvershield Knight",1],
"37":["Silvershield Warrior",1],
"38":["Tyrus Paladium",2],
"39":["Peacebringer",2],
"40":["Silvershield Paladin",2],
"41":["Clay Golem",2],
"42":["Defender of Truth",3],
"43":["Air Elemental",3],
"44":["Angel of Light",4],
"45":["Animated Corpse",1],
"46":["Haunted Spider",1],
"47":["Skeleton Assassin",1],
"48":["Spineback Wolf",1],
"49":["Zintar Mortalis",2],
"50":["Haunted Spirit",2],
"51":["Twisted Jester",2],
"52":["Undead Priest",2],
"53":["Dark Enchantress",3],
"54":["Screaming Banshee",3],
"55":["Lord of Darkness",4],
"56":["Selenia Sky",4],
"57":["Lightning Dragon",4],
"58":["Chromatic Dragon",4],
"59":["Gold Dragon",4],
"60":["Peaceful Giant",1],
"61":["Grumpy Dwarf",1],
"62":["Elven Cutthroat",1],
"63":["Centaur",1],
"64":["Cocatrice",2],
"65":["Cyclops",2],
"66":["Enchanted Pixie",2],
"67":["Raging Impaler",3],
"68":["Magi Sphinx",3],
"69":["Hydra",4],
"70":["Talia Firestorm",3],
"71":["Xia Seachan",3],
"72":["Xander Foxwood",3],
"73":["Kiara Lightbringer",3],
"74":["Jarlax the Undead",3],
"75":["Dragon Whelp",1],
"76":["Royal Dragon Archer",3],
"77":["Shin-Lo",4],
"78":["Neb Seni",2],
"79":["Highland Archer",1],
"80":["Rusty Android",1],
"81":["Hobgoblin",2],
"82":["Lord Arianthus",4],
"83":["Sea Genie",1],
"84":["Divine Sorceress",3],
"85":["Mushroom Seer",2],
"86":["Vampire",1],
"87":["Flame Imp",2],
"88":["Daria Dragonscale",3],
"89":["Sacred Unicorn",4],
"90":["Wood Nymph",1],
"91":["Creeping Ooze",1],
"92":["Phantom Soldier",3],
"93":["Pirate Archer",2],
"94":["Naga Fire Wizard",2],
"95":["Brownie",3],
"96":["Silvershield Archers",1],
"97":["Goblin Mech",1],
"98":["Ruler of the Seas",4],
"99":["Skeletal Warrior",2],
"100":["Imp Bowman",3],
"101":["Crystal Werewolf",2],
"102":["Javelin Thrower",2],
"103":["Sea Monster",1],
"104":["Prismatic Energy",2],
"105":["Undead Minotaur",1],
"106":["Exploding Dwarf",1],
"107":["Manticore",3],
"108":["Black Dragon",4],
"109":["Crypt Mancer",4],
"110":["Plado Emberstorm",4],
"111":["Valnamor",4],
"112":["Prince Rennyn",4],
"113":["The Peakrider",4],
"114":["Delwyn Dragonscale",1],
"115":["Dragonling Bowman",2],
"116":["Fiendish Harpy",3],
"117":["Red Dragon",4],
"118":["Armorsmith",1],
"119":["Silvershield Bard",2],
"120":["Goblin Chef",1],
"121":["Minotaur Warlord",4],
"122":["Electric Eels",2],
"123":["Mermaid Healer",3],
"124":["Undead Archer",2],
"125":["Corrupted Pegasus",4],
"126":["Molten Ogre",1],
"127":["Lord of Fire",4],
"128":["Enchanted Defender",1],
"129":["Dwarven Wizard",3],
"130":["Archmage Arius",4],
"131":["Furious Chicken",2],
"132":["Fallen Specter",4],
"133":["Beetle Queen",2],
"134":["Naga Windmaster",2],

}


def get_card_detail_info(from_file=0) :
    # get the carddetails from steemmonsters.com
    global CARDS
    # get the carddetails from steemmonsters.com
    if CARDS == [] :
        if (from_file) :
            CARDS = load_json_from_file("sm_get_details.txt")
        else :
            r = requests.get("https://steemmonsters.com/cards/get_details")
            CARDS = r.json()

def card_issued_status(from_file=0) :
    get_card_detail_info(from_file) 
    card_lists = []
    card_lists_so = []  # sold out
    print("======================================")
    print("id       name          issued   remain")
    print("======================================")
    for card in CARDS :
        if (card['editions'] == '3') :
            xp = XP_Based_On_Rarity[card['rarity']]
            xp_gold = XP_Based_On_Rarity_GOLD[card['rarity']]
            # XP가 0으로 시작하므로, 현재 남은 카드 수량*xp 한 만큼 XP 더한 후 XP로 나눈다.
            # gold 카드의 경우에는 한 장부터 XP가 있으므로 그냥 XP로 나누면 된다.
            num_printed_cards = (int(card['distribution'][0]['total_xp']) + int(card['distribution'][0]['num_cards'])*xp) / xp  + \
                                (int(card['distribution'][0]['total_burned_xp']) + int(card['distribution'][0]['num_burned'])*xp) / xp
            num_printed_cards_gold = int(card['distribution'][1]['total_xp']) / xp_gold  + \
                                int(card['distribution'][1]['total_burned_xp']) / xp_gold
            percent = (num_printed_cards+num_printed_cards_gold)/ MAX_CAP[card['rarity']] * 10000
            info = [card['id'], card['name'], card['rarity'], card['editions'], card['distribution'][0], int(percent)]
            if (percent >= 10000.0) :
                card_lists_so.append(info)
            else :
                card_lists.append(info)

    slist = sorted(card_lists, key = lambda x: (x[5], x[0]), reverse=True)  # 0번째가 key
    slist_so = sorted(card_lists_so, key = lambda x: (x[5], x[0]), reverse=True)  # 0번째가 key
    cnt = 0
    
    for card_info in slist_so :
        if (cnt > MAX_NUM_CARD_PRINTING ) :
            break
        cnt += 1
        remain = MAX_CAP[card_info[2]] * (1 - card_info[5]/10000)
        print(format(card_info[0], "3d"), format(card_info[1], "20s"), format(card_info[5]/100, "6.2f"), '%', format(int(remain), "7,d"))
    cnt = 0
    for card_info in slist :
        if (cnt > MAX_NUM_CARD_PRINTING ) :
            break
        cnt += 1
        remain = MAX_CAP[card_info[2]] * (1 - card_info[5]/10000)
        print(format(card_info[0], "3d"), format(card_info[1], "20s"), format(card_info[5]/100, "6.2f"), '%', format(int(remain), "7,d"))

# def get_card_details()에서 rarity를 찾아야한다.
# rarity : 1 - 4 (common, rare, epic, legandary)
def get_single_cards(card_detail_id, edition, gold, xp):
    global CARD_ID_NAME
    cards = 0
    rarity = CARD_ID_NAME[str(card_detail_id)][1]
    # Alpha Edition Cards per XP
    if edition == 0 and gold == 0 and rarity == 4:
        cards = (xp / 1000) +1
    if edition == 0 and gold == 0 and rarity == 3:
        cards = (xp / 250) +1
    if edition == 0 and gold == 0 and rarity == 2:
        cards = (xp / 100) +1
    if edition == 0 and gold == 0 and rarity == 1:
        cards = (xp / 20) +1
    if edition == 0 and gold == 1 and rarity == 4:
        cards = xp / 2500
    if edition == 0 and gold == 1 and rarity == 3:
        cards = xp / 1000
    if edition == 0 and gold == 1 and rarity == 2:
        cards = xp / 500
    if edition == 0 and gold == 1 and rarity == 1:
        cards = xp / 250
    # Beta Edition Cards per XP
    if edition == 1 and gold == 0 and rarity == 4:
        cards = (xp / 750) +1
    if edition == 1 and gold == 0 and rarity == 3:
        cards = (xp / 175) +1
    if edition == 1 and gold == 0 and rarity == 2:
        cards = (xp / 75) +1
    if edition == 1 and gold == 0 and rarity == 1:
        cards = (xp / 15) +1
    if edition == 1 and gold == 1 and rarity == 4:
        cards = xp / 2000
    if edition == 1 and gold == 1 and rarity == 3:
        cards = xp / 800
    if edition == 1 and gold == 1 and rarity == 2:
        cards = xp / 400
    if edition == 1 and gold == 1 and rarity == 1:
        cards = xp / 200
    # Promo Edition Cards per XP
    if edition == 2 and gold == 0 and rarity == 4:
        cards = (xp / 1000) +1
    if edition == 2 and gold == 0 and rarity == 3:
        cards = (xp / 250) +1
    if edition == 2 and gold == 0 and rarity == 2:
        cards = (xp / 100) +1
    if edition == 2 and gold == 0 and rarity == 1:
        cards = (xp / 20) +1
    if edition == 2 and gold == 1 and rarity == 4:
        cards = xp / 2000
    if edition == 2 and gold == 1 and rarity == 3:
        cards = xp / 800
    if edition == 2 and gold == 1 and rarity == 2:
        cards = xp / 400
    if edition == 2 and gold == 1 and rarity == 1:
        cards = xp / 200
    # reward Edition Cards per XP
    if edition == 3 and gold == 0 and rarity == 4:
        cards = (xp / 750) +1
    if edition == 3 and gold == 0 and rarity == 3:
        cards = (xp / 175) +1
    if edition == 3 and gold == 0 and rarity == 2:
        cards = (xp / 75) +1
    if edition == 3 and gold == 0 and rarity == 1:
        cards = (xp / 15) +1
    if edition == 3 and gold == 1 and rarity == 4:
        cards = xp / 2000
    if edition == 3 and gold == 1 and rarity == 3:
        cards = xp / 800
    if edition == 3 and gold == 1 and rarity == 2:
        cards = xp / 400
    if edition == 3 and gold == 1 and rarity == 1:
        cards = xp / 200

    return cards


__url__ = 'https://steemmonsters.com/'
__url2__ = 'https://api.steemmonsters.io'

def get_data_from_sm(cmd, url2=0) :
    url = __url__ + cmd
    if (url2) :
       url = __url2__ + cmd

    response = ""
    cnt2 = 0
    while str(response) != '<Response [200]>' and cnt2 < 15:
        response = requests.get(url)
        if str(response) != '<Response [200]>':
            time.sleep(1)
        cnt2 += 1

    rets = response.json()
    return rets

def get_smon_settings() :
    global SMON_SETTINGS
    SMON_SETTINGS = get_data_from_sm('settings')
    
    steem_price = SMON_SETTINGS['steem_price']
    dec_price = SMON_SETTINGS['dec_price']

    MIN_PRICES['general_beta_rewards'] = {
        'common' : dec_price * SMON_SETTINGS['dec']['burn_rate'][0]* 1.05, 
        'rare': dec_price * SMON_SETTINGS['dec']['burn_rate'][1]* 1.05,
        'epic' : dec_price * SMON_SETTINGS['dec']['burn_rate'][2]* 1.05,
        'leg' : dec_price * SMON_SETTINGS['dec']['burn_rate'][3]* 1.05
    }
    gd_factor = SMON_SETTINGS['dec']['gold_burn_bonus']
    MIN_PRICES['general_beta_rewards_gold'] = {
        'common' : dec_price * SMON_SETTINGS['dec']['burn_rate'][0] * gd_factor* 1.05, 
        'rare': dec_price * SMON_SETTINGS['dec']['burn_rate'][1]* gd_factor* 1.05,
        'epic' : dec_price * SMON_SETTINGS['dec']['burn_rate'][2]* gd_factor* 1.05,
        'leg' : dec_price * SMON_SETTINGS['dec']['burn_rate'][3]* gd_factor* 1.05
    }
    

def save_to_file_json(file_name, data) :
    with open(file_name,'w',encoding="utf-8") as make_file: 
       json.dump(data, make_file, ensure_ascii=False, indent="\t") 

def load_json_from_file(file_name) :
    try :
        with open(file_name,'r',encoding="utf-8") as make_file: 
           data=json.load(make_file) 
    except :
        data = {}
    return data
def reload_market_data() :
    global MARKET_REAL_DATA
    MARKET_REAL_DATA = get_data_from_sm("market/for_sale")

def get_cards_price(print_all=1, from_file=0):
    global MARKET_REAL_DATA
    count = 0
    if from_file :
        MARKET_REAL_DATA = load_json_from_file("sm_market.txt")
    else:
        MARKET_REAL_DATA = get_data_from_sm("market/for_sale")
#            save_to_file_json("sm_market.txt", rets)

    market_data = []
    market_gd_data = []
    for r in MARKET_REAL_DATA:
        market_id = r["market_id"]
        card_detail_id = r["card_detail_id"]
        edition = r["edition"]
        gold = r["gold"]
        uid = r["uid"]
        buy_price = r["buy_price"]
        seller = r["seller"]
        xp = r["xp"]

        count += 1
        #print(card_detail_id, edition, gold, uid, buy_price, seller, xp)
        cards = get_single_cards(card_detail_id, edition, gold, xp)
        if (cards == 0 ) :
            cards = 1
        bcx_price = float(buy_price) / cards
        card_name = CARD_ID_NAME[str(card_detail_id)]
#        if card_name[0] == 'Flame Imp' :
#           print('h')

        card_info = [card_detail_id, CARD_ID_NAME[str(card_detail_id)], buy_price, xp, bcx_price]
        if (gold) :
            market_gd_data.append(card_info)
        else :
            market_data.append(card_info)

    slist = sorted(market_data, key = lambda x: (x[4]))  # 0번째가 key
    sglist = sorted(market_gd_data, key = lambda x: (x[4]))  # 0번째가 key
    return slist, sglist

def print_market_card_list(print_all, slist, sglist) :
    print("== general ==")
    display_cards(print_all, slist, MIN_PRICES['general_beta_rewards'])
    print("== gold ==")
    display_cards(print_all, sglist, MIN_PRICES['general_beta_rewards_gold'])

MARGIN = 0.97
def display_cards(print_all, slist, min_price) :
    displayed = []
    cnt = 1
    # cd = [id, [name, rarirty(카드종류)], 가격(str), 0, 가격(float)]
    # common or intesting card
    for cd in slist :
        if ( print_all and cnt > MAX_NUM_CARD_PRINTING ):
            break
        if ( cd[0] not in displayed) :
            if print_all :
                displayed.append(cd[0])
                buy = ''
                if (cd[4] < min_price['common'] * MARGIN) :
                    buy = 'buy f'
                    if (cd[4] < min_price['common'] / 1.05 * 1.01 * MARGIN) :
                        buy_s = 'buy s'
                # id, name, price, below여부
                print (format(cd[0], "3d"), format(cd[1][0], "20s"), format(cd[4], "6.3f"), buy)
                cnt += 1
            elif cd[1][0] in INT_CARDS :
                displayed.append(cd[0])
                print (format(cd[0], "3d"), format(cd[1][0], "20s"), format(cd[4], "6.3f"))
                cnt += 1
    if (print_all == 0) :
        return
    # rare
    print('--- rare ---')
    displayed = []
    cnt= 1
    for cd in slist :
        if ( cnt > 5 ):
            break
        if ( cd[0] not in displayed) :
            if print_all :
                if cd[1][1] == 2 : #rare
                    displayed.append(cd[0])
                    buy = ''
                    buy_s = ''
                    if (cd[4] < min_price['rare']* MARGIN) :
                        buy = 'buy f'
                    if (cd[4] < min_price['rare'] / 1.05 * 1.01 * MARGIN) :
                        buy_s = 'buy s'
                    print (format(cd[0], "3d"), format(cd[1][0], "20s"), format(cd[4], "6.3f"), buy, buy_s)
                    cnt += 1
    # epic
    print('--- epic ---')
    displayed = []
    cnt= 1
    for cd in slist :
        if ( cnt > 3 ):
            break
        if ( cd[0] not in displayed) :
            if print_all :
                if cd[1][1] == 3 : #epic
                    displayed.append(cd[0])
                    buy = ''
                    if (cd[4] < min_price['epic']* MARGIN) :
                        buy = 'buy f'
                    if (cd[4] < min_price['epic'] / 1.05 * 1.01 * MARGIN) :
                        buy_s = 'buy s'
                    print (format(cd[0], "3d"), format(cd[1][0], "20s"), format(cd[4], "6.3f"), buy, buy_s)
                    cnt += 1
    # leg
    print('--- leg ---')
    displayed = []
    cnt= 1
    for cd in slist :
        if ( cnt > 2 ):
            break
        if ( cd[0] not in displayed) :
            if print_all :
                if cd[1][1] == 4 : #leg
                    displayed.append(cd[0])
                    buy = ''
                    if (cd[4] < min_price['leg']* MARGIN) :
                        buy = 'buy f'
                    if (cd[4] < min_price['leg'] / 1.05 * 1.01 * MARGIN) :
                        buy_s = 'buy s'
                    print (format(cd[0], "3d"), format(cd[1][0], "20s"), format(cd[4], "6.3f"), buy, buy_s)
                    cnt += 1

def print_this_team_info(type, account, res) :
    details = json.loads(res["details"])
    winner = res['winner']
    player1 = res['player_1']
    player2 = res['player_2']
    team = details['team2']
    if (player1 == winner) : # team1
        team = details['team1']

    print(type, player1, player2, 'winner is ', winner)
    if (team == None) :
        return 
#        self.my_team_info
# { 'mana': 'ruleset':'inactive';'color';'summoner':{uid, id}, 'monsters':[{}{}{}]

    print("\nConditions:", res['mana_cap'], res['ruleset'], res['inactive'])

    summoner_id = str(team['summoner']['card_detail_id'])
    print("--- winner team info ---")

    print(team['color'], '\nsummoner:', CARD_ID_NAME[summoner_id][0])

    monsters = team['monsters']
    found = []
    for mon in monsters :
        found.append(CARD_ID_NAME[str(mon['card_detail_id'])][0])

    print('monsters:', found)
    print('---')


def request_get(url, echo=0) :
    response = ""
    cnt2 = 0
    while str(response) != '<Response [200]>' and cnt2 < 10:
        if echo : 
          print("requests request_get", url)
        response = requests.get(url)
        if str(response) != '<Response [200]>':
            print('sleep ', url)
            time.sleep(15)
        cnt2 += 1
    return response.json()


def find_card(name) :
    for acc in INT_ACCOUNTS :
        found = []
        url = "https://steemmonsters.com/cards/collection/"+acc
        holding_cards = request_get(url)
        for card in holding_cards['cards'] :
            id = card['card_detail_id']
            if ( CARD_ID_NAME[str(id)][0].upper() == name.upper()) :
                if (acc not in found) :
                    print(format(acc, "16s"), name)
                    found.append(acc)
     

def game_history(account) :
        url = "https://steemmonsters.com/battle/history?player=%s" % account
        battles = request_get(url)
        cnt = 1
        updated = 0
        for battle in battles['battles'] :
            if cnt > MAX_BATTLE_NUM :
                break
            cnt += 1
            res_url = "https://steemmonsters.com/battle/result?id=%s" %  battle['battle_queue_id_1']
            res = request_get(res_url)
            print_this_team_info(battle['match_type'], account, res)


def get_date(tm) :
    tt = tm.split("T")
    return tt[0]

def find_prize(tour, user) :
    path = 'tournaments/find?id='+tour['id']
    tourna_info = get_data_from_sm(path)

    for winner in tourna_info['players'] :
        if winner['player'] == user :
            if winner['prize'] == None:
                return 0

            print(get_date(tour['start_date']), format(winner['prize'], "16s"), tour['name'])
            amount = winner['prize'].split(' ')
            return float(amount[0])
    return 0

    
def tournament_prizes(user) :
    total = 0
    completed_tours = get_data_from_sm("tournaments/completed")
    cnt = 0
    for tour in completed_tours :
        amount = find_prize(tour, user)
        if ( amount > 0 ) :
            total += amount
            cnt += 1
        if (cnt > 5) :
            break
    print("total prize :", total)

def get_cur_low_card_price(id, plist) :
    cnt = 0
    for p in plist :
        if p[0] == id :
            return p[4]
    return 0

# updated 2019/9/27 open_all에 대한 대응 추가
def value_of_open_packs(player, num_packs, param, plist, pglist) :
#    https://api.steemmonsters.io/players/history?username=tradingideas&from_block=-1&limit=250&types=sm_pack_purchase,sm_open_pack,open_pack,sm_open_all,open_all
    print(' id : ', player)
    packs = get_data_from_sm("/players/history?username="+player+"&from_block=-1&limit=250&types="+param, 1)
    open_cards = {}
    cnt = 1
    if len(packs) == 0 : 
      print('no opened pack')
      return
    for pack in packs :
        if ( cnt > int(num_packs) ) :
            break
        if (pack['result'] == None) :
            continue
        cards = json.loads(pack['result'])
        if param != "sm_claim_reward" :
            cards = cards['cards']    # reward와 open pack의 경우에 key가 틀리다.        
            cnt += len(cards)/5   # beta orb open (for open_all)
        else :
            cnt += 1            # reward open

        for card in cards :
            gold = ''
            if card['gold'] :
                gold = 'gold'
            id = card['card_detail_id']
            if id in open_cards : 
                val = open_cards[id]
                if card['gold'] :
                    val[1] += 1
                else :
                    val[0] += 1
            else :
                if card['gold'] :
                    open_cards[id] = [0,1]
                else :
                    open_cards[id] = [1,0]

    total =[0,0]
    list = []
    for card in open_cards :
        val = open_cards[card]
        total[0] += val[0]
        total[1] += val[1]
        #[id, type, val1, val2]
        info = [card, CARD_ID_NAME[str(card)][1], val[0], val[1]]
        list.append(info)

    gen_prices = 0
    gold_prices = 0
    slist = sorted(list, key = lambda x: (x[1]))  # 1번째가 key (type)
    for card in slist :
        price = get_cur_low_card_price(card[0], plist)
        price_gold = get_cur_low_card_price(card[0], pglist)
        gen_prices += card[2] * price
        gold_prices += card[3] * price_gold
        name = CARD_ID_NAME[str(card[0])][0]
        print(format(name, "20s"), format(CARD_TYPE_NAME[card[1]], "9s"), "[", format(card[2], "3d"), ",", format(card[3],"3d"), "]", format(card[2] * price,"6.2f"), format(card[3] * price_gold,"6.2f") )

    print("-----\ntotal value: $", format(gen_prices+gold_prices, "7,.2f"), ' total #cards:', total[0]+total[1])

def    has_gold_card_order(acc, sglist, cd_id) :
    for cd in sglist :
        if ( cd[0] == cd_id) :
            return 'Gold'
    return ' '

def print_this_pending_order(card, gd, num) :
    gold = ' '
    if gd != ' ' :
        gold = '+ gold card'
    # id, name, price, edition
    edition = EDITIONS[card[6]]
    print (format(card[0], "3d"), format(card[1][0], "20s"), format(card[2], "8s"), format(edition, "6s"), format(num, "4d"), gold)

def    print_my_pending_orders(acc, slist, sglist) :
    displayed = []
    cnt = 1
    gold = ' '
    # cd = [id, [name, rarirty(카드종류)], 가격(str), 0, id, seller]
    # common or intesting card
    pre_card = [-1]
    same_card = 1
    for cd in slist :
      if ( cd[0] not in displayed) :
          displayed.append(cd[0])
      if (pre_card[0] == -1) :  # 첫 카드에 대한 예외처리
          pre_card = cd
          continue

      if (pre_card[0] == cd[0]) : # 동일한 카드의 주문이 또 있느냐?
          same_card += 1
          continue
  
      gd = has_gold_card_order(acc, sglist, pre_card[0])
      print_this_pending_order(pre_card, gd, same_card)

      printed = pre_card[0]
      cnt += 1
      pre_card = cd
      same_card = 1
#            if (cnt % 20) == 0 :
#                print("press any key")
#                input()
    if printed != pre_card[0] : # print last card
        gd = has_gold_card_order(acc, sglist, pre_card[0])
        print_this_pending_order(pre_card, gd, same_card)

    # find only gold card
    print_pending_gold_only(displayed, sglist)
    print('-----------\n Total pending cards is ', len(slist) + len(sglist) )

def    print_pending_gold_only(displayed, sglist) :
    for card in sglist :
        if card[0] not in displayed :
            displayed.append(card[0])
            print_this_pending_order(card, 'Gold', 0)

def    get_my_pending_orders(acc) :
    market_data = []
    market_gd_data = []
    count = 0
    slist = []
    sglist = []
    for r in MARKET_REAL_DATA:
        if r["seller"] != acc :
            continue
        market_id = r["market_id"]
        card_detail_id = r["card_detail_id"]
        edition = r["edition"]
        gold = r["gold"]
        uid = r["uid"]
        buy_price = r["buy_price"]
        xp = r["xp"]
        card_name = CARD_ID_NAME[str(card_detail_id)]

        count += 1
        card_info = [card_detail_id, CARD_ID_NAME[str(card_detail_id)], buy_price, xp, market_id, acc, edition]
        if (gold) :
            market_gd_data.append(card_info)
        else :
            market_data.append(card_info)

        # alphabet 순으로 소팅
        slist = sorted(market_data, key = lambda x: (x[1]), reverse=False)  # 1번째가 key (name)
        sglist = sorted(market_gd_data, key = lambda x: (x[1]), reverse=False)  # 1번째가 key (name)

    return slist, sglist

def    my_pending_orders(acc) :
    print("id : ", acc)
    reload_market_data()
    slist, sglist = get_my_pending_orders(acc)
    if slist == [] :
        return    
    print_my_pending_orders(acc, slist, sglist)

import time
from datetime import datetime
#start : format "2019-10-05T14:00:52.206Z"
#end : format "2019-10-05T14:00:52.206Z" 
#    or '' 현재 utc 시간 얻어서 처리
def time_diff_in_sec(start, end='', utc=1) : # return based on sec
    st = start.split('.')  # milisec 삭제
    st_time = datetime.strptime(st[0],'%Y-%m-%dT%H:%M:%S') # datetime 포맷으로 변경

    if end == '' : # 현재 시각을 얻는다.
        end_time = datetime.utcnow()
        if utc != 1  : # local time 
            end_time = datetime.now()
    else :
        end = end.split('.')  # milisec 삭제
        end_time = datetime.strptime(end[0],'%Y-%m-%dT%H:%M:%S') # datetime 포맷으로 변경

    diff = end_time-st_time
    return (diff.total_seconds())

QUEST_NAME = {'Rising Dead' : 'Black',
              'Pirate Attacks' : 'Blue',
              "Stir the Volcano" : 'Red',
              "Lyanna's Call" : 'Green',
              'Defend the Borders' : 'White',
}
def print_dec_quest() :
    print("--- quest info ---")
    for acc in INT_ACCOUNTS :
        url =  'https://steemmonsters.com/players/quests?username=' + acc
        r = requests.get(url)
        quest_inf = r.json()
        if quest_inf == [] :
            continue
        quest_info = quest_inf[0]
        quest_done = 0
        diff_hours = time_diff_in_sec(quest_info['created_date']) / 3600  # 현재 시간 기준으로 비교
        # claim되었는지 확인, 이전 quest가 끝났다는 의미
        if quest_info['claim_date'] :
            # qeust 이후 24시간이 지났는지 확인
            if diff_hours < 24 :
                quest_done = 1

        print(format(acc,"13s"), "quest :",  quest_done, format(diff_hours,"5.2f"), QUEST_NAME[quest_info['name']])

        time.sleep(5)

    # https://steemmonsters.com/players/balances?username==tradingideas
    dec_total = 0
    for acc in INT_ACCOUNTS :
        url =  'https://steemmonsters.com/players/balances?username=' + acc
        r = requests.get(url)
        profiles = r.json()
        if profiles == [] :
            print("not existed account", acc)
            continue
        dec = 0
        ecr = 0
        for site in profiles:
            if site['token'] == 'DEC' :
                dec = site['balance']
                dec_total += dec
            elif site['token'] == 'ECR' :
                ecr = site['balance']

        print(format(acc, "15s"), "mana:", ecr, "dec:", format(dec, "8,.0f"))
        time.sleep(5)
    print("DEC total :", format(dec_total, "8,.0f"))

def menu1() :

    while(1) :
        print("\n=============================")
        print("1) card prices")
        print("2) interesting cards price")
        print("3) card remain status")
        print("----")
        print("4) my pending orders")
        print("5) cards need for purchasing")
        print("----")
        print("6) tournament prizes")
        print("----")
        print("7) open packs value")
        print("71) daily quest value")
        print("----")
        print("8) find the card holder")
        print("----")
        print("9) game history")
        print("10) DEC and Quest status")
        print("----")
        print("0) end")
        print("=============================")

        val = input()
        args = val.split(' ')
        if ( val == '1' ) :
            get_smon_settings()
            print('steem price : ', SMON_SETTINGS['steem_price'], 'dec price :', SMON_SETTINGS['dec_price']/SMON_SETTINGS['steem_price'])
            slist, sglist = get_cards_price(1,0) # (print_all = 1, from file = 1)
            print_market_card_list(1, slist, sglist)
        elif ( val == '2' ) :
            get_smon_settings()
            slist, sglist = get_cards_price(0,0) # (print_all = 0(only int), from file = 1)
            print_market_card_list(0, slist, sglist)
        elif ( val == '3' ) :
            card_issued_status()
        elif ( args[0] == '4' ) :
            if (len(args) > 1) :
                my_pending_orders(args[1])
            elif (len(args) == 1) :
                my_pending_orders(INT_ACCOUNTS[0])
            else :
                print("usage : 4 account")
        elif ( args[0] == '5' ) :
            get_smon_settings()
            sm_trading.init_steem_bc()
            sm_trading.buy_cards_within_condition()
        elif ( args[0] == '6' ) :
            if (len(args) > 1) :
                tournament_prizes(args[1])
            elif (len(args) == 1) :
                tournament_prizes(INT_ACCOUNTS[0])
            else :
                print("usage : 6 account")
        elif ( args[0] == '7' or args[0] == '71') :
            get_smon_settings()
            acc = INT_ACCOUNTS[0] 
            if (len(args) > 2) :
                acc = args[1]
                num = args[2]
            elif(len(args) == 2) :
                num = args[1]
            else :
                print("usage : 7 account #packs or 7 #packs")
                continue

            get_smon_settings()
            slist, sglist = get_cards_price(1,0) # (print_all = 1, from file = 1)
            param = "sm_pack_purchase,sm_open_pack,open_pack,sm_open_all,open_all"
            if args[0] == '71' :
                param = "sm_claim_reward"
            value_of_open_packs(acc, num, param, slist, sglist)
        elif ( args[0] == '8' ) :
            if (len(args) == 1) :
                name = input()
                find_card(name)
            else :
                print("usage : 8 (enter) card_name")
        elif ( args[0] == '9' ) :
            if (len(args) > 1) :
                game_history(args[1])
            elif (len(args) == 1) :
                game_history(INT_ACCOUNTS[0])
            else :
                print("usage : 9 account")
        elif ( args[0] == '10' ) :
            print_dec_quest()                
        elif ( val == '0' ) :
            return
        else  :
            print("press number")

if __name__ == "__main__":
    menu1()