forked from notnotmelon/skyblock-simplified
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
1354 lines (1133 loc) · 40.8 KB
/
bot.py
File metadata and controls
1354 lines (1133 loc) · 40.8 KB
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 os
import discord
import skypy
import skypy_constants
from bs4 import BeautifulSoup
import requests
import asyncio
import math
import traceback
import itertools
from datetime import datetime, timezone
time_format = '%m/%d %I:%M %p UTC'
import re
import random
from sortedcollections import ValueSortedDict
from statistics import mean, median, pstdev, StatisticsError
if os.environ.get('API_KEY') is None:
import dotenv
dotenv.load_dotenv()
keys = os.getenv('API_KEY').split()
damaging_potions = [
{
'name': 'critical',
'stats': {
'crit chance': [0, 10, 15, 20, 25],
'crit damage': [0, 10, 20, 30, 40]
}
},
{
'name': 'strength',
'stats': {'strength': [0, 5.25, 13.125, 21, 31.5, 42, 52.5, 63, 78.75]} # Assume cola
},
{
'name': 'spirit',
'stats': {'crit damage': [0, 10, 20, 30, 40]}
},
{
'name': 'archery',
'stats': {'enchantment modifier': [0, 17.5, 30, 55, 80]}
}
]
# 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_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
}
cheapo_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'
]
}
relavant_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': (None, None, (4, 2, 3), (7, 3, 6), (10, 5, 8))
}
reforges_list = list(relavant_reforges.values())
# Forums parsing ---
trending_threads = []
last_forums_update = [datetime.now()]
num_trending = 3
trending_timeout = 24
trending_algorithm = lambda thread: (thread['views'] + thread['likes'] * 200) / math.sqrt(thread['date'] / 1000 + 1)
async def update_trending(trending_threads, last_forums_update):
class Timeout(Exception):
pass
class Nothing(Exception):
pass
while True:
pagenumber = 1
now = None
backup = trending_threads.copy()
trending_threads.clear()
s = requests.session()
try:
while True:
await client.log(f'Attempting to parse forums page {pagenumber}')
soup = BeautifulSoup(
s.get(f'https://hypixel.net/forums/skyblock.157/page-{pagenumber}?order=post_date').content,
'html.parser',
multi_valued_attributes=None
)
posts = soup.find_all(class_='discussionListItem visible ')
if not posts:
raise Nothing
for post in posts:
thread = {}
header = post.find('h3').a
thread['link'] = f'https://hypixel.net/{header["href"]}'
thread['name'] = header.string
info = post.find(class_='listBlock stats pairsJustified')
thread['likes'] = int(info['title'].replace('Members who liked the first message: ', ''))
thread['views'] = int(info.find(class_='minor').dd.string.replace(',', ''))
thread['replies'] = int(info.find(class_='major').dd.string.replace(',', ''))
thread['date'] = int(post.find(class_='posterDate muted').find('abbr')['data-time'])
if now is None:
now = thread['date']
thread['date'] = now - thread['date']
if thread['date'] >= trending_timeout * 3600:
raise Timeout
if discord.utils.find(lambda t: thread['link'] == t['link'], trending_threads) is None:
trending_threads.append(thread)
trending_threads.sort(key=trending_algorithm, reverse=True)
del trending_threads[num_trending:]
pagenumber += 1
except Timeout:
now = datetime.now(timezone.utc)
last_forums_update[0] = now
await client.log(
f'Trending threads updated at {now.strftime(time_format)}. {pagenumber} pages parsed\n',
'\n'.join([thread['link'] for thread in trending_threads])
)
except (Nothing, RuntimeError):
now = datetime.now(timezone.utc)
await client.log(f'Failed to parse forums at {now.strftime(time_format)}')
trending_threads = backup
await asyncio.sleep(3600 * 2)
# ! -------------- !
def chunks(lst, n):
lst = list(lst)
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
guild_cache = {}
async def clear_cache(guild_cache):
while True:
await asyncio.sleep(60 * 60 * 24)
guild_cache.clear()
await client.log(f'Guild cache cleared at {datetime.now(timezone.utc).strftime(time_format)}')
class Embed(discord.Embed):
nbst = '\u200b'
def __init__(self, channel, *, title, **kwargs):
self.channel = channel
if 'description' in kwargs:
kwargs['description'] = kwargs['description'] or self.nbst
super().__init__(title=title or self.nbst, color=self.color(channel), **kwargs)
def color(self, 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(embed=self)
discord.Embed = None
leaderboards = {
'Skill Average': ('📈', lambda player: player.skill_average, None, lambda guild: guild.stat_average('skill_average'), None),
'Minion Slots': ('⛓', lambda player: player.unique_minions, lambda player: player.minion_slots, lambda guild: guild.stat_average('unique_minions'), lambda guild: guild.stat_average('minion_slots')),
'Farming': ('🌾', lambda player: player.skill_experience['farming'], lambda player: player.skills['farming'], lambda guild: guild.stat_average('skill_experience')['farming'], lambda guild: guild.stat_average('skills')['farming']),
'Mining': ('⛏', lambda player: player.skill_experience['mining'], lambda player: player.skills['mining'], lambda guild: guild.stat_average('skill_experience')['mining'], lambda guild: guild.stat_average('skills')['mining']),
'Combat': ('⚔', lambda player: player.skill_experience['combat'], lambda player: player.skills['combat'], lambda guild: guild.stat_average('skill_experience')['combat'], lambda guild: guild.stat_average('skills')['combat']),
'Foraging': ('🪓', lambda player: player.skill_experience['foraging'], lambda player: player.skills['foraging'], lambda guild: guild.stat_average('skill_experience')['foraging'], lambda guild: guild.stat_average('skills')['foraging']),
'Enchanting': ('📖', lambda player: player.skill_experience['enchanting'], lambda player: player.skills['enchanting'], lambda guild: guild.stat_average('skill_experience')['enchanting'], lambda guild: guild.stat_average('skills')['enchanting']),
'Alchemy': ('⚗', lambda player: player.skill_experience['alchemy'], lambda player: player.skills['alchemy'], lambda guild: guild.stat_average('skill_experience')['alchemy'], lambda guild: guild.stat_average('skills')['alchemy']),
'Fishing': ('🎣', lambda player: player.skill_experience['fishing'], lambda player: player.skills['fishing'], lambda guild: guild.stat_average('skill_experience')['carpentry'], lambda guild: guild.stat_average('skills')['carpentry']),
'Carpentry': ('🪑', lambda player: player.skill_experience['carpentry'], lambda player: player.skills['carpentry'], lambda guild: guild.stat_average('skill_experience')['farming'], lambda guild: guild.stat_average('skills')['farming']),
'Runecrafting': ('⚜️', lambda player: player.skill_experience['runecrafting'], lambda player: player.skills['runecrafting'], lambda guild: guild.stat_average('skill_experience')['runecrafting'], lambda guild: guild.stat_average('skills')['runecrafting']),
'Zombie': ('🧟', lambda player: player.slayer_exp['zombie'], lambda player: player.slayer_levels['zombie'], lambda guild: guild.stat_average('slayer_exp')['zombie'], lambda guild: guild.stat_average('slayer_levels')['zombie']),
'Spider': ('🕸️', lambda player: player.slayer_exp['spider'], lambda player: player.slayer_levels['spider'], lambda guild: guild.stat_average('slayer_exp')['spider'], lambda guild: guild.stat_average('slayer_levels')['spider']),
'Wolf': ('🐺', lambda player: player.slayer_exp['wolf'], lambda player: player.slayer_levels['wolf'], lambda guild: guild.stat_average('slayer_exp')['wolf'], lambda guild: guild.stat_average('slayer_levels')['wolf'])
}
levels = {
name: leaderboards[name] for name in
['Farming', 'Mining', 'Combat', 'Foraging', 'Enchanting', 'Alchemy', 'Fishing', 'Carpentry', 'Runecrafting', 'Zombie', 'Spider', 'Wolf']
}
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']
]
top_players = {name: ValueSortedDict(lambda player_tuple: -player_tuple[1]) for name in leaderboards.keys()}
def update_top_players(player):
for skill, players in top_players.items():
lb = leaderboards[skill]
own = lb[1](player)
if lb[2]:
players[player.uuid] = (player.uname, own, lb[2](player))
else:
players[player.uuid] = (player.uname, own)
close_message = '\n> _use **exit** to close the session_'
args_message = '`[] signifies a required argument, while () signifies an optional argument`'
whitelisted_servers = [int(server) for server in os.getenv('SERVERS').split()]
class Bot(discord.Client):
def __init__(self, *args, **kwargs):
self.hot_channels = {}
self.ready = False
super().__init__(*args, **kwargs)
async def log(self, *args):
print(*args, sep='')
async def on_ready(self):
await self.log(f'Logged on as {self.user}!')
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': {
'function': self.view_missing_talismans,
'desc': 'Displays a list of missing talismans',
'session': True
},
'useless': {
'function': self.view_unnecessary_talismans,
'desc': 'Displays a list your overlapping talismans',
'session': True
},
'damage': {
'function': self.calculate_damage,
'desc': 'Calcuates damage based on hypothetical stat values',
'session': True
}
}
},
'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'
}
}
},
'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'
}
}
},
'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]',
'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] (stacksize)',
'function': self.sells,
'desc': 'Displays all past purchases for any player'
}
}
}
}
self.callables = {}
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_error(self, event, *args, **kwargs):
traceback.print_exc()
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.lower().replace('!', '', 1)
if command == self.user.mention:
await self.help(message)
return
command = re.split('\s+', command)
if command[0] == self.user.mention or command[0] == 'sbs':
command = command[1:]
elif not dm:
return
if not command:
return
name = command[0]
args = command[1:]
if name not in self.callables:
return
if not dm and not channel.guild.id in whitelisted_servers:
await Embed(
channel,
title='Donate 20$ to my PayPal to use Skyblock Simplified on this server',
description='https://www.paypal.com/pools/c/8mstSPhQNO'
).send()
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
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 discord.errors.Forbidden:
await channel.send(f'{user.mention} your DM\'s are disabled')
self.hot_channels.pop(channel)
else:
await function(message, *args)
async def no_args(self, command, user, channel):
data = self.callables[command]
usage = f'{command} {data["args"]}' if 'args' in data else command
await Embed(
channel,
title='This command requires arguments!',
description=f'Correct usage is `{usage}`\n{args_message}'
).send()
async def royalty(self, message, *args):
user = message.author
channel = message.channel
menu = {}
for name, (emoji, function, optional_function, _, _) in leaderboards.items():
lb = Embed(
channel,
title=f'{name} Leaderboard',
description=None
)
players = []
top = top_players[name]
if optional_function:
for i in range(min(50, len(top))):
uuid, (name, data, optional) = top.peekitem(i)
players.append(f'#{str(i + 1).ljust(2)} {name} [{round(optional, 3)}] [{round(data, 3):,}]')
else:
for i in range(min(50, len(top))):
uuid, (name, data) = top.peekitem(i)
players.append(f'#{str(i + 1).ljust(2)} {name} [{round(data, 3):,}]')
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():
lb.add_field(
name=pepper,
value=('```css\n' + '\n'.join(players) + '```') if players else '```¯\_(ツ)_/¯```',
inline=False
)
menu[emoji] = lb
embed = menu['📈']
while True:
msg = await embed.send()
embed = await self.reaction_menu(msg, user, menu)
if embed is None:
break
await msg.delete()
def craftlink(self, query, *, operation, **kwargs):
json = {
'operationName': operation,
'variables': dict(kwargs),
'query': query
}
r = requests.post(f'https://craftlink.xyz/graphql', json=json)
r.raise_for_status()
r = r.json()
return r['data']
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():
stacksize = int(args[-1])
itemname = ' '.join(args[:-1]).title()
else:
stacksize = 1
itemname = ' '.join(args).title()
query = 'query ItemsList($page: Int, $items: Int, $name: String) { itemList(page: $page, items: $items, name: $name) { page item { name }}}'
r = self.craftlink(query, operation='ItemsList', name=itemname, items=1, page=1)['itemList']['item']
if len(r) == 0:
await channel.send(f'{user.mention} invalid itemname')
itemname = r[0]['name']
query = 'query Item($name: String) { item(name: $name) { sales { price } } }'
r = self.craftlink(query, operation='Item', name=itemname)['item']['sales']
auctions = [float(item['price']) * stacksize for item in r]
size = len(auctions)
avg = mean(auctions)
std = pstdev(auctions, mu=avg)
cutoff = std * 2
lower, upper = avg - cutoff, avg + cutoff
steals = [a for a in auctions if a < lower]
auctions = [a for a in auctions if lower < a < upper]
try:
avg = mean(auctions)
mid = median(auctions)
std = pstdev(auctions, mu=avg)
except StatisticsError:
await channel.send(f'{user.mention} there haven\'t been any `{itemname}` sold recently')
return
await Embed(
channel,
title=f'{itemname} (x{stacksize})',
description='Powered by https://hypixel-skyblock.com'
).add_field(
name=None,
value=f'```Average: {round(avg):,}\nMedian: {round(mid):,}\nStandard Deviation: {round(std):,}```'
f'```There were {len(steals)} steals and {size} total sales```'
).set_footer(
text='Statistics are from the last 1500 items sold\nPrices are ignored unless they are within 2 standard deviations'
).send()
async def sells(self, message, *args):
page_size = 12
user = message.author
channel = message.channel
if not args:
await self.no_args('sells', user, channel)
return
name = args[0]
try:
uuid = await skypy.get_uuid(name)
except skypy.BadNameError:
await channel.send(f'{user.mention} invalid username!')
return
async def pages(page_num):
query = 'query UserHistory($id: String, $type: String, $limit: Int, $skip: Int) { userHistory(id: $id, type: $type, limit: $limit, skip: $skip) { auctions { id seller itemData { texture id name tag quantity lore __typename } bids { bidder timestamp amount __typename } highestBidAmount end __typename } __typename } }'
r = self.craftlink(query, operation='UserHistory', id=uuid, limit=page_size, skip=page_num * page_size, type='auctions')['userHistory']['auctions']
if len(r) < page_size:
last_page = True
else:
last_page = False
embed = Embed(
channel,
title=f'Past Auctions From {name}',
description=f'Page {page_num + 1} | Powered by https://hypixel-skyblock.com'
)
if r:
for auction in r:
buyer = await skypy.get_uname(auction['bids'][0]['bidder'])
item = auction['itemData']
embed.add_field(
name = f'{item["quantity"]}x {item["name"].upper()}',
value = f'```diff\n! {int(auction["highestBidAmount"]):,} coins\n'
f'-sold to {buyer}\n'
f'{datetime.fromtimestamp(int(auction["end"]) // 1000).strftime(time_format)}```'
)
else:
embed.add_field(name=None, value='```¯\_(ツ)_/¯```')
return (embed, last_page)
await self.book(user, channel, pages)
async def buys(self, message, *args):
page_size = 12
user = message.author
channel = message.channel
if not args:
await self.no_args('buys', user, channel)
return
name = args[0]
try:
uuid = await skypy.get_uuid(name)
except skypy.BadNameError:
await channel.send(f'{user.mention} invalid username!')
async def pages(page_num):
query = 'query UserHistory($id: String, $type: String, $limit: Int, $skip: Int) {userHistory(id: $id, type: $type, limit: $limit, skip: $skip) {auctions {id seller itemData {texture id name tag quantity lore __typename} bids {bidder timestamp amount __typename} highestBidAmount end __typename} __typename}}'
r = self.craftlink(query, operation='UserHistory', id=uuid, limit=page_size, skip=page_num * page_size, type='purchases')['userHistory']['auctions']
if len(r) < page_size:
last_page = True
else:
last_page = False
embed = Embed(
channel,
title=f'Past Purchases From {name}',
description=f'Page {page_num + 1} | Powered by https://hypixel-skyblock.com'
)
if r:
for auction in r:
item = auction['itemData']
embed.add_field(
name = f'{item["quantity"]}x {item["name"].upper()}',
value = f'```diff\n! {int(auction["highestBidAmount"]):,} coins\n'
f'-by {await skypy.get_uname(auction["seller"])}\n'
f'{datetime.fromtimestamp(int(auction["end"]) // 1000).strftime(time_format)}```'
)
else:
embed.add_field(name=None, value='```¯\_(ツ)_/¯```')
return (embed, last_page)
await self.book(user, channel, pages)
async def player(self, message, *args):
user = message.author
channel = message.channel
if not args:
await self.no_args('player', user, channel)
return
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
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
update_top_players(player)
embed = Embed(
channel,
title=f'{player.uname} | {player.profile_name}',
description='```' + ' '.join([f'{k.capitalize()} {"✅" if v else "❌"}' for k, v in player.enabled_api.items()]) + '```\n'
f'```Skill Average > {round(player.skill_average, 2)}\n'
f'Deaths > {player.deaths}\n'
f'Guild > {player.guild}\n'
f'Money > {round(player.bank_balance + player.purse):,}\n'
f'Slots > {player.minion_slots} ({player.unique_minions} crafts)```'
).set_thumbnail(
url=player.skin()
)
for name, (emoji, function, optional_function, _, _) in levels.items():
embed.add_field(
name=f'{emoji}\t{name}',
value=f'```Level > {optional_function(player)}\nxp: {function(player):,}```'
)
await embed.send()
async def guild(self, message, *args):
user = message.author
channel = message.channel
if not args:
await self.no_args('guild', user, channel)
return
args = ' '.join(args).lower()
if args in guild_cache:
guild = guild_cache[args]
else:
try:
guild = await skypy.Guild(keys, gname=args)
guild_cache[args] = guild
except skypy.BadNameError:
await channel.send(f'{user.mention} invalid guild!')
return
for player in guild:
update_top_players(player)
embed = Embed(
channel,
title=f'{guild.gname} | {guild.tag}' if guild.tag else guild.gname,
description=f'```Skill Average > {round(guild.stat_average("skill_average"), 3)}\n'
f'Players > {len(guild)}\n'
f'Level > {guild.level}\n'
f'Deaths > {guild.deaths:,}\n'
f'Average Money > {round((guild.bank_balance + guild.purse) / len(guild)):,}\n'
f'Slots > {round(guild.stat_average("minion_slots"), 3)} ({round(guild.stat_average("unique_minions"))} crafts)```'
)
for name, (emoji, _, _, function, optional_function) in levels.items():
embed.add_field(
name=f'{emoji}\t{name}',
value=f'```Level > {round(optional_function(guild), 3)}\nxp: {round(function(guild)):,}```'
)
menu = {}
prompt = {}
for name, (emoji, function, optional_function, _, _) in leaderboards.items():
lb = Embed(
channel,
title=f'{guild.gname} {name} Leaderboard'
)
if optional_function:
players = [(player, function(player), optional_function(player)) for player in guild.players]
else:
players = [(player, function(player)) for player in guild.players]
players.sort(key=lambda tuple: tuple[1], reverse=True)
if optional_function:
players = [f'#{str(index + 1).ljust(2)} {player.uname} [{round(optional_stat, 2)}] [{round(stat, 2):,}]'
for index, (player, stat, optional_stat) in enumerate(players)]
else:
players = [f'#{str(index + 1).ljust(2)} {player.uname} [{round(stat, 2):,}]'
for index, (player, stat) in enumerate(players)]
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():
lb.add_field(
name=pepper,
value=('```css\n' + "\n".join(players) + '```') if players else '```¯\_(ツ)_/¯```',
inline=False
)
prompt[emoji] = name
menu[emoji] = lb
reaction_prompt = '**React to this message for guild leaderboards**```'
for group in chunks(prompt.items(), 4):
reaction_prompt += f'{" | ".join([" ".join(g) for g in group])}\n'
reaction_prompt += '```'
embed.add_field(
name=None,
value=reaction_prompt,
inline=False
)
while True:
msg = await embed.send()
lb = await self.reaction_menu(msg, user, menu)
if lb:
await msg.delete()
msg = await lb.send()
if await self.back(msg, user):
await msg.delete()
else:
break
else:
break
async def optimize_talismans(self, message, *args):
await self.unimplemented(message)
async def unimplemented(self, message):
await message.channel.send(f'{message.author.mention} this command is unimplemented')
async def view_trending(self, message, *args):
embed = Embed(
message.channel,
title='Trending Threads',
description=f'It\'s the talk of the town! Here\'s three popular threads from the past {trending_timeout} hours'
).set_footer(
text=f'Last updated {last_forums_update[0].strftime(time_format)}'
)
if trending_threads:
for thread in trending_threads:
embed.add_field(
name=f'**{thread["name"]}\n_{thread["views"]} views_ | _{thread["likes"]} likes_**',
value=f'[{thread["link"]}]'
)
else:
embed.add_field(
name=None,
value='Hypixel currently has their anti DDOS protection enabled. I can\'t get in!'
)
await embed.send()
async def calculate_damage(self, message, *args):
channel = message.channel
user = message.author
stats = {'strength': 0, 'crit damage': 0, 'weapon damage': 0, 'combat level': 0}
questions = {
'strength': f'{user.mention} how much **strength** do you want to have?',
'crit damage': f'{user.mention} how much **crit damage** do you want to have?',
'weapon damage': f'{user.mention} how much **damage** does your weapon have on the tooltip?',
'combat level': f'{user.mention} what is your **combat level**?'
}
for stat in stats.keys():
await channel.send(questions[stat])
resp = await self.respond(user, channel)
if resp is None:
return
if resp.content[0] == '+':
resp.content = resp.content[1:]
if resp.content.isdigit() is False or len(resp.content) > 20:
await channel.send(f'{user.mention} Invalid input!')
return
stats[stat] = int(resp.content)
mobs = '\n'.join([k.capitalize() for k in activities.keys()])
embed = Embed(
channel,
title='Which mob will you be targeting with this setup?'
).add_field(
name=None,
value=f'```{mobs}```',