forked from notnotmelon/skyblock-simplified
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
2154 lines (1808 loc) · 63 KB
/
bot.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
import skypy
skypy.enable_advanced_mode()
import os
import discord
import asyncio
import math
import traceback
import motor.motor_asyncio
import itertools
import re
import random
from statistics import mean, median, mode, pstdev, StatisticsError
from datetime import datetime, timezone, timedelta
from bs4 import BeautifulSoup
import cloudscraper
from aiohttp import ClientError
import traceback
import concurrent.futures
TIME_FORMAT = '%m/%d %I:%M %p UTC'
if os.environ.get('API_KEY') is None:
import dotenv
dotenv.load_dotenv()
keys = os.getenv('API_KEY').split()
def time_until(goal):
now = datetime.now(timezone.utc)
then = datetime.fromtimestamp(goal, timezone.utc)
delta = then - now
d, h, m, s = delta.days, delta // timedelta(hours=1), delta // timedelta(minutes=1), delta.seconds
if d:
return f'{d} days, {h} hours'
if h:
return f'{h} hours'
return f'0:{m:02}:{s:02}'
DAMAGING_POTIONS = {
'critical': {
'stats': {
'crit chance': [0, 10, 15, 20, 25],
'crit damage': [0, 10, 20, 30, 40]
},
'levels': [0, 3, 4]
},
'strength': {
'stats': {'strength': [0, 5.25, 13.125, 21, 31.5, 42, 52.5, 63, 78.75]}, # Assume cola
'levels': [0, 5, 6, 7, 8]
},
'spirit': {
'stats': {'crit damage': [0, 10, 20, 30, 40]},
'levels': [0, 3, 4]
},
'archery': {
'stats': {'enchantment modifier': [0, 17.5, 30, 55, 80]},
'levels': [0, 3, 4]
}
}
ORBS = {
'weird tuba': {
'internal': 'WEIRD_TUBA',
'stats': {'strength': 30}
},
'mana flux': {
'internal': 'MANA_FLUX_POWER_ORB',
'stats': {'strength': 10}
},
'overflux': {
'internal': 'OVERFLUX_POWER_ORB',
'stats': {'strength': 25}
}
}
LEADERBOARDS = {
'skill average': ('📈', lambda player: player.skill_average, None),
'minion slots': ('⛓', lambda player: player.unique_minions, lambda player: player.minion_slots),
'farming': ('🌾', lambda player: player.skill_xp['farming'], lambda player: player.skills['farming']),
'mining': ('⛏', lambda player: player.skill_xp['mining'], lambda player: player.skills['mining']),
'combat': ('⚔', lambda player: player.skill_xp['combat'], lambda player: player.skills['combat']),
'foraging': ('🪓', lambda player: player.skill_xp['foraging'], lambda player: player.skills['foraging']),
'enchanting': ('📖', lambda player: player.skill_xp['enchanting'], lambda player: player.skills['enchanting']),
'alchemy': ('⚗', lambda player: player.skill_xp['alchemy'], lambda player: player.skills['alchemy']),
'fishing': ('🎣', lambda player: player.skill_xp['fishing'], lambda player: player.skills['fishing']),
'carpentry': ('🪑', lambda player: player.skill_xp['carpentry'], lambda player: player.skills['carpentry']),
'runecrafting': ('⚜️', lambda player: player.skill_xp['runecrafting'], lambda player: player.skills['runecrafting']),
'zombie': ('🧟', lambda player: player.slayer_xp['zombie'], lambda player: player.slayers['zombie']),
'spider': ('🕸️', lambda player: player.slayer_xp['spider'], lambda player: player.slayers['spider']),
'wolf': ('🐺', lambda player: player.slayer_xp['wolf'], lambda player: player.slayers['wolf']),
'total slayer': ('☠️', lambda player: player.total_slayer_xp, None)
}
LEVELS = {name: LEADERBOARDS[name] for name in skypy.skills + skypy.slayers}
RANKS = [
['CAROLINA REAPER', 'GHOST PEPPER', 'HABAÑERO', 'JALAPEÑO', 'SWEET BANANA', 'BELL PEPPER'],
['WIZARD', 'KING', 'QUEEN', 'LORD', 'JESTER', 'PEASANT'],
['PRESIDENT', 'GENERAL', 'MAJOR', 'SERGEANT', 'CORPORAL', 'PRIVATE'],
['S', 'A', 'B', 'C', 'D', 'F'],
['MVP++', 'MVP+', 'MVP', 'VIP+', 'VIP', 'NON'],
['DRAGON', 'DINOSAUR', 'GILA', 'TURTLE', 'SNAKE', 'GECKO'],
['LEGENDARY', 'EPIC', 'RARE', 'UNCOMMON', 'COMMON', '" " " "SPECIAL" " " "'],
['GOD', 'PRO', 'ADVANCED', 'VIABLE', 'AVERAGE', 'NOOB'],
['PC', 'NINTENDO', 'PLAY STATION', 'XBOX', 'VR', 'MOBILE']
]
# List of players that bug abused skills or severely macroed for stats
EXPLOITERS = {
'6c80f48d85544035bb31e6cb9f40b948': ('farming', 'enchanting'),
'04e0ad3f4b7f4815bb39c3888249115c': ('farming',),
'6ac668e787e74561b86bae8c496d0f97': ('farming',),
'02bd483c511b4e1fbd0f0c071e2d0411': ('farming',),
'e91e2680d7da4bc4adbb30c04366f6fa': ('farming',),
'd14403fd77664905929ee1a6e365e623': ('enchanting',),
'8f0d1d399aee48f59d5af5f0f69e4eee': ('enchanting',),
'720d2a83efe446969bc29fbc8c98b31e': ('enchanting',),
'f33f51a796914076abdaf66e3d047a71': ('enchanting',),
'73464a378313409d8232076f44074bcf': ('enchanting',),
'7b488582998f405a84c19ad7a4e9b2e7': ('enchanting',),
'6170dede383a42a99db6166ca46a8469': ('combat',),
'6c5b615c2c47428aad137249d37c6fcc': ('farming',),
'44d03c6e2cba41799ad5c9d2f837d03d': ('farming',),
'446dea472dd0494b89260421b9981d15': ('combat',)
}
PROFILE_EMOJIS = {
'Apple': '🍎',
'Banana': '🍌',
'Blueberry': '🔵',
'Coconut': '🥥',
'Cucumber': '🥒',
'Grapes': '🍇',
'Kiwi': '🥝',
'Lemon': '🍋',
'Lime': '🍏',
'Mango': '🥭',
'Orange': '🍊',
'Papaya': '🍈',
'Peach': '🍑',
'Pear': '🍐',
'Pineapple': '🍍',
'Pomegranate': '👛',
'Raspberry': '🍒',
'Strawberry': '🍓',
'Tomato': '🍅',
'Watermelon': '🍉',
'Zucchini': '🥬'
}
# list of all enchantment powers per level. can be a function or a number
ENCHANTMENT_VALUES = {
# sword always
'sharpness': 5,
'giant_killer': lambda level: 25 if level > 0 else 0,
# sword sometimes
'smite': 8,
'bane_of_arthropods': 8,
'first_strike': 25,
'ender_slayer': 12,
'cubism': 10,
'execute': 10,
'impaling': 12.5,
# bow always
'power': 8,
# bow sometimes
'dragon_hunter': 8,
'snipe': 5, # Would be lower except I only use this for drags and magma bosses
# rod always
'spiked_hook': 5
}
MAX_BOOK_LEVELS = {
'sharpness': 6,
'giant_killer': 6,
'smite': 6,
'bane_of_arthropods': 6,
'first_strike': 4,
'ender_slayer': 6,
'cubism': 5,
'execute': 5,
'impaling': 3,
'power': 6,
'dragon_hunter': 5,
'snipe': 3,
'spiked_hook': 6
}
CHEAP_MAX_BOOK_LEVELS = {
'sharpness': 5,
'giant_killer': 5,
'smite': 5,
'bane_of_arthropods': 5,
'first_strike': 4,
'ender_slayer': 5,
'cubism': 5,
'execute': 5,
'impaling': 3,
'power': 5,
'dragon_hunter': 3,
'snipe': 3,
'spiked_hook': 5
}
# list of relevant enchants for common mobs
ACTIVITIES = {
'slayer bosses': [
'giant_killer',
'sharpness',
'power',
'spiked_hook',
'smite',
'bane_of_arthropods',
'execute'
],
'dragons': [
'giant_killer',
'sharpness',
'power',
'spiked_hook',
'ender_slayer',
'execute',
'dragon_hunter',
'snipe'
],
'zealots': [
'giant_killer',
'sharpness',
'power',
'spiked_hook',
'ender_slayer',
'first_strike'
],
'sea creatures': [
'giant_killer',
'sharpness',
'power',
'spiked_hook',
'first_strike',
'impaling'
],
'players': [
'giant_killer',
'sharpness',
'power',
'spiked_hook',
'execute',
'snipe'
],
'magma boss': [
'giant_killer',
'sharpness',
'power',
'spiked_hook',
'cubism',
'execute',
'snipe'
],
'horseman': [
'giant_killer',
'sharpness',
'power',
'spiked_hook',
'execute',
'snipe'
],
'other': [
'giant_killer',
'sharpness',
'power',
'spiked_hook',
'smite',
'bane_of_arthropods',
'first_strike'
]
}
RELEVANT_REFORGES = {
'forceful': (None, None, (7, 0, 0), None, None),
'itchy': ((1, 0, 3), (2, 0, 5), (2, 0, 8), (3, 0, 12), (5, 0, 15)),
'strong': (None, None, (4, 0, 4), (7, 0, 7), (10, 0, 10)),
'godly': ((1, 1, 1), (2, 2, 2), (4, 2, 3), (7, 3, 6), (10, 5, 8))
}
reforges_list = list(RELEVANT_REFORGES.values())
'''
RELEVANT_REFORGES = {
'forceful': ((2, 0), (4, 0), (7, 0), None, None),
'itchy': ((1, 3), (2, 5), (2, 8), (3, 12), (5, 15)),
'strong': (None, None, (4, 4), (7, 7), (10, 10))
}
'''
CLOSE_MESSAGE = '\n> _use **exit** to close the session_'
PET_EMOJIS = {
'SKELETON_HORSE': '💀',
'SNOWMAN': '⛄',
'BAT': '🦇',
'SHEEP': '🐑',
'CHICKEN': '🐔',
'WITHER_SKELETON': '🏴☠️',
'SILVERFISH': '🗿',
'RABBIT': '🐇',
'HORSE': '🐴',
'PIGMAN': '🐽',
'WOLF': '🐺',
'OCELOT': '🐱',
'LION': '🦁',
'ENDER_DRAGON': '🐲',
'GUARDIAN': '🛡️',
'ENDERMAN': '😈',
'BLUE_WHALE': '🐳',
'GIRAFFE': '🦒',
'PHOENIX': '🐦',
'BEE': '🐝',
'MAGMA_CUBE': '🌋',
'FLYING_FISH': '🐟',
'SQUID': '🦑',
'PARROT': '🦜',
'TIGER': '🐯',
'TURTLE': '🐢',
'SPIDER': '🕸️',
'BLAZE': '🔥',
'JERRY': '🤡'
}
class Embed(discord.Embed):
nbst = '\u200b'
def __init__(self, channel, *, user=None, **kwargs):
self.channel = channel
self.user = user
super().__init__(
color=self.color(channel),
**kwargs
)
@staticmethod
def color(channel):
default = 0xbf2158
if hasattr(channel, 'guild'):
color = channel.guild.me.color
return discord.Color(default) if color == 0x000000 else color
else:
return discord.Color(default)
def add_field(self, *, name, value, inline=True):
return super().add_field(name=f'**{name}**' if name else self.nbst, value=value or self.nbst, inline=inline)
async def send(self):
return await self.channel.send(self.user.mention if self.user else None, embed=self)
def format_pet(pet):
"""Returns a pretty string repersenting a pet"""
return f'{pet.title} |{pet.rarity.upper()}|' if pet else ''
WHITE = ('', '')
GRAY = ('brainfuck', '')
GREY = GRAY
PUKE = ('css', '')
GREEN = ('yaml', '')
BLUE = ('md', '#')
YELLOW = ('fix', '')
ORANGE = ('glsl', '#')
RED = ('diff', '-')
RARITY_COLORS = {'common': GREY, 'uncommon': GREEN, 'rare': BLUE, 'epic': ORANGE, 'legendary': YELLOW}
def colorize(s, color):
language, point = color
s = str(s)
if s:
return f'```{language}\n{point}' + s.replace('\n', f'\n{point}') + '\n```'
else:
return ''
formatting_codes = {
'0': GREY,
'1': BLUE,
'2': GREEN,
'3': BLUE,
'4': RED,
'5': '%s',
'6': YELLOW,
'7': GREY,
'8': GREY,
'9': BLUE,
'a': PUKE,
'b': BLUE,
'c': ORANGE,
'd': '%s',
'e': YELLOW,
'f': WHITE,
'k': lambda s: '*' * len(s),
'l': '**%s**',
'm': '~%s~',
'n': '__%s__',
'o': '*%s*',
'r': '%s'
}
#§
def minecraft_to_discord(minecraft):
minecraft = '§r' + minecraft
def f(match):
code = match.group(1)
format = formatting_codes[code]
if isinstance(format, str):
return format % match.group(0)
elif isinstance(format, tuple):
return colorize(format, match.group(0))
elif callable(format):
return format(match.group(0))
return re.sub('§(.).*?', f, minecraft)
def optimizer(opt_goal, player, weapon_damage, base_str, base_cc, base_cd):
best = 0
best_route = []
best_str = 0
best_cc = 0
best_cd = 0
stat_modifiers = player.stat_modifiers()
str_mod = stat_modifiers.get('strength', lambda x: x)
cc_mod = stat_modifiers.get('crit chance', lambda x: x)
cd_mod = stat_modifiers.get('crit damage', lambda x, y: x)
counts = player.talisman_counts()
if opt_goal == 1 or cc_mod(base_cc) > 100:
for c, u, r, e, l in itertools.product(
*[Route.routes(counts[key], 4, rarity_num) for rarity_num, key in enumerate(counts.keys())]):
strength = str_mod(base_str + c.strength + u.strength + r.strength + e.strength + l.strength)
crit_damage = cd_mod(
base_cd + c.crit_damage + u.crit_damage + r.crit_damage + e.crit_damage + l.crit_damage, strength)
d = (5 + weapon_damage + strength // 5) * (1 + strength / 100) * (1 + crit_damage / 100)
if d > best:
best = d
best_route = [c, u, r, e, l]
best_str = strength
best_cc = cc_mod(
base_cc + c.crit_chance + u.crit_chance + r.crit_chance + e.crit_chance + l.crit_chance)
best_cd = crit_damage
else:
cc_mod = stat_modifiers.get('crit chance', None)
if cc_mod:
for c, u, r, e, l in itertools.product(
*[Route.routes(counts[key], 4, rarity_num) for rarity_num, key in enumerate(counts.keys())]):
crit_chance = cc_mod(
base_cc + c.crit_chance + u.crit_chance + r.crit_chance + e.crit_chance + l.crit_chance) // 1
if crit_chance >= 100:
strength = str_mod(base_str + c.strength + u.strength + r.strength + e.strength + l.strength)
crit_damage = cd_mod(
base_cd + c.crit_damage + u.crit_damage + r.crit_damage + e.crit_damage + l.crit_damage,
strength)
d = (5 + weapon_damage + strength // 5) * (1 + strength / 100) * (1 + crit_damage / 100)
if d > best:
best = d
best_route = [c, u, r, e, l]
best_str = strength
best_cc = crit_chance
best_cd = crit_damage
else:
for c, u, r, e, l in itertools.product(
*[Route.routes(counts[key], 4, rarity_num) for rarity_num, key in enumerate(counts.keys())]):
crit_chance = base_cc + c.crit_chance + u.crit_chance + r.crit_chance + e.crit_chance + l.crit_chance
if crit_chance >= 100:
strength = str_mod(base_str + c.strength + u.strength + r.strength + e.strength + l.strength)
crit_damage = cd_mod(
base_cd + c.crit_damage + u.crit_damage + r.crit_damage + e.crit_damage + l.crit_damage,
strength)
d = (5 + weapon_damage + strength // 5) * (1 + strength / 100) * (1 + crit_damage / 100)
if d > best:
best = d
best_route = [c, u, r, e, l]
best_str = strength
best_cc = crit_chance
best_cd = crit_damage
return best, best_route, best_str, best_cc, best_cd
class Route:
def __init__(self, talismans, rarity):
self.strength, self.crit_chance, self.crit_damage = [
sum(reforges_list[y][rarity][x] * talismans[y]
for y in range(len(reforges_list)) if reforges_list[y][rarity])
for x in range(3)
]
self.counts = talismans
self.rarity = rarity
self.rarity_str = ["common", "uncommon", "rare", "epic", "legendary"][self.rarity]
def __str__(self):
return ' ߸ '.join(f'{c} '
f'{"godly/zealous" if self.rarity < 2 and name == "godly" else name} '
f'{Route.rarity_grammar(self.rarity_str, c)}'
for name, c in zip(RELEVANT_REFORGES.keys(), self.counts) if c != 0)
@staticmethod
def routes(count, size, rarity):
def helper(count, idx, current):
if count == 0:
yield Route(current, rarity)
elif idx == size - 1:
new = current.copy()
new[idx] += count
yield Route(new, rarity)
else:
if reforges_list[idx][rarity]:
new = current.copy()
new[idx] += 1
for x in helper(count - 1, idx, new):
yield x
for x in helper(count, idx + 1, current):
yield x
return helper(count, 0, [0] * size)
@staticmethod
def rarity_grammar(rarity, count=0):
if count == 1:
return rarity
return f'{rarity[:-1]}ies' if rarity[-1] == 'y' else f'{rarity}s'
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
lst = list(lst)
for i in range(0, len(lst), n):
yield lst[i:i + n]
'''
'skill events': {
'emoji': '😎',
'desc': 'Useful for guilds. Records the amount of skill experience gained by each player in a week. Raise your averages!',
'commands': {
'start event': {
'security': 1,
'function': self.start_event,
'desc': 'Starts a skyblock event',
'session': True
},
'view leaderboard': {
'function': self.view_lb,
'desc': 'Displays the leaderboard for the current event'
},
'end event': {
'security': 1,
'function': self.end_event,
'desc': 'Ends the current event and displays the winners'
}
}
},
'''
class Bot(discord.Client):
def __init__(self, *args, **kwargs):
self.callables = {}
self.commands = {
'bot': {
'emoji': '🤖',
'desc': 'View bot stats, visit the support server, and other status commands',
'commands': {
'stats': {
'function': self.stats,
'desc': 'Displays stats about the bot including number of servers and users'
},
'help': {
'function': self.help,
'desc': 'Opens the menu that you are looking at now'
},
'support': {
'function': self.support_server,
'desc': 'Have an question about the bot? Use this command'
}
}
},
'internet': {
'emoji': '🌐',
'desc': 'Surf the world wide web! Check the forums, manage guild applications, view the skyblock wiki, and more',
'commands': {
'news': {
'function': self.view_trending,
'desc': f'Displays the top three Skyblock threads from the past {trending_timeout} hours'
}
}
},
'damage': {
'emoji': '💪',
'desc': 'A collection of tools designed to optimize your damage and talismans',
'commands': {
'optimizer': {
'function': self.optimize_talismans,
'desc': 'Optimizes your talismans to their best reforges',
'session': True
},
'missing': {
'args': '[username] (profile)',
'function': self.view_missing_talismans,
'desc': 'Displays a list of your missing talismans. Also displays inactive/unnecessary talismans if you have them'
},
'damage': {
'function': self.calculate_damage,
'desc': 'Calcuates damage based on hypothetical stat values. This is not the talisman optimizer',
'session': True
}
}
},
'spy': {
'emoji': '🕵️♂️',
'desc': 'View stats and leaderboards for both guilds and players. Most functions work without API settings enabled',
'commands': {
'player': {
'args': '[username] (profile)',
'function': self.player,
'desc': 'Displays a player\'s guild, skills, and slayer levels'
},
'guild': {
'args': '[name]',
'function': self.guild,
'desc': 'Displays skill averages for a guild, aswell as leaderboards for all their players'
},
'royalty': {
'function': self.royalty,
'desc': 'Shows the top 30 guilds and players for every skill and slayer'
},
'pets': {
'args': '[username] (profile)',
'function': self.pets,
'desc': 'Shows all of a player\'s pets and their pet levels'
}
}
},
'auctions': {
'emoji': '💸',
'desc': 'View average prices for items aswell as past auctions for any player. Powered by https://hypixel-skyblock.com',
'commands': {
'price': {
'args': '[itemname] (stacksize)',
'function': self.price,
'desc': 'Displays the average price for any item'
},
'buys': {
'args': '[username]',
'function': self.buys,
'desc': 'Displays all past purchases for any player'
},
'sells': {
'args': '[username]',
'function': self.sells,
'desc': 'Displays all past purchases for any player'
},
'current': {
'args': '[username]',
'function': self.current_auctions,
'desc': 'Displays all current auctions'
}
}
}
}
self.hot_channels = {}
self.ready = False
self.args_message = '`[] signifies a required argument, while () signifies an optional argument`'
super().__init__(*args, **kwargs)
async def log(self, *args):
print(*args, sep='')
async def on_error(self, *args, **kwargs):
error = traceback.format_exc().replace('```', '"""')
await self.get_user(270352691924959243).send(f'```python\n{error}```')
print(error)
async def on_ready(self):
await self.log(f'Logged on as {self.user}!')
for data in self.commands.values():
self.callables.update(data['commands'])
await self.change_presence(activity=discord.Game('| 🍤 sbs help'))
self.ready = True
async def on_message(self, message):
if self.ready is False:
return
user = message.author
if user.bot:
return
channel = message.channel
dm = channel == user.dm_channel
if channel in self.hot_channels and self.hot_channels[channel] == user:
return
command = message.content.replace('!', '', 1)
if command == self.user.mention:
await self.help(message)
return
command = re.split('\s+', command)
command[0] = command[0].lower()
if command[0] == self.user.mention or command[0].lower() == 'sbs':
command = command[1:]
elif not dm:
return
if not command:
return
name = command[0].lower()
args = command[1:]
if name not in self.callables:
return
'''
whitelisted_servers = [int(server) for server in os.getenv('SERVERS').split()]
if not dm and not channel.guild.id in whitelisted_servers and len(channel.guild.members) > 50:
await Embed(
channel,
user=user,
title='Donate 20$ to my PayPal to use Skyblock Simplified on this server',
description='https://www.paypal.com/pools/c/8mstSPhQNO'
).set_footer(
text='Free for servers under 50 members'
).send()
await self.log('Paywal enforced in server {guild.name}')
return
'''
data = self.callables[name]
security = data['security'] if 'security' in data else 0
session = 'session' in data and data['session']
function = data['function']
if session and channel in self.hot_channels:
await channel.send(
f'{user.mention} someone else is currently using me in this channel! Try sending me a DM with your command instead')
return
if security == 1 and not channel.permissions_for(user).administrator:
await channel.send(
f'{user.mention} you do not have permission to use this command here! Try using it on your own discord server')
return
error = Embed(
channel,
user=user,
title='Error!'
).add_field(
name=None,
value='Something terrible happened while running your command\n'
'The error has been automatically reported to SBS devs'
)
await self.log(f'{user.name} used {name} {args} in {"a DM" if dm else channel.guild.name}')
if session:
self.hot_channels[channel] = user
try:
await function(message, *args)
except Exception as e:
error.send()
self.hot_channels.pop(channel)
raise e from None
self.hot_channels.pop(channel)
else:
try:
await function(message, *args)
except Exception as e:
error.send()
raise e from None
async def args_to_player(self, user, channel, *args):
try:
player = await skypy.Player(keys, uname=args[0], guild=True)
except (skypy.BadNameError, skypy.NeverPlayedSkyblockError):
await channel.send(f'{user.mention} invalid username!')
return None
except skypy.ExternalAPIError as e:
await channel.send(f'{user.mention} {e.reason}')
return None
if len(args) == 1:
await player.set_profile_automatically()
else:
try:
await player.set_profile(player.profiles[args[1].capitalize()])
except KeyError:
await channel.send(f'{user.mention} invalid profile!')
return None
#await update_top_players(player)
return player
async def no_args(self, command, user, channel):
data = self.callables[command]
usage = f'sbs {command} {data["args"]}' if 'args' in data else command
await Embed(
channel,
user=user,
title='This command requires arguments!',
description=f'Correct usage is `{usage}`\n{self.args_message}'
).send()
async def current_auctions(self, message, *args):
user = message.author
channel = message.channel
if not args:
await self.no_args('current', user, channel)
return
player = await self.args_to_player(user, channel, *args)
if player is None:
return
auctions = await player.auctions()
if not auctions:
await Embed(channel, user=user, title='no auctions found').send()
async def pages(page_num):
target = auctions[page_num]
item = target['item']
embed = Embed(
channel,
user=user,
title=item.name
).add_field(
name=None,
value=minecraft_to_discord(item.description)
)
return embed, page_num == len(auctions) - 1
await self.book(user, channel, pages)
async def royalty(self, message, *args):
global db
lb = db.leaderboards
user = message.author
channel = message.channel
menu = {emoji: name for name, (emoji, _, _) in LEADERBOARDS.items()}
current = 'Skill Average'
while True:
emoji, function, optional_function = LEADERBOARDS[current.lower()]
embed = Embed(
channel,
user=user,
title=f'{current} Leaderboard',
description=None
)
players = []
cursor = lb.find().sort(current, -1).limit(30)
i = 0
if optional_function:
for d in await cursor.to_list(length=None):
players.append(f'#{str(i + 1).ljust(2)} {d["name"]} [{round(d[current + "_"], 3)}] [{round(d[current], 3)}]')
i += 1
else:
for d in await cursor.to_list(length=None):
players.append(f'#{str(i + 1).ljust(2)} {d["name"]} [{round(d[current], 3)}]')
i += 1
portion = len(players) / 30
sections = [0, 1, 4, 9, 15, 22, 30]
peppers = random.choice(RANKS)
meal = {}
for i, pepper in enumerate(peppers):
meal[pepper] = players[round(sections[i] * portion): round(sections[i + 1] * portion)]
for pepper, players in meal.items():
embed.add_field(
name=pepper,
value=('```css\n' + '\n'.join(players) + '```') if players else r'```¯\_(ツ)_/¯```',
inline=False
)
msg = await embed.send()
current = (await self.reaction_menu(msg, user, menu)).title()
if current is None:
break
await msg.delete()
async def price(self, message, *args):
user = message.author
channel = message.channel
if not args:
await self.no_args('price', user, channel)
return
if len(args) > 1 and args[-1].isdigit():
if len(args[-1]) > 20:
await channel.send(f'In what world would you need {args[-1]} of that???')
return
stacksize = int(args[-1])
itemname = ' '.join(args[:-1]).title()
else:
stacksize = None
itemname = ' '.join(args).title()
query = 'query ItemsList($page: Int, $items: Int, $name: String) { itemList(page: $page, items: $items, name: $name) { page item { name }}}'
r = await craftlink(user, channel, query, operation='ItemsList', name=itemname, items=1, page=1)
if r is None:
return
r = r['itemList']['item']
if not r:
await channel.send(f'{user.mention} invalid itemname')
return
itemname = r[0]['name']
query = 'query Item($name: String) { item(name: $name) { sales { end price } recent { id seller itemData { quantity lore } bids { bidder timestamp amount } highestBidAmount end } }}'
r = await craftlink(user, channel, query, operation='Item', name=itemname)
if r is None:
return
r = r['item']
sales = r['sales']
if stacksize is None:
if r['recent']:
stacksize = 64 if max([int(auction['itemData']['quantity']) for auction in r['recent']]) > 32 else 1
else:
stacksize = 1
auctions = [float(item['price']) * stacksize for item in sales]
size = len(auctions)
if size == 0:
await channel.send(f'{user.mention} there haven\'t been any `{itemname}` sold recently')
return
small, big = min(auctions), max(auctions)
mid = median(auctions)
lower, upper = mid / 10, mid * 10
steals = [a for a in auctions if lower >= a]
auctions = [a for a in auctions if lower < a < upper]
mid = median(auctions)
avg = mean(auctions)
common = mode(auctions)
std = pstdev(auctions, mu=avg)
await Embed(
channel,
user=user,
title=f'{itemname} (x{stacksize})',
description='Powered by https://hypixel-skyblock.com'
).add_field(
name=None,
value=f'```Average: {avg:,.0f}\nMedian: {mid:,.0f}\nMode: {common:,.0f}\nStandard Deviation: {std:,.0f}\nMin: {math.ceil(small):,}\nMax: {math.ceil(big):,}```'
f'```There were {len(steals)} steals and {size} total sales```'
).set_footer(
text='Statistics are from the last 1500 items sold if possible\nPrices ignored if they are 10 times larger or smaller than the average'
).send()
async def sells(self, message, *args):
page_size = 12
user = message.author