-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
leveler.py
3634 lines (3241 loc) · 145 KB
/
leveler.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 asyncio
import logging
import math
import operator
import platform
import random
import re
import textwrap
import time
from asyncio import TimeoutError as AsyncTimeoutError
from collections import OrderedDict
from datetime import timedelta
from io import BytesIO
from typing import Union
import aiohttp
import discord
from discord.utils import find
from fontTools.ttLib import TTFont
from redbot.core import Config, bank, checks, commands
from redbot.core.bot import Red
from redbot.core.data_manager import bundled_data_path
from redbot.core.utils import AsyncIter
from redbot.core.utils.chat_formatting import box, pagify
from redbot.core.utils.menus import DEFAULT_CONTROLS, menu
from redbot.core.utils.predicates import MessagePredicate
from tabulate import tabulate
try:
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import errors as mongoerrors
except Exception as e:
raise RuntimeError(f"Can't load pymongo/motor:{e}\nInstall 'pymongo' and 'motor' packages")
try:
import numpy
from scipy import cluster
except Exception as e:
print(
f"{__file__}: numpy/scipy is unable to import: {e}\nAutocolor feature will be unavailable"
)
try:
from PIL import Image, ImageColor, ImageDraw, ImageFilter, ImageFont, ImageOps
from PIL import features as pil_features
except Exception as e:
raise RuntimeError(f"Can't load pillow: {e}\nDo '[p]pipinstall pillow'.")
log = logging.getLogger("red.fixator10-cogs.leveler")
AVATAR_FORMAT = "webp" if pil_features.check("webp_anim") else "jpg"
log.debug(f"using {AVATAR_FORMAT} avatar format")
# noinspection PyUnusedLocal
async def non_global_bank(ctx):
return not await bank.is_global()
class Leveler(commands.Cog):
"""A level up thing with image generation!"""
__version__ = "2.1.4b"
# noinspection PyMissingConstructor
def __init__(self, bot: Red):
self.bot = bot
# fonts
self.font_file = f"{bundled_data_path(self)}/font.ttf"
self.font_bold_file = f"{bundled_data_path(self)}/font_bold.ttf"
self.font_unicode_file = f"{bundled_data_path(self)}/unicode.ttf"
self.config = Config.get_conf(self, identifier=0x3AAFD05EA4AA4FDF8DDEAD8224328191)
default_mongodb = {
"host": "localhost",
"port": 27017,
"username": None,
"password": None,
"db_name": "leveler",
}
default_global = {
"bg_price": 0,
"badge_type": "circles",
"xp": [15, 20],
"message_length": 10,
"mention": True,
"backgrounds": {
"profile": {
"alice": "http://i.imgur.com/MUSuMao.png",
"abstract": "http://i.imgur.com/70ZH6LX.png",
"bluestairs": "http://i.imgur.com/EjuvxjT.png",
"lamp": "http://i.imgur.com/0nQSmKX.jpg",
"coastline": "http://i.imgur.com/XzUtY47.jpg",
"redblack": "http://i.imgur.com/74J2zZn.jpg",
"default": "http://i.imgur.com/8T1FUP5.jpg",
"iceberg": "http://i.imgur.com/8KowiMh.png",
"miraiglasses": "http://i.imgur.com/2Ak5VG3.png",
"miraikuriyama": "http://i.imgur.com/jQ4s4jj.png",
"mountaindawn": "http://i.imgur.com/kJ1yYY6.jpg",
"waterlilies": "http://i.imgur.com/qwdcJjI.jpg",
},
"rank": {
"aurora": "http://i.imgur.com/gVSbmYj.jpg",
"default": "http://i.imgur.com/SorwIrc.jpg",
"nebula": "http://i.imgur.com/V5zSCmO.jpg",
"mountain": "http://i.imgur.com/qYqEUYp.jpg",
"city": "http://i.imgur.com/yr2cUM9.jpg",
},
"levelup": {"default": "http://i.imgur.com/eEFfKqa.jpg"},
},
}
default_guild = {
"disabled": False,
"lvl_msg": False,
"text_only": False,
"private_lvl_message": False,
"lvl_msg_lock": None,
"msg_credits": 0,
"ignored_channels": [],
}
self.config.init_custom("MONGODB", -1)
self.config.register_custom("MONGODB", **default_mongodb)
self.config.register_global(**default_global)
self.config.register_guild(**default_guild)
self._db_ready = False
self.client = None
self.db = None
self.session = aiohttp.ClientSession(loop=self.bot.loop)
async def initialize(self):
await self._connect_to_mongo()
async def _connect_to_mongo(self):
if self._db_ready:
self._db_ready = False
self._disconnect_mongo()
config = await self.config.custom("MONGODB").all()
try:
self.client = AsyncIOMotorClient(
**{k: v for k, v in config.items() if not k == "db_name"}
)
await self.client.server_info()
self.db = self.client[config["db_name"]]
self._db_ready = True
except (
mongoerrors.ServerSelectionTimeoutError,
mongoerrors.ConfigurationError,
mongoerrors.OperationFailure,
) as error:
log.exception(
"Can't connect to the MongoDB server.\nFollow instructions on Git/online to install MongoDB.",
exc_info=error,
)
self.client = None
self.db = None
return self.client
def _disconnect_mongo(self):
if self.client:
self.client.close()
async def cog_check(self, ctx):
if (ctx.command.parent is self.levelerset) or ctx.command is self.levelerset:
return True
return self._db_ready
def cog_unload(self):
self.session.detach()
self._disconnect_mongo()
@commands.cooldown(1, 10, commands.BucketType.user)
@commands.command(name="profile")
@commands.guild_only()
async def profile(self, ctx, *, user: discord.Member = None):
"""Displays a user profile."""
if user is None:
user = ctx.message.author
if user.bot:
ctx.command.reset_cooldown(ctx)
await ctx.send_help()
return
channel = ctx.message.channel
server = user.guild
curr_time = time.time()
# creates user if doesn't exist
await self._create_user(user, server)
userinfo = await self.db.users.find_one({"user_id": str(user.id)})
# check if disabled
if await self.config.guild(ctx.guild).disabled():
await ctx.send("**Leveler commands for this server are disabled!**")
return
# no cooldown for text only
if await self.config.guild(ctx.guild).text_only():
em = await self.profile_text(user, server, userinfo)
await channel.send(embed=em)
else:
async with ctx.channel.typing():
profile = await self.draw_profile(user, server)
file = discord.File(profile, filename="profile.png")
await channel.send(
"**User profile for {}**".format(await self._is_mention(user)), file=file,
)
await self.db.users.update_one(
{"user_id": str(user.id)}, {"$set": {"profile_block": curr_time}}, upsert=True,
)
async def profile_text(self, user, server, userinfo):
em = discord.Embed(colour=user.colour)
em.add_field(name="Title:", value=userinfo["title"] or None)
em.add_field(name="Reps:", value=userinfo["rep"])
em.add_field(name="Global Rank:", value="#{}".format(await self._find_global_rank(user)))
em.add_field(
name="Server Rank:", value="#{}".format(await self._find_server_rank(user, server)),
)
em.add_field(
name="Server Level:", value=format(userinfo["servers"][str(server.id)]["level"]),
)
em.add_field(name="Total Exp:", value=userinfo["total_exp"])
em.add_field(name="Server Exp:", value=await self._find_server_exp(user, server))
u_credits = await bank.get_balance(user)
em.add_field(
name="Credits:", value=f"{u_credits}{(await bank.get_currency_name(server))[0]}",
)
em.add_field(name="Info:", value=userinfo["info"] or None)
em.add_field(
name="Badges:", value=(", ".join(userinfo["badges"]).replace("_", " ") or None),
)
em.set_author(name="Profile for {}".format(user.name), url=user.avatar_url)
em.set_thumbnail(url=user.avatar_url)
return em
@commands.cooldown(1, 10, commands.BucketType.user)
@commands.command()
@commands.guild_only()
async def rank(self, ctx, *, user: discord.Member = None):
"""Displays the rank of a user."""
if user is None:
user = ctx.message.author
if user.bot:
ctx.command.reset_cooldown(ctx)
await ctx.send_help()
return
channel = ctx.message.channel
server = user.guild
curr_time = time.time()
# creates user if doesn't exist
await self._create_user(user, server)
userinfo = await self.db.users.find_one({"user_id": str(user.id)})
# check if disabled
if await self.config.guild(ctx.guild).disabled():
await ctx.send("**Leveler commands for this server are disabled!**")
return
# no cooldown for text only
if await self.config.guild(server).text_only():
em = await self.rank_text(user, server, userinfo)
await channel.send(embed=em)
else:
async with channel.typing():
rank = await self.draw_rank(user, server)
file = discord.File(rank, filename="rank.png")
await channel.send(
"**Ranking & Statistics for {}**".format(await self._is_mention(user)),
file=file,
)
await self.db.users.update_one(
{"user_id": str(user.id)},
{"$set": {"rank_block".format(server.id): curr_time}},
upsert=True,
)
async def rank_text(self, user, server, userinfo):
em = discord.Embed(colour=user.colour)
em.add_field(
name="Server Rank", value="#{}".format(await self._find_server_rank(user, server)),
)
em.add_field(name="Reps", value=userinfo["rep"])
em.add_field(name="Server Level", value=userinfo["servers"][str(server.id)]["level"])
em.add_field(name="Server Exp", value=await self._find_server_exp(user, server))
em.set_author(name="Rank & Statistics for {}".format(user.name), url=user.avatar_url)
em.set_thumbnail(url=user.avatar_url)
return em
# should the user be mentioned based on settings?
async def _is_mention(self, user):
if await self.config.mention():
return user.mention
return user.name
@commands.command(usage="[page] [-rep] [-global]")
@commands.guild_only()
async def top(self, ctx, *options):
"""Displays leaderboard.
Add -global parameter for global and -rep for reputation."""
server = ctx.guild
user = ctx.author
if await self.config.guild(ctx.guild).disabled():
await ctx.send("**Leveler commands for this server are disabled!**")
return
async with ctx.typing():
users = []
user_stat = None
if "-rep" in options and "-global" in options:
title = "Global Rep Leaderboard for {}\n".format(self.bot.user.name)
async for userinfo in self.db.users.find({}):
try:
users.append((userinfo["username"], userinfo["rep"]))
except KeyError:
users.append((userinfo["user_id"], userinfo["rep"]))
if str(user.id) == userinfo["user_id"]:
user_stat = userinfo["rep"]
board_type = "Rep"
footer_text = "Your Rank: {} {}: {}".format(
await self._find_global_rep_rank(user), board_type, user_stat
)
icon_url = self.bot.user.avatar_url
elif "-global" in options:
title = "Global Exp Leaderboard for {}\n".format(self.bot.user.name)
async for userinfo in self.db.users.find({}):
try:
users.append((userinfo["username"], userinfo["total_exp"]))
except KeyError:
users.append((userinfo["user_id"], userinfo["total_exp"]))
if str(user.id) == userinfo["user_id"]:
user_stat = userinfo["total_exp"]
board_type = "Points"
footer_text = "Your Rank: {} {}: {}".format(
await self._find_global_rank(user), board_type, user_stat
)
icon_url = self.bot.user.avatar_url
elif "-rep" in options:
title = "Rep Leaderboard for {}\n".format(server.name)
async for userinfo in self.db.users.find({}):
if "servers" in userinfo and str(server.id) in userinfo["servers"]:
try:
users.append((userinfo["username"], userinfo["rep"]))
except KeyError:
users.append((userinfo["user_id"], userinfo["rep"]))
if str(user.id) == userinfo["user_id"]:
user_stat = userinfo["rep"]
board_type = "Rep"
footer_text = "Your Rank: {} {}: {}".format(
await self._find_server_rep_rank(user, server), board_type, user_stat,
)
icon_url = server.icon_url
else:
title = "Exp Leaderboard for {}\n".format(server.name)
async for userinfo in self.db.users.find({}):
try:
if "servers" in userinfo and str(server.id) in userinfo["servers"]:
server_exp = 0
for i in range(userinfo["servers"][str(server.id)]["level"]):
server_exp += await self._required_exp(i)
server_exp += userinfo["servers"][str(server.id)]["current_exp"]
try:
users.append((userinfo["username"], server_exp))
except KeyError:
users.append((userinfo["user_id"], server_exp))
except KeyError:
pass
board_type = "Points"
footer_text = "Your Rank: {} {}: {}".format(
await self._find_server_rank(user, server),
board_type,
await self._find_server_exp(user, server),
)
icon_url = server.icon_url
sorted_list = sorted(users, key=operator.itemgetter(1), reverse=True)
# multiple page support
page = 1
per_page = 15
pages = math.ceil(len(sorted_list) / per_page)
for option in options:
if str(option).isdigit():
if page >= 1 and int(option) <= pages:
page = int(str(option))
else:
await ctx.send(
"**Please enter a valid page number! (1 - {})**".format(str(pages))
)
return
break
msg = ""
msg += "Rank Name (Page {}/{}) \n\n".format(page, pages)
rank = 1 + per_page * (page - 1)
start_index = per_page * page - per_page
end_index = per_page * page
default_label = " "
special_labels = ["♔", "♕", "♖", "♗", "♘", "♙"]
async for single_user in AsyncIter(sorted_list[start_index:end_index]):
if rank - 1 < len(special_labels):
label = special_labels[rank - 1]
else:
label = default_label
msg += "{:<2}{:<2}{:<2} # {:<11}".format(
rank, label, "➤", await self._truncate_text(single_user[0], 11)
)
msg += "{:>5}{:<2}{:<2}{:<5}\n".format(
" ", " ", " ", " {}: ".format(board_type) + str(single_user[1])
)
rank += 1
msg += "-------------------------------------------- \n"
msg += "{}".format(footer_text)
em = discord.Embed(description="", colour=user.colour)
em.set_author(name=title, icon_url=icon_url)
em.description = box(msg)
await ctx.send(embed=em)
@commands.command()
@commands.guild_only()
async def rep(self, ctx, *, user: discord.Member = None):
"""Gives a reputation point to a designated player."""
org_user = ctx.author
server = ctx.guild
# creates user if doesn't exist
await self._create_user(org_user, server)
if user:
await self._create_user(user, server)
org_userinfo = await self.db.users.find_one({"user_id": str(org_user.id)})
curr_time = time.time()
if await self.config.guild(ctx.guild).disabled():
await ctx.send("**Leveler commands for this server are disabled!**")
return
if user and user.id == org_user.id:
await ctx.send("**You can't give a rep to yourself!**")
return
if user and user.bot:
await ctx.send("**You can't give a rep to a bot!**")
return
if "rep_block" not in org_userinfo:
org_userinfo["rep_block"] = 0
delta = float(curr_time) - float(org_userinfo["rep_block"])
if user and delta >= 43200.0 and delta > 0:
userinfo = await self.db.users.find_one({"user_id": str(user.id)})
await self.db.users.update_one(
{"user_id": str(org_user.id)}, {"$set": {"rep_block": curr_time}}
)
await self.db.users.update_one(
{"user_id": str(user.id)}, {"$set": {"rep": userinfo["rep"] + 1}}
)
await ctx.send(
"**You have just given {} a reputation point!**".format(
await self._is_mention(user)
)
)
else:
# calulate time left
seconds = 43200 - delta
if seconds < 0:
await ctx.send("**You can give a rep!**")
return
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
await ctx.send(
"**You need to wait {} hours, {} minutes, and {} seconds until you can give reputation again!**".format(
int(h), int(m), int(s)
)
)
@commands.command()
@commands.guild_only()
async def lvlinfo(self, ctx, *, user: discord.Member = None):
"""Gives more specific details about user profile image."""
if not user:
user = ctx.author
if user.bot:
await ctx.send_help()
return
server = ctx.guild
userinfo = await self.db.users.find_one({"user_id": str(user.id)})
if await self.config.guild(ctx.guild).disabled():
await ctx.send("**Leveler commands for this server are disabled!**")
return
# creates user if doesn't exist
await self._create_user(user, server)
msg = ""
msg += "Name: {}\n".format(user.name)
msg += "Title: {}\n".format(userinfo["title"])
msg += "Reps: {}\n".format(userinfo["rep"])
msg += "Server Level: {}\n".format(userinfo["servers"][str(server.id)]["level"])
total_server_exp = 0
for i in range(userinfo["servers"][str(server.id)]["level"]):
total_server_exp += await self._required_exp(i)
total_server_exp += userinfo["servers"][str(server.id)]["current_exp"]
msg += "Server Exp: {}\n".format(total_server_exp)
msg += "Total Exp: {}\n".format(userinfo["total_exp"])
msg += "Info: {}\n".format(userinfo["info"])
msg += "Profile background: {}\n".format(userinfo["profile_background"])
msg += "Rank background: {}\n".format(userinfo["rank_background"])
msg += "Levelup background: {}\n".format(userinfo["levelup_background"])
if "profile_info_color" in userinfo.keys() and userinfo["profile_info_color"]:
msg += "Profile info color: {}\n".format(
self._rgb_to_hex(userinfo["profile_info_color"])
)
if "profile_exp_color" in userinfo.keys() and userinfo["profile_exp_color"]:
msg += "Profile exp color: {}\n".format(
self._rgb_to_hex(userinfo["profile_exp_color"])
)
if "rep_color" in userinfo.keys() and userinfo["rep_color"]:
msg += "Rep section color: {}\n".format(self._rgb_to_hex(userinfo["rep_color"]))
if "badge_col_color" in userinfo.keys() and userinfo["badge_col_color"]:
msg += "Badge section color: {}\n".format(
self._rgb_to_hex(userinfo["badge_col_color"])
)
if "rank_info_color" in userinfo.keys() and userinfo["rank_info_color"]:
msg += "Rank info color: {}\n".format(self._rgb_to_hex(userinfo["rank_info_color"]))
if "rank_exp_color" in userinfo.keys() and userinfo["rank_exp_color"]:
msg += "Rank exp color: {}\n".format(self._rgb_to_hex(userinfo["rank_exp_color"]))
if "levelup_info_color" in userinfo.keys() and userinfo["levelup_info_color"]:
msg += "Level info color: {}\n".format(
self._rgb_to_hex(userinfo["levelup_info_color"])
)
msg += "Badges: "
msg += ", ".join(userinfo["badges"])
em = discord.Embed(description=msg, colour=user.colour)
em.set_author(
name="Profile Information for {}".format(user.name), icon_url=user.avatar_url,
)
await ctx.send(embed=em)
def _rgb_to_hex(self, rgb):
rgb = tuple(rgb[:3])
return "#%02x%02x%02x" % rgb
@checks.is_owner()
@commands.group()
async def levelerset(self, ctx):
"""
MongoDB server configuration options.
Use that command in DM to see current settings.
"""
if not ctx.invoked_subcommand and ctx.channel.type == discord.ChannelType.private:
settings = [
(setting.replace("_", " ").title(), value)
for setting, value in (await self.config.custom("MONGODB").get_raw()).items()
if value
]
await ctx.send(box(tabulate(settings, tablefmt="plain")))
@levelerset.command()
async def host(self, ctx, host: str = "localhost"):
"""Set the MongoDB server host."""
await self.config.custom("MONGODB").host.set(host)
message = await ctx.send(
f"MongoDB host set to {host}.\nNow trying to connect to the new host..."
)
client = await self._connect_to_mongo()
if not client:
return await message.edit(
content=message.content.replace("Now trying to connect to the new host...", "")
+ "Failed to connect. Please try again with a valid host."
)
await message.edit(
content=message.content.replace("Now trying to connect to the new host...", "")
)
@levelerset.command()
async def port(self, ctx, port: int = 27017):
"""Set the MongoDB server port."""
await self.config.custom("MONGODB").port.set(port)
message = await ctx.send(
f"MongoDB port set to {port}.\nNow trying to connect to the new port..."
)
client = await self._connect_to_mongo()
if not client:
return await message.edit(
content=message.content.replace("Now trying to connect to the new port...", "")
+ "Failed to connect. Please try again with a valid port."
)
await message.edit(
content=message.content.replace("Now trying to connect to the new port...", "")
)
@levelerset.command(aliases=["creds"])
async def credentials(self, ctx, username: str = None, password: str = None):
"""Set the MongoDB server credentials."""
await self.config.custom("MONGODB").username.set(username)
await self.config.custom("MONGODB").password.set(password)
message = await ctx.send("MongoDB credentials set.\nNow trying to connect...")
client = await self._connect_to_mongo()
if not client:
return await message.edit(
content=message.content.replace("Now trying to connect...", "")
+ "Failed to connect. Please try again with valid credentials."
)
await message.edit(content=message.content.replace("Now trying to connect...", ""))
@levelerset.command()
async def dbname(self, ctx, dbname: str = "leveler"):
"""Set the MongoDB db name."""
await self.config.custom("MONGODB").db_name.set(dbname)
message = await ctx.send("MongoDB db name set.\nNow trying to connect...")
client = await self._connect_to_mongo()
if not client:
return await message.edit(
content=message.content.replace("Now trying to connect...", "")
+ "Failed to connect. Please try again with a valid db name."
)
await message.edit(content=message.content.replace("Now trying to connect...", ""))
@commands.group(name="lvlset", pass_context=True)
async def lvlset(self, ctx):
"""Profile configuration Options."""
pass
@lvlset.group(name="profile", pass_context=True)
async def profileset(self, ctx):
"""Profile options."""
pass
@lvlset.group(name="rank", pass_context=True)
async def rankset(self, ctx):
"""Rank options."""
pass
@lvlset.group(name="levelup", pass_context=True)
async def levelupset(self, ctx):
"""Level-Up options."""
pass
@profileset.command(name="color", pass_context=True, no_pm=True)
async def profilecolors(self, ctx, section: str, color: str):
"""Set profile color.
For section, you can choose: `exp`, `rep`, `badge`, `info` or `all`.
For color, you can use: `default`, `white`, `HEX code` (#000000) or `auto`.
e.g: `[p]lvlset profile color all #eb4034`"""
user = ctx.author
server = ctx.guild
# creates user if doesn't exist
await self._create_user(user, server)
userinfo = await self.db.users.find_one({"user_id": str(user.id)})
section = section.lower()
default_info_color = (30, 30, 30, 200)
white_info_color = (150, 150, 150, 180)
default_rep = (92, 130, 203, 230)
default_badge = (128, 151, 165, 230)
default_exp = (255, 255, 255, 230)
default_a = 200
if await self.config.guild(ctx.guild).disabled():
await ctx.send("**Leveler commands for this server are disabled!**")
return
if await self.config.guild(ctx.guild).text_only():
await ctx.send("**Text-only commands allowed.**")
return
# get correct section for db query
if section == "rep":
section_name = "rep_color"
elif section == "exp":
section_name = "profile_exp_color"
elif section == "badge":
section_name = "badge_col_color"
elif section == "info":
section_name = "profile_info_color"
elif section == "all":
section_name = "all"
else:
await ctx.send(
"**Not a valid section. Must be `rep`, `exp`, `badge`, `info` or `all`.**"
)
return
# get correct color choice
if color == "auto":
if not all(lib in globals().keys() for lib in ["numpy", "cluster"]):
await ctx.send("**Missing required package. Autocolor feature unavailable**")
return
if section == "exp":
color_ranks = [random.randint(2, 3)]
elif section == "rep":
color_ranks = [random.randint(2, 3)]
elif section == "badge":
color_ranks = [0] # most prominent color
elif section == "info":
color_ranks = [random.randint(0, 1)]
elif section == "all":
color_ranks = [
random.randint(2, 3),
random.randint(2, 3),
0,
random.randint(0, 2),
]
hex_colors = await self._auto_color(ctx, userinfo["profile_background"], color_ranks)
set_color = []
for hex_color in hex_colors:
color_temp = self._hex_to_rgb(hex_color, default_a)
set_color.append(color_temp)
elif color == "white":
set_color = [white_info_color]
elif color == "default":
if section == "exp":
set_color = [default_exp]
elif section == "rep":
set_color = [default_rep]
elif section == "badge":
set_color = [default_badge]
elif section == "info":
set_color = [default_info_color]
elif section == "all":
set_color = [
default_exp,
default_rep,
default_badge,
default_info_color,
]
elif self._is_hex(color):
set_color = [self._hex_to_rgb(color, default_a)]
else:
await ctx.send(
"**Not a valid color. Must be `default`, `HEX color`, `white` or `auto`.**"
)
return
if section == "all":
if len(set_color) == 1:
await self.db.users.update_one(
{"user_id": str(user.id)},
{
"$set": {
"profile_exp_color": set_color[0],
"rep_color": set_color[0],
"badge_col_color": set_color[0],
"profile_info_color": set_color[0],
}
},
)
elif color == "default":
await self.db.users.update_one(
{"user_id": str(user.id)},
{
"$set": {
"profile_exp_color": default_exp,
"rep_color": default_rep,
"badge_col_color": default_badge,
"profile_info_color": default_info_color,
}
},
)
elif color == "auto":
await self.db.users.update_one(
{"user_id": str(user.id)},
{
"$set": {
"profile_exp_color": set_color[0],
"rep_color": set_color[1],
"badge_col_color": set_color[2],
"profile_info_color": set_color[3],
}
},
)
await ctx.send("**Colors for profile set.**")
else:
await self.db.users.update_one(
{"user_id": str(user.id)}, {"$set": {section_name: set_color[0]}}
)
await ctx.send("**Color for profile {} set.**".format(section))
@rankset.command(name="color")
@commands.guild_only()
async def rankcolors(self, ctx, section: str, color: str = None):
"""Set rank color.
For section, you can choose: `exp`, `info` or `all`.
For color, you can use: `default`, `white`, `HEX code` (#000000) or `auto`.
e.g: `[p]lvlset rank color info white`"""
user = ctx.author
server = ctx.guild
# creates user if doesn't exist
await self._create_user(user, server)
userinfo = await self.db.users.find_one({"user_id": str(user.id)})
section = section.lower()
default_info_color = (30, 30, 30, 200)
white_info_color = (150, 150, 150, 180)
default_exp = (255, 255, 255, 230)
default_rep = (92, 130, 203, 230)
default_badge = (128, 151, 165, 230)
default_a = 200
if await self.config.guild(ctx.guild).disabled():
await ctx.send("**Leveler commands for this server are disabled!**")
return
if await self.config.guild(ctx.guild).text_only():
await ctx.send("**Text-only commands allowed.**")
return
# get correct section for db query
if section == "exp":
section_name = "rank_exp_color"
elif section == "info":
section_name = "rank_info_color"
elif section == "all":
section_name = "all"
else:
await ctx.send("**Not a valid section. Must be `exp`, `info` or `all`**")
return
# get correct color choice
if color == "auto":
if not all(lib in globals().keys() for lib in ["numpy", "cluster"]):
await ctx.send("**Missing required package. Autocolor feature unavailable**")
return
if section == "exp":
color_ranks = [random.randint(2, 3)]
elif section == "info":
color_ranks = [random.randint(0, 1)]
elif section == "all":
color_ranks = [random.randint(2, 3), random.randint(0, 1)]
hex_colors = await self._auto_color(ctx, userinfo["rank_background"], color_ranks)
set_color = []
for hex_color in hex_colors:
color_temp = self._hex_to_rgb(hex_color, default_a)
set_color.append(color_temp)
elif color == "white":
set_color = [white_info_color]
elif color == "default":
if section == "exp":
set_color = [default_exp]
elif section == "info":
set_color = [default_info_color]
elif section == "all":
set_color = [
default_exp,
default_rep,
default_badge,
default_info_color,
]
elif self._is_hex(color):
set_color = [self._hex_to_rgb(color, default_a)]
else:
await ctx.send(
"**Not a valid color. Must be `default`, `HEX color`, `white or `auto`.**"
)
return
if section == "all":
if len(set_color) == 1:
await self.db.users.update_one(
{"user_id": str(user.id)},
{"$set": {"rank_exp_color": set_color[0], "rank_info_color": set_color[0],}},
)
elif color == "default":
await self.db.users.update_one(
{"user_id": str(user.id)},
{
"$set": {
"rank_exp_color": default_exp,
"rank_info_color": default_info_color,
}
},
)
elif color == "auto":
await self.db.users.update_one(
{"user_id": str(user.id)},
{"$set": {"rank_exp_color": set_color[0], "rank_info_color": set_color[1],}},
)
await ctx.send("**Colors for rank set.**")
else:
await self.db.users.update_one(
{"user_id": str(user.id)}, {"$set": {section_name: set_color[0]}}
)
await ctx.send("**Color for rank {} set.**".format(section))
@levelupset.command(name="color")
@commands.guild_only()
async def levelupcolors(self, ctx, section: str, color: str = None):
"""Set levelup color.
Section can only be `info`.
Color can be : `default`, `white`, `HEX code` (#000000) or `auto`.
e.g: `[p]lvlset color info default`"""
user = ctx.author
server = ctx.guild
# creates user if doesn't exist
await self._create_user(user, server)
userinfo = await self.db.users.find_one({"user_id": str(user.id)})
section = section.lower()
default_info_color = (30, 30, 30, 200)
white_info_color = (150, 150, 150, 180)
default_a = 200
if await self.config.guild(ctx.guild).disabled():
await ctx.send("**Leveler commands for this server are disabled!**")
return
if await self.config.guild(ctx.guild).text_only():
await ctx.send("**Text-only commands allowed.**")
return
# get correct section for db query
if section == "info":
section_name = "levelup_info_color"
else:
await ctx.send("**Not a valid section. Must be `info`.**")
return
# get correct color choice
if color == "auto":
if not all(lib in globals().keys() for lib in ["numpy", "cluster"]):
await ctx.send("**Missing required package. Autocolor feature unavailable**")
return
if section == "info":
color_ranks = [random.randint(0, 1)]
hex_colors = await self._auto_color(ctx, userinfo["levelup_background"], color_ranks)
set_color = []
for hex_color in hex_colors:
color_temp = self._hex_to_rgb(hex_color, default_a)
set_color.append(color_temp)
elif color == "white":
set_color = [white_info_color]
elif color == "default":
if section == "info":
set_color = [default_info_color]
elif self._is_hex(color):
set_color = [self._hex_to_rgb(color, default_a)]
else:
await ctx.send(
"**Not a valid color. Must be `default` `HEX color`, `white` or `auto`.**"
)
return
await self.db.users.update_one(
{"user_id": str(user.id)}, {"$set": {section_name: set_color[0]}}
)
await ctx.send("**Color for level-up {} set.**".format(section))
# uses k-means algorithm to find color from bg, rank is abundance of color, descending
async def _auto_color(self, ctx, url: str, ranks):
phrases = ["Calculating colors..."] # in case I want more
await ctx.send("**{}**".format(random.choice(phrases)))
clusters = 10
async with self.session.get(url) as r:
image = await r.content.read()
image = BytesIO(image)
im = Image.open(image).convert("RGBA")
im = im.resize((290, 290)) # resized to reduce time
ar = numpy.asarray(im)
shape = ar.shape
ar = ar.reshape(numpy.product(shape[:2]), shape[2])
codes, dist = cluster.vq.kmeans(ar.astype(float), clusters)
vecs, dist = cluster.vq.vq(ar, codes) # assign codes
counts, bins = numpy.histogram(vecs, len(codes)) # count occurrences
# sort counts
freq_index = []
index = 0
for count in counts:
freq_index.append((index, count))
index += 1
sorted_list = sorted(freq_index, key=operator.itemgetter(1), reverse=True)
colors = []
for rank in ranks:
color_index = min(rank, len(codes))
peak = codes[sorted_list[color_index][0]] # gets the original index
peak = peak.astype(int)
colors.append("".join(format(c, "02x") for c in peak))
return colors # returns array