forked from LampAndMaxAxie/LampAndMaxAxieBot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
UtilBot.py
1340 lines (1088 loc) · 48.1 KB
/
UtilBot.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
# Author: Michael Conard
# Purpose: An Axie Infinity utility bot. Gives QR codes and daily progress/alerts.
import datetime
import json
import math
import os
import os.path
import sys
import time
import traceback
import urllib
import asyncio
import discord
import numpy as np
import pandas as pd
import pytz
import qrcode
import requests
import urllib3
from PIL import Image
from loguru import logger
from urllib3 import Retry
import AccessToken
import Common
import DB
try:
CACHE_TIME = int(Common.config.get('Bot', 'cacheTimeMinutes'))
if int(CACHE_TIME) < 30:
logger.warning("Configured cache time invalid, setting to 30 minutes")
CACHE_TIME = 30
tz1String = Common.config.get('Bot', 'timezone1')
tz2String = Common.config.get('Bot', 'timezone2')
tz1 = pytz.timezone(tz1String)
tz2 = pytz.timezone(tz2String)
tzutc = pytz.timezone('UTC')
except:
logger.error("Please fill out a [Bot] section with cacheTimeMinutes, timezone1, and timezone2.")
sys.exit()
scholarCache = {}
summaryCache = {}
battlesCache = {}
teamCache = {}
slpEmojiID = {}
graphQL = "https://graphql-gateway.axieinfinity.com/graphql"
gameAPI = "https://game-api.skymavis.com/game-api"
def formatToRonin(address):
return address.replace('0x', 'ronin:', 1);
def getQRCode(accessToken, discordID):
# Function to create a QRCode from the accessToken
# Make an image as a QR Code from the accessToken
img = qrcode.make(accessToken)
# Save the image
imgName = "./qr/" + str(discordID) + 'QRCode.png'
img.save(imgName)
return imgName
# setup requests pool
retryAmount = 3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
retries = Retry(connect=retryAmount, read=retryAmount, redirect=2, status=retryAmount, status_forcelist=[502, 503])
http = urllib3.PoolManager(retries=retries)
async def getMarketplaceProfile(address, attempts=0):
url = "https://axieinfinity.com/graphql-server-v2/graphql?query={publicProfileWithRoninAddress(roninAddress:\"" + address + "\"){accountId,name}}"
payload = {}
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)',
}
try:
response = requests.request("GET", url, headers=headers, data=payload)
jsonDat = json.loads(response.text)
return jsonDat['data']['publicProfileWithRoninAddress']['name']
except Exception:
if attempts > 3:
# logger.error("Error in getMarketplaceProfile")
# logger.error(e)
return None
else:
return await getMarketplaceProfile(address, attempts+1)
async def sendErrorToManagers(e, flag):
tb = traceback.format_exc()
lineNumber = str(sys.exc_info()[-1].tb_lineno)
if flag != "":
msg = f"On {flag}:\n"
else:
msg = ""
msg += f"Caught exception: {e} on line {lineNumber}\n"
msg += f"```\n{tb}\n```"
mgrIds = await DB.getAllManagerIDs()
await Common.messageManagers(msg, mgrIds)
def getEmojiFromReact(reaction):
if type(reaction.emoji) is str:
emoji = reaction.emoji
else:
emoji = reaction.emoji.name
return emoji
async def getKeyForUser(user):
seedNum = user["seed_num"]
accountNum = user["account_num"]
scholarAddr = user["scholar_addr"]
ret = await Common.getFromMnemonic(seedNum, accountNum, scholarAddr)
if ret is None:
return None, None
return ret["key"], ret["address"]
def is_int(val):
try:
int(val)
except ValueError:
return False
return True
# fetch a remote image
def saveUrlImage(url, name):
try:
urllib.request.urlretrieve(url, name)
return name
except:
logger.error("Erroring downloading image " + url)
return None
def concatImages(imagePaths, name, excessPxl=0):
try:
images = [Image.open(x) for x in imagePaths]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths) + excessPxl
max_height = max(heights)
new_im = Image.new('RGBA', (total_width, max_height), (0, 0, 0, 0))
x_offset = excessPxl
for im in images:
new_im.paste(im, (x_offset, 0))
x_offset += im.size[0]
new_im.save(name)
return name
except:
logger.error("Error combining images")
return None
# get a player's Axie Infinity game-api auth/bearer token
def getPlayerToken(roninKey, roninAddr):
try:
changed = False
# make the caching file if it doesn't exist
if not os.path.exists("jwtTokens.json"):
f = open("jwtTokens.json", 'w')
f.write("{}")
f.close()
changed = True
with open("jwtTokens.json") as f:
tokenBook = json.load(f)
# check if cached token is available and not-expired for player
if roninAddr in tokenBook and int(tokenBook[roninAddr]["exp"]) > int(time.time()):
token = tokenBook[roninAddr]["token"]
else:
# generate new token
token = AccessToken.GenerateAccessToken(roninKey, roninAddr)
exp = int(time.time()) + 6 * 24 * 60 * 60 # 6 day expiration, to be shy of 7 days
tokenBook[roninAddr] = {"token": token, "exp": exp}
changed = True
if changed:
# save the tokens
with open("jwtTokens.json", 'w') as f:
json.dump(tokenBook, f)
except:
logger.error("Failed to get token for: " + roninAddr)
logger.error(traceback.format_exc())
return None
return token
# make an API request and process the result as JSON data
async def makeJsonRequestWeb(url):
response = None
try:
response = http.request(
"GET",
url,
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36",
"Accept": "*/*",
}
)
jsonDat = json.loads(response.data.decode('utf8')) # .decode('utf8')
except Exception as e:
logger.error("Exception in makeJsonRequest for: " + url)
logger.error(response.data.decode('utf8'))
# traceback.print_exc()
await sendErrorToManagers(e, url)
return None
return jsonDat
# make an Axie Infinity game-api authorized request and process the result as JSON data
async def makeJsonRequest(url, token, attempt=0):
response = None
try:
response = http.request(
"GET",
url,
headers={
"Host": "game-api.skymavis.com",
"User-Agent": "UnityPlayer/2019.4.28f1 (UnityWebRequest/1.0, libcurl/7.52.0-DEV)",
"Accept": "*/*",
"Accept-Encoding": "identity",
"Authorization": 'Bearer ' + token,
"X-Unity-Version": "2019.4.28f1"
}
)
jsonDat = json.loads(response.data.decode('utf8')) # .decode('utf8')
succ = False
if 'success' in jsonDat:
succ = jsonDat['success']
if 'story_id' in jsonDat:
succ = True
if not succ:
if 'details' in jsonDat and len(jsonDat['details']) > 0:
if 'code' in jsonDat:
logger.error(f"API call failed in makeJsonRequest for: {url}, {jsonDat['code']}, attempt {attempt}")
else:
logger.error(f"API call failed in makeJsonRequest for: {url}, {jsonDat['details'][0]}, attempt {attempt}")
else:
logger.error(f"API call failed in makeJsonRequest for: {url}, attempt {attempt}")
if attempt < 3:
return await makeJsonRequest(url, token, attempt + 1)
else:
return None
except Exception as e:
logger.error(f"Exception in makeJsonRequest for: {url}, attempt {attempt}")
logger.error(response.data.decode('utf8'))
# traceback.print_exc()
if attempt < 3:
return await makeJsonRequest(url, token, attempt + 1)
else:
await sendErrorToManagers(e, url)
return None
return jsonDat
# get a player's daily stats and progress
async def getPlayerDailies(targetId, discordName, roninKey, roninAddr, guildId=None):
global scholarCache
# check caching
# print(scholarCache)
# print(targetId)
if targetId in scholarCache and int(scholarCache[targetId]["cache"]) - int(time.time()) > 0:
if scholarCache[targetId]["data"] is not None:
return scholarCache[targetId]["data"]
# get auth token
token = getPlayerToken(roninKey, roninAddr)
if token is None:
logger.error(f"Failed to get auth token for daily for {roninAddr}")
return None
# fetch data
url = gameAPI + "/clients/" + roninAddr + "/player-stats"
jsonDat = await makeJsonRequest(url, token)
urlQuests = gameAPI + "/clients/" + roninAddr + "/quests"
jsonDatQuests = await makeJsonRequest(urlQuests, token)
urlBattle = gameAPI + "/leaderboard?client_id=" + roninAddr + "&offset=0&limit=0"
jsonDatBattle = await makeJsonRequest(urlBattle, token)
urlBalance = gameAPI + "/clients/" + roninAddr + "/items/1"
jsonDatBalance = await makeJsonRequest(urlBalance, token)
# fail out if any data is missing
if jsonDat is None or jsonDatQuests is None or jsonDatBattle is None or jsonDatBalance is None:
logger.error(f"Failed an API call for daily for {roninAddr}")
return None
try:
meta = jsonDat['meta_data']
jsonDat = jsonDat['player_stat']
utc_time = int(datetime.datetime.now(tzutc).timestamp())
cacheExp = utc_time + CACHE_TIME * 60
# process data
maxEnergy = meta['max_energy']
lastUpdatedStamp = int(jsonDat['updated_at'])
# player-stats, energy/daily SLP/match counts
remainingEnergy = int(jsonDat['remaining_energy'])
pvpSlp = int(jsonDat['pvp_slp_gained_last_day'])
pveSlp = int(jsonDat['pve_slp_gained_last_day'])
# quests, quest completion data and progress
if len(jsonDatQuests['items']) > 0:
quest = jsonDatQuests['items'][0]
questClaimed = quest['claimed'] is not None
checkIn = quest['missions'][0]['is_completed']
pveQuest = quest['missions'][1]['progress']
pveCount = pveQuest # temporary
pveQuestN = quest['missions'][1]['total']
pvpQuest = quest['missions'][2]['progress']
pvpCount = pvpQuest # temporary
pvpQuestN = quest['missions'][2]['total']
questSlp = 0
questCompleted = pveQuest >= pveQuestN and pvpQuest >= pvpQuestN and checkIn
if questCompleted and questClaimed:
questSlp = 25
else:
quest = None
questClaimed = None
checkIn = False
pveQuest = 0
pveCount = pveQuest # temporary
pveQuestN = 0
pvpQuest = 0
pvpCount = pvpQuest # temporary
pvpQuestN = 0
questSlp = 0
questCompleted = False
questSlp = 0
# sometimes it returns 0 energy if they haven't done anything yet
#if questSlp == 0 and remainingEnergy == 0 and pvpCount == 0 and pveCount == 0 and pveSlp == 0:
# if maxEnergy is not None and maxEnergy > 0:
# remainingEnergy = maxEnergy
# else:
# remainingEnergy = 20
# battle data. mmr/rank/wins etc
player = jsonDatBattle['items'][1]
name = player["name"]
mmr = int(player["elo"])
rank = int(player["rank"])
wins = int(player["win_total"])
losses = int(player["lose_total"])
draws = int(player["draw_total"])
if wins + losses + draws > 0:
pass
# items, account/lifetime/earned SLP and claim date
lifetimeSlp = jsonDatBalance["blockchain_related"]["checkpoint"]
if lifetimeSlp is None:
lifetimeSlp = 0
else:
lifetimeSlp = int(lifetimeSlp)
totalSlp = int(jsonDatBalance["total"])
roninSlp = jsonDatBalance["blockchain_related"]["balance"]
claimableSlp = jsonDatBalance["claimable_total"]
if roninSlp is None:
roninSlp = 0
else:
roninSlp = int(roninSlp)
if totalSlp - roninSlp - claimableSlp < 0:
inGameSlp = int(totalSlp - claimableSlp)
else:
inGameSlp = int(totalSlp - roninSlp - claimableSlp)
lastClaimStamp = int(jsonDatBalance["last_claimed_item_at"])
nextClaimStamp = lastClaimStamp + (14 * 24 * 60 * 60)
daysSinceClaim = math.ceil((utc_time - int(jsonDatBalance["last_claimed_item_at"])) / (60 * 60 * 24))
claimDate = tz1.fromutc(
datetime.datetime.fromtimestamp(int(jsonDatBalance["last_claimed_item_at"]) + (14 * 24 * 60 * 60)))
daysRemaining = 14 - daysSinceClaim
if daysRemaining < 0:
pass
if pvpCount > 0:
pass
if pveCount > 0:
pass
questTxt = ""
if questCompleted and questClaimed:
questTxt = "completed and claimed"
elif questCompleted and not questClaimed:
questTxt = "completed but not claimed"
elif not questCompleted:
questTxt = "incomplete"
checkInTxt = "complete" if checkIn else "incomplete"
slpPerDay = round(inGameSlp / daysSinceClaim, 1)
pveTxt = str(pveQuest) + '/' + str(pveQuestN)
pvpTxt = str(pvpQuest) + '/' + str(pvpQuestN)
slpIcon = None
if guildId and guildId in slpEmojiID:
if slpEmojiID[guildId] is not None:
slpIcon = '<:slp:{}>'.format(slpEmojiID[guildId])
if slpIcon is None:
slpIcon = ""
if Common.hideScholarRonins:
roninAddr = "<hidden>"
embed = discord.Embed(title="Scholar Daily Stats", description="Daily stats for scholar " + discordName,
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: Scholar Name", value=f"{name}")
embed.add_field(name=":house: Ronin Address", value=f"{formatToRonin(roninAddr)}")
embed.add_field(name=":baggage_claim: Next Claim Ready", value=f"<t:{nextClaimStamp}:R>")
embed.add_field(name="Lifetime SLP", value=f"{lifetimeSlp} {slpIcon}")
embed.add_field(name="Current SLP", value=f"{inGameSlp} {slpIcon}")
embed.add_field(name="Avg SLP/Day", value=f"{slpPerDay} {slpIcon}")
embed.add_field(name=":crossed_swords: Arena MMR", value=f"{mmr}")
embed.add_field(name=":trophy: Arena Rank", value=f"{rank}")
embed.add_field(name=":cloud_lightning: Remaining Energy", value=f"{remainingEnergy}")
if quest is not None:
embed.add_field(name=":white_check_mark: Quest - Check in", value=f"{checkInTxt}")
embed.add_field(name=":bear: Quest - PvE", value=f"{pveTxt}, {pveSlp}/50 SLP")
embed.add_field(name=":bow_and_arrow: Quest - PvP", value=f"{pvpTxt}")
embed.add_field(name=":scroll: Daily Quest", value=f"{questTxt}")
embed.add_field(name=":clock1: Last Updated", value=f"<t:{lastUpdatedStamp}:f>")
embed.add_field(name=":floppy_disk: Uncache Timer", value=f"<t:{cacheExp}:R>")
# package the data to cache and return
res = {
"embed": embed,
"mmr": mmr,
"rank": rank,
"name": name,
"pvpSlp": pvpSlp,
"pveSlp": pveSlp,
"pvpCount": pvpCount,
"pveCount": pveCount,
"questSlp": questSlp,
"totalSlp": pveSlp + pvpSlp + questSlp,
"energy": remainingEnergy,
"lifetimeSlp": lifetimeSlp,
"claimCycleDays": daysSinceClaim,
"inGameSlp": inGameSlp,
"discordName": discordName,
"avgSlpPerDay": round(inGameSlp / daysSinceClaim, 1),
"claimDate": claimDate
}
except Exception as e:
# traceback.print_exc()
logger.error(e)
logger.error(traceback.format_exc())
await sendErrorToManagers(e, discordName)
return None
# save to the cache
scholarCache[targetId] = {"data": res, "cache": cacheExp}
return res
# returns data on scholar's battles
async def getRoninBattles(roninAddr):
global battlesCache
roninAddr = roninAddr.replace("ronin:", "0x")
# check caching
if roninAddr in battlesCache and int(battlesCache[roninAddr]["cache"]) - int(time.time()) > 0:
return battlesCache[roninAddr]["data"]
# fetch data
url = "https://game-api.axie.technology/logs/pvp/" + roninAddr.replace("0x","ronin:")
jsonDat = await makeJsonRequestWeb(url)
urlRank = gameAPI + "/leaderboard?client_id=" + roninAddr + "&offset=0&limit=0"
jsonDatRank = await makeJsonRequest(urlRank, "none")
name = await getMarketplaceProfile(roninAddr)
if name is None:
name = "<unknown>"
# fail out if any data is missing
if jsonDat is None or jsonDatRank is None:
return None
try:
battles = jsonDat['battles']
# Arena data, mmr/rank
if len(jsonDatRank['items']) > 1:
player = jsonDatRank['items'][1]
else:
player = jsonDatRank['items'][0]
name = player["name"]
mmr = int(player["elo"])
rank = int(player["rank"])
utc_time = int(datetime.datetime.now(tzutc).timestamp())
cacheExp = utc_time + CACHE_TIME * 60
streakType = None
streakBroken = False
streakAmount = 0
axieIds = []
wins = 0
losses = 0
draws = 0
lastTime = None
latestMatches = []
for battle in battles:
if roninAddr == battle["first_client_id"]:
fighter = "first_team_fighters"
bClient = "first_client_id"
else:
fighter = "second_team_fighters"
bClient = "second_client_id"
if "eloAndItem" in battle:
eloDat = True
if battle["eloAndItem"][0]["player_id"] == roninAddr:
oldMmr = battle["eloAndItem"][0]["old_elo"]
newMmr = battle["eloAndItem"][0]["new_elo"]
if "_items" in battle["eloAndItem"][0]:
slp = int(battle["eloAndItem"][0]["_items"][0]["amount"])
else:
slp = 0
else:
oldMmr = battle["eloAndItem"][1]["old_elo"]
newMmr = battle["eloAndItem"][1]["new_elo"]
if "_items" in battle["eloAndItem"][1]:
slp = int(battle["eloAndItem"][1]["_items"][0]["amount"])
else:
slp = 0
else:
eloDat = False
if lastTime is None:
lastTime = int(datetime.datetime.strptime(battle['game_ended'], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=tzutc).timestamp())
fighter = "first_team_fighters"
if roninAddr != battle["first_client_id"]:
figher = "second_team_fighters"
axieIds = battle[fighter]
# count draw
if battle['winner'] == "draw":
draws += 1
result = 'draw'
# count win
elif battle['winner'] == roninAddr:
wins += 1
result = 'win'
# count loss
else:
losses += 1
result = 'lose'
# streak
if streakBroken:
pass
elif streakType is None:
streakType = result
streakAmount = 1
elif not streakBroken and streakType == result:
streakAmount += 1
elif not streakBroken and streakType != result:
streakBroken = True
if eloDat:
change = newMmr - oldMmr
if change >= 0:
resTxt = f"{result}, +{change}, {slp} SLP"
else:
resTxt = f"{result}, {change}, {slp} SLP"
else:
resTxt = result
if len(latestMatches) < 10:
latestMatches.append({'result': resTxt,
'replay': 'https://cdn.axieinfinity.com/game/deeplink.html?f=rpl&q={}'.format(
battle['battle_uuid'])})
axieImages = []
combinedImg = None
combinedIds = None
imgErr = False
for axieId in axieIds:
imgPath = './images/{}.png'.format(axieId)
if os.path.exists(imgPath):
axieImages.append(imgPath)
else:
axieUrl = 'https://storage.googleapis.com/assets.axieinfinity.com/axies/{}/axie/axie-full-transparent.png'.format(
axieId)
res = saveUrlImage(axieUrl, imgPath)
if res is None:
imgErr = True
break
else:
axieImages.append(imgPath)
if len(axieIds) >= 3 and not imgErr:
combinedIds = '{}-{}-{}.png'.format(axieIds[0], axieIds[1], axieIds[2])
combinedImg = './images/{}-{}-{}.png'.format(axieIds[0], axieIds[1], axieIds[2])
if not os.path.exists(combinedImg):
res = concatImages(axieImages, combinedImg)
if res is None:
imgErr = True
else:
imgErr = True
matches = wins + losses + draws
if matches == 0:
return None
winrate = 0
loserate = 0
drawrate = 0
if matches > 0:
winrate = round(wins / matches * 100, 2)
loserate = round(losses / matches * 100, 2)
drawrate = round(draws / matches * 100, 2)
replayText = ""
resultText = ""
count = 1
for match in latestMatches:
resultText += match['result'] + '\n'
if count <= 5:
replayText += '[Replay {}]({})\n'.format(count, match['replay'])
count += 1
streakText = "Current " + streakType.capitalize() + " Streak"
embed = discord.Embed(title="Account Recent Battles", description="Recent battles for address " + roninAddr,
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: In Game Name", value=f"{name}")
embed.add_field(name=":clock1: Last Match Time", value=f"<t:{lastTime}:R>")
embed.add_field(name=":anger: Arena Matches", value=f"{matches}, last ~7 days")
embed.add_field(name=":crossed_swords: Arena MMR", value=f"{mmr}")
embed.add_field(name=":trophy: Arena Rank", value=f"{rank}")
embed.add_field(name=f":pencil: {streakText}", value=f"{streakAmount}")
embed.add_field(name=":dagger: Arena Wins", value=f"{wins}, {winrate}%")
embed.add_field(name=":shield: Arena Losses", value=f"{losses}, {loserate}%")
embed.add_field(name=":broken_heart: Arena Draws", value=f"{draws}, {drawrate}%")
embed.add_field(name="Last 10 Results", value=f"{resultText}")
embed.add_field(name="Last 5 Replays", value=f"{replayText}")
embed.add_field(name=":floppy_disk: Uncache Timer", value=f"<t:{cacheExp}:R>")
# embed.set_footer(text=f"The first timezone is {tz1String} and the second is {tz2String}.")
if not imgErr:
embed.set_image(url=f"attachment://{combinedIds}")
res = {
'embed': embed,
'name': name,
'matches': matches,
'wins': wins,
'losses': losses,
'draws': draws,
'winrate': winrate,
'loserate': loserate,
'drawrate': drawrate,
'latest': latestMatches,
'replays': replayText,
'streakType': streakType,
'streakAmount': streakAmount
}
if not imgErr:
res['image'] = combinedImg
except Exception as e:
# traceback.print_exc()
logger.error(e)
await sendErrorToManagers(e, name)
return None
# save to the cache
battlesCache[roninAddr] = {"data": res, "cache": cacheExp}
return res
# returns data on scholar's battles
async def getScholarBattles(targetId, discordName, roninAddr):
global battlesCache
roninAddr = roninAddr.replace("ronin:", "0x")
# check caching
if roninAddr in battlesCache and int(battlesCache[roninAddr]["cache"]) - int(time.time()) > 0:
return battlesCache[roninAddr]["data"]
# fetch data
url = "https://game-api.axie.technology/logs/pvp/" + roninAddr.replace("0x","ronin:")
jsonDat = await makeJsonRequestWeb(url)
urlRank = gameAPI + "/leaderboard?client_id=" + roninAddr + "&offset=0&limit=0"
jsonDatRank = await makeJsonRequest(urlRank, "none")
# fail out if any data is missing
if jsonDat is None or jsonDatRank is None:
return None
try:
battles = jsonDat['battles']
# Arena data, mmr/rank
if len(jsonDatRank['items']) > 1:
player = jsonDatRank['items'][1]
else:
player = jsonDatRank['items'][0]
name = player["name"]
mmr = int(player["elo"])
rank = int(player["rank"])
utc_time = int(datetime.datetime.now(tzutc).timestamp())
cacheExp = utc_time + CACHE_TIME * 60
streakType = None
streakBroken = False
streakAmount = 0
axieIds = []
wins = 0
losses = 0
draws = 0
lastTime = None
latestMatches = []
for battle in battles:
if roninAddr == battle["first_client_id"]:
fighter = "first_team_fighters"
bClient = "first_client_id"
else:
fighter = "second_team_fighters"
bClient = "second_client_id"
if "eloAndItem" in battle:
eloDat = True
if battle["eloAndItem"][0]["player_id"] == roninAddr:
oldMmr = battle["eloAndItem"][0]["old_elo"]
newMmr = battle["eloAndItem"][0]["new_elo"]
if "_items" in battle["eloAndItem"][0]:
slp = int(battle["eloAndItem"][0]["_items"][0]["amount"])
else:
slp = 0
else:
oldMmr = battle["eloAndItem"][1]["old_elo"]
newMmr = battle["eloAndItem"][1]["new_elo"]
if "_items" in battle["eloAndItem"][1]:
slp = int(battle["eloAndItem"][1]["_items"][0]["amount"])
else:
slp = 0
else:
eloDat = False
if lastTime is None:
lastTime = int(datetime.datetime.strptime(battle['game_ended'], "%Y-%m-%dT%H:%M:%S").replace(tzinfo=tzutc).timestamp())
axieIds = battle[fighter]
# count draw
if battle['winner'] == "draw":
draws += 1
result = 'draw'
# count win
elif battle['winner'] == roninAddr:
wins += 1
result = 'win'
# count loss
else:
losses += 1
result = 'lose'
# streak
if streakBroken:
pass
elif streakType is None:
streakType = result
streakAmount = 1
elif not streakBroken and streakType == result:
streakAmount += 1
elif not streakBroken and streakType != result:
streakBroken = True
if eloDat:
change = newMmr - oldMmr
if change >= 0:
resTxt = f"{result}, +{change}, {slp} SLP"
else:
resTxt = f"{result}, {change}, {slp} SLP"
else:
resTxt = result
if len(latestMatches) < 10:
latestMatches.append({'result': resTxt,
'replay': 'https://cdn.axieinfinity.com/game/deeplink.html?f=rpl&q={}'.format(
battle['battle_uuid'])})
axieImages = []
combinedImg = None
combinedIds = None
imgErr = False
for axieId in axieIds:
imgPath = './images/{}.png'.format(axieId)
if os.path.exists(imgPath):
axieImages.append(imgPath)
else:
axieUrl = 'https://storage.googleapis.com/assets.axieinfinity.com/axies/{}/axie/axie-full-transparent.png'.format(
axieId)
res = saveUrlImage(axieUrl, imgPath)
if res is None:
imgErr = True
break
else:
axieImages.append(imgPath)
if len(axieIds) >= 3 and not imgErr:
combinedIds = '{}-{}-{}.png'.format(axieIds[0], axieIds[1], axieIds[2])
combinedImg = './images/{}-{}-{}.png'.format(axieIds[0], axieIds[1], axieIds[2])
if not os.path.exists(combinedImg):
res = concatImages(axieImages, combinedImg)
if res is None:
imgErr = True
else:
imgErr = True
matches = wins + losses + draws
if matches == 0:
return None
winrate = 0
loserate = 0
drawrate = 0
if matches > 0:
winrate = round(wins / matches * 100, 2)
loserate = round(losses / matches * 100, 2)
drawrate = round(draws / matches * 100, 2)
replayText = ""
resultText = ""
count = 1
for match in latestMatches:
resultText += match['result'] + '\n'
if count <= 5:
replayText += '[Replay {}]({})\n'.format(count, match['replay'])
count += 1
streakText = "Current " + streakType.capitalize() + " Streak"
embed = discord.Embed(title="Scholar Recent Battles", description="Recent battles for scholar " + discordName,
timestamp=datetime.datetime.utcnow(), color=discord.Color.blue())
embed.add_field(name=":book: In-Game Name", value=f"{name}")
embed.add_field(name=":clock1: Last Match Time", value=f"<t:{lastTime}:R>")
embed.add_field(name=":anger: Arena Matches", value=f"{matches}, last ~7 days")
embed.add_field(name=":crossed_swords: Arena MMR", value=f"{mmr}")
embed.add_field(name=":trophy: Arena Rank", value=f"{rank}")
embed.add_field(name=f":pencil: {streakText}", value=f"{streakAmount}")
embed.add_field(name=":dagger: Arena Wins", value=f"{wins}, {winrate}%")
embed.add_field(name=":shield: Arena Losses", value=f"{losses}, {loserate}%")
embed.add_field(name=":broken_heart: Arena Draws", value=f"{draws}, {drawrate}%")
embed.add_field(name="Last 10 Results", value=f"{resultText}")
embed.add_field(name="Last 5 Replays", value=f"{replayText}")
embed.add_field(name=":floppy_disk: Cached Until", value=f"<t:{cacheExp}:R>")
# embed.set_footer(text=f"The first timezone is {tz1String} and the second is {tz2String}.")
if not imgErr:
embed.set_image(url=f"attachment://{combinedIds}")
res = {
'embed': embed,
'matches': matches,
'wins': wins,
'losses': losses,
'draws': draws,
'winrate': winrate,
'loserate': loserate,
'drawrate': drawrate,
'latest': latestMatches,
'replays': replayText,
'streakType': streakType,
'streakAmount': streakAmount
}
if not imgErr:
res['image'] = combinedImg
except Exception as e:
# traceback.print_exc()
logger.error(e)
await sendErrorToManagers(e, str(targetId))
return None
# save to the cache
battlesCache[targetId] = {"data": res, "cache": cacheExp}
return res
async def getScholarExport():
df = pd.DataFrame(columns=['ScholarID', 'ScholarName', 'Seed', 'Account', 'ScholarAddr', 'PayoutAddr', 'Share'])
scholarsDict = await DB.getAllScholars()
if scholarsDict["success"] is None:
return None, None
for scholar in scholarsDict["rows"]:
df.loc[len(df.index)] = [scholar["discord_id"], scholar["name"], scholar["seed_num"], scholar["account_num"], scholar["scholar_addr"], scholar["payout_addr"], scholar["share"]]
return df
# builds a summary table of all scholars
async def getScholarSummary(sort="avgslp", ascending=False, guildId=None):
global summaryCache
utc_time = int(datetime.datetime.now(tzutc).timestamp())
cacheExp = utc_time + CACHE_TIME * 60
cacheEast = datetime.datetime.fromtimestamp(int(cacheExp)).replace(tzinfo=tzutc).astimezone(tz1)
try:
# check caching
if "cache" in summaryCache and int(summaryCache["cache"]) - int(time.time()) > 0:
df = summaryCache["df"]
# sort as desired
if sort in ["avgslp", "slp", "adventure", "adv"]:
df = df.sort_values(by=['SLP/Day'], ascending=ascending)
elif sort in ["mmr", "rank", "arena", "battle"]:
df = df.sort_values(by=['MMR'], ascending=ascending)
elif sort == "claim":
df = df.sort_values(by=['NextClaim'], ascending=ascending)
df['Pos'] = np.arange(1, len(df)+1)
return df, cacheEast
# build the data table
df = pd.DataFrame(
#columns=['Pos', 'Scholar', 'MMR', 'ArenaRank', 'CurSLP', 'SLP/Day', 'Energy', 'PvPWins', 'PvEWins', 'PvESLP', 'Quest', 'NextClaim'])
columns=['Pos', 'Scholar (In-Game)', 'Scholar (Discord)', 'MMR', 'ArenaRank', 'CurSLP', 'SLP/Day', 'Energy', 'PvPWins', 'NextClaim'])
scholarsDict = await DB.getAllScholars()
if scholarsDict["success"] is None:
return None, None
for scholar in scholarsDict["rows"]:
roninKey, roninAddr = await getKeyForUser(scholar)