-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
2122 lines (1892 loc) Β· 90.9 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
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
# Imports
from math import ceil
from random import randint
from os import path
from datetime import date, datetime
import json
import re
import requests
import socket
import cv2
import discord
import discord.ext.commands
# from discord.ui import Modal, InputText
# from discord_slash.utils.manage_commands import create_option, create_permission, remove_all_commands
# from discord_slash.utils.manage_components import create_button, create_actionrow, ButtonStyle, create_select, create_select_option
# from discord_slash.model import SlashCommandPermissionType, ContextMenuType
# import interactions
# Local imports
from log_handling import *
from imaging import generate_level_card
import AI
from colours import colours
# Loads config CONST variables
DEFAULT_TOKEN = "ENTER TOKEN HERE"
DEFAULT_PREFIX = "-"
DEFAULT_DEBUG = True
DEFAULT_LEVEL = "INFO"
DEFAULT_JOKE_SERVERS = []
DEFAULT_REPORT_CHANNEL = None
DEFAULT_DEVELOPERS = [241772848564142080, 258284765776576512]
DEFAULT_DEFAULT_COLOUR = 0xffc000 # Default
hostname = socket.gethostname()
VERSION = "1.3.4 beta"
SERVER_STRUCTURE = \
{
"config": {
"announcements channel id": 0
},
"rules": {
"title": "Server rules",
"description": "",
"list": [],
"image link": ""
},
"roles": {
"verify role": 0,
"categories": {}
},
"ranks": {}
}
TOKEN = DEFAULT_TOKEN
PREFIX = DEFAULT_PREFIX
DEBUG = DEFAULT_DEBUG
LEVEL = DEFAULT_LEVEL
JOKE_SERVERS = DEFAULT_JOKE_SERVERS
REPORT_CHANNEL = DEFAULT_REPORT_CHANNEL
DEVELOPERS = DEFAULT_DEVELOPERS
DEFAULT_COLOUR = DEFAULT_DEFAULT_COLOUR
# Data upgrade
def upgrade_data():
global DEVELOPERS
new_data = {}
data = {}
config = {}
try:
with open("data.json", encoding='utf-8') as file:
data = json.load(file)
with open("config.json", encoding='utf-8') as config_file:
config = json.load(config_file)
if "config" in data:
print("Upgrading data file")
# Data "config" rename to "bot settings"
new_data = {"bot settings": data["config"]}
del data["config"]
new_data.update(data)
# Developers move to config
if "developers" in new_data["bot settings"]:
print("Detected developers in old location")
# Checks if config or data developers should be used
move = "y"
if "developers" in config:
move = input("Developers found in config file, would you like to replace with ones in data file? Y/N").lower()
if move == "y":
print("Moving developers data")
DEVELOPERS = new_data["bot settings"]["developers"]
config["developers"] = DEVELOPERS
del new_data["bot settings"]["developers"]
else:
new_data.update(data)
with open("data.json", "w", encoding='utf-8') as file:
json.dump(new_data, file, indent=4)
with open("config.json", "w") as file:
json.dump(config,file, indent=4)
except FileNotFoundError:
print("data.json not setup. This is a fresh install!")
except Exception as exception:
print(f"Failed to check data file was upgraded: \"{type(exception).__name__}\" : {exception.args[0]}\n")
upgrade_data()
def create_config():
with open("config.json", "w") as file:
TOKEN = input("Please input your bot's token (this will be stored in the config.json file)")
json.dump({"token": TOKEN,"prefix":PREFIX,"debug":DEBUG,"level":LEVEL,"joke servers":JOKE_SERVERS,"report channel":REPORT_CHANNEL,"developers":DEVELOPERS,"default colour":DEFAULT_COLOUR}, file, indent=4)
print("Additional config can be written in config.json")
def setup_config():
global TOKEN, PREFIX, DEBUG, LEVEL, JOKE_SERVERS, REPORT_CHANNEL, DEVELOPERS, DEFAULT_COLOUR
def initiate_const(name, default, dictionary):
try:
return dictionary[name]
except KeyError:
return default
if not path.exists("config.json"):
create_config()
print("config.json created")
with open("config.json", encoding='utf-8') as file:
try:
data = json.load(file)
except json.JSONDecodeError:
data = {}
TOKEN = initiate_const("token", DEFAULT_TOKEN, data)
if TOKEN == DEFAULT_TOKEN:
create_config()
print("config.json setup")
PREFIX = initiate_const("prefix", DEFAULT_PREFIX, data)
DEBUG = initiate_const("debug", DEFAULT_DEBUG, data)
LEVEL = initiate_const("level", DEFAULT_LEVEL, data)
JOKE_SERVERS = initiate_const("joke servers", DEFAULT_JOKE_SERVERS, data)
REPORT_CHANNEL = initiate_const("report channel", DEFAULT_REPORT_CHANNEL, data)
DEVELOPERS = initiate_const("developers", DEFAULT_DEVELOPERS, data)
DEFAULT_COLOUR = initiate_const("default colour", DEFAULT_DEFAULT_COLOUR, data)
setup_config()
# Functions
def populate_actionrows(button_list):
"""Returns a list of actionrows of 5 or fewer buttons."""
actionrow_list = []
for x in range(ceil(len(button_list) / 5)):
if len(button_list[(5 * x):]) > 5:
actionrow_list.append(create_actionrow(*button_list[(5 * x):(5 * x) + 5]))
else:
actionrow_list.append(create_actionrow(*button_list[(5 * x):]))
return actionrow_list
# Definitions
class MyClient(discord.ext.commands.Bot):
def __init__(self, *args, **kwargs):
"""Constructor."""
super().__init__(*args, **kwargs,command_prefix=PREFIX)
self.connected = True # Starts true so on first boot, it won't think its restarted
self.start_time = datetime.now()
self.last_disconnect = datetime.now()
self.data = {}
self.cache = {}
self.poll = {}
self.purge_messages = {}
self.activity = discord.Activity(type=discord.ActivityType.listening, name="the rain") # There is no room for purple gods here
# Prints logs to the console
if DEBUG is True:
x = logging.StreamHandler()
x.setLevel(LEVEL)
logger.addHandler(x)
def update_data(self):
"""Writes the data attribute to the file."""
try:
with open("data.json", "w", encoding='utf-8') as file:
json.dump(self.data, file, indent=4)
logger.debug("Updated data.json") # Event log
except Exception as exception:
logger.critical("Failed to update data.json. Exception: " + str(exception)) # Event log
def initialise_guild(self, guild):
"""Creates data for a new guild."""
try:
if str(guild.id) not in self.data["servers"]: # Check if server data already exists
self.data["servers"][str(guild.id)] = SERVER_STRUCTURE
self.cache[str(guild.id)] = {}
self.poll[str(guild.id)] = {}
# Write the updated data
self.update_data()
logger.info("Initialised guild: " + guild.name + " (ID: " + str(guild.id) + ")") # Event log
except Exception as exception:
logger.critical("Failed to initialise guild: " + guild.name + " (ID: " + str(guild.id) + "). Exception: " + str(exception)) # Event log
def get_uptime(self):
"""Returns instance uptime."""
try:
seconds = round((datetime.now() - self.start_time).total_seconds())
uptime = ""
if seconds >= 3600:
uptime += str(seconds // 3600) + " "
if seconds // 3600 == 1:
uptime += "hour"
else:
uptime += "hours"
if seconds % 3600 >= 60:
if uptime != "":
uptime += " "
uptime += str(seconds % 3600 // 60) + " "
if seconds % 3600 // 60 == 1:
uptime += "minute"
else:
uptime += "minutes"
if seconds % 60 > 0:
if uptime != "":
uptime += " "
uptime += str(seconds % 60) + " "
if seconds % 60 == 1:
uptime += "second"
else:
uptime += "seconds"
logger.debug("Calculated uptime") # Event log
return uptime
except Exception as exception:
logger.error("Failed to calculate uptime. Exception: " + str(exception)) # Event log
return None
async def terminate_poll(self, message):
"""Closes poll"""
reactions = message.reactions
highest_count = 0
emojis = []
counts = []
for reaction in reactions:
emoji = reaction.emoji
if emoji not in emojis:
emojis.append(emoji)
if str(emoji) != "π": # Doesn't count end emote
counts.append(str(reaction.count - 1))
if reaction.count > highest_count:
highest_count = reaction.count
highest_emoji = reaction.emoji
highest_count -= 1 # Takes away the bots reaction
poll = self.poll[str(message.guild.id)][str(message.id)]
options = []
# for option in poll["options"]: # Makes list of options
for emoji in emojis:
if str(emoji) != "π":
options.append(str(emoji) + " " + poll["voters"][str(emoji)])
title = str(poll["title"])
if title == "Embed.Empty":
title = ""
embed_results = discord.Embed(title=title + " Results")
embed_results.add_field(name="Candidates", value="\n".join(options), inline=True)
embed_results.add_field(name="Count", value="\n".join(counts), inline=True)
if poll["config"]["winner"] == "highest": # Winner is shown as the highest scoring candidate
embed_results.add_field(name="Winner", value=(str(highest_emoji) + " " + poll["voters"][str(highest_emoji)] + " Score: " + str(highest_count)), inline=False)
await message.channel.send(embed=embed_results)
self.poll[str(message.guild.id)].pop(str(message.id)) # Removes poll entry from dictionary
async def get_formatted_emoji(self, emoji_reference, guild):
"""Returns an emoji that discord should always be able to use"""
if emoji_reference.startswith("<"):
parts = emoji_reference.split(":")
return discord.utils.get(guild.emojis, name=parts[1]) # Uses the name part to get the emoji
else:
return emoji_reference
async def create_thread_message(self, channel_id, content, tts=False, embeds=[]): # Made from the corpse of helminth
token = 'Bot ' + TOKEN
# Converts embed(s) into json
try:
for x in range(len(embeds)):
embeds[x] = embeds[x].to_dict()
except TypeError:
embeds = [embeds.to_dict()]
headers = {
"authorization": token,
"content-type": "application/json"
}
request_body = {
"content": content,
"tts": tts,
"embeds": embeds
}
return requests.post("https://discordapp.com/api/channels/" + str(channel_id) + "/messages", headers=headers,data=json.dumps(request_body))
def get_server_colour(self,guild_id):
if "colour theme" in self.data["servers"][str(guild_id)]["config"]:
return self.data["servers"][str(guild_id)]["config"]["colour theme"]
else:
return DEFAULT_COLOUR
async def announce(self, announcement, announcement_type="generic"):
"""Sends announcement messages to each guild's assigned announcement channel."""
if announcement_type == "alert":
try:
await self.get_channel(REPORT_CHANNEL).send(announcement)
except AttributeError:
logger.info("No report channel set. It is highly recommended to set one in config.json")
else:
for guild in self.guilds:
if self.data["servers"][str(guild.id)]["config"]["announcements channel id"] != 0: # Only finds announcement channel if the guild has one set
announcement_sent = False
for channel in guild.text_channels:
if channel.id == self.data["servers"][str(guild.id)]["config"]["announcements channel id"]:
logger.debug("Sending " + announcement_type + " announcement to " + guild.name + " in " + channel.name) # Event log
announcement_sent = True
await channel.send(announcement)
break
if announcement_sent is False:
logger.debug("Failed to send " + announcement_type + " announcement. Announcement channel not found in " + guild.name) # Event log
async def on_ready(self):
"""Runs when the client is ready."""
logger.debug("Connected!")
if self.connected == False:
logger.info("Last disconnect was " + str(self.last_disconnect))
await self.announce("**Reconnected**\nLast disconnect was " + str(self.last_disconnect), announcement_type="reconnection")
self.connected = True
# Load the data file into the data variable
try:
with open("data.json", encoding='utf-8') as file:
self.data = json.load(file)
logger.debug("Loaded data.json") # Event log
except Exception as exception:
logger.debug(f"Failed to load data.json. Exception: {exception}. Attempting to make new data.") # Event log
self.data = {"bot settings":{
"jokes": False,
"safety": True,
"add info": True},
"servers":{}}
self.update_data()
# Check if the bot has been added to a guild while offline
for guild in self.guilds:
if str(guild.id) not in self.data["servers"]:
logger.warning("The bot is in " + guild.name + " but has no data for it") # Event log
# Initialise guild
self.initialise_guild(guild)
# Initialise cache for servers
for guild in self.guilds:
self.cache[str(guild.id)] = {}
self.poll[str(guild.id)] = {}
logger.info(self.user.name + " is ready (finished on_ready)") # Event log
# Log on_ready messages
logger.info(self.user.name + " is ready (commencing on_ready)") # Event log
if self.guilds != []:
logger.info(self.user.name + " is connected to the following guilds:") # Event log
for guild in self.guilds:
logger.info(" " + guild.name + " (ID: " + str(guild.id) + ")") # Event log
# Send on_ready announcement
await self.announce("**" + self.user.name + " online**\nVersion: " + VERSION, announcement_type="on_ready")
guild_ids = []
for guild in self.guilds:
guild_ids.append(guild.id)
async def on_disconnect(self):
"""Runs on disconnection.
Logs disconnection."""
if self.connected == True: # Stops code being ran every time discord realises its still disconnected since the last minute or so
logger.info("Bot disconnected")
self.last_disconnect = datetime.now()
self.connected = False
async def on_guild_join(self, guild):
"""Runs on joining a guild.
The bot initialises the guild if it has no data on it."""
logger.info(self.user.name + " has joined the guild: " + guild.name + " with id: " + str(guild.id)) # Event log
await self.announce(self.user.name + " has joined the guild: " + guild.name + " with id: " + str(guild.id),"alert") # Event log
# Initialise guild
self.initialise_guild(guild)
await guild.text_channels[0].send(f"Oh this place looks nice. Setup my settings by doing {PREFIX}settings if you have admin permissions.\nIf you need help with anything else {PREFIX}help is the way to go!")
async def on_message(self, message):
"""Runs on message."""
logger.debug("Message sent by " + message.author.name) # Event log
# Don't respond to yourself
if message.author.id == self.user.id:
return
# Don't respond to other bots
if message.author.bot is True: # !!! Needs to be tested. Can replace "message.author.id == self.user.id" if so. Same goes for reactions.
return
# Set guild of origin
guild = self.get_guild(message.guild.id)
# Update the user's experience
if (message.author.id not in self.cache[str(guild.id)]) or (((datetime.now().minute + datetime.now().hour * 60) - self.cache[str(guild.id)][message.author.id]) > 60): # This is the longest like of code I've ever seen survive a scrutinised and picky merge from me. Well played.
logger.debug("Adding experience to " + message.author.name) # Event log
# Update the cache and increment the user's experience
self.cache[str(guild.id)][message.author.id] = datetime.now().minute + datetime.now().hour * 60
try:
self.data["servers"][str(guild.id)]["ranks"][str(message.author.id)] += 1
except KeyError:
self.data["servers"][str(guild.id)]["ranks"][str(message.author.id)] = 1
# Write the updated data
self.update_data()
else:
logger.debug("Not adding experience to " + message.author.name) # Event log
if not message.content.startswith(PREFIX):
# Joke functionality
if self.data["bot settings"]["jokes"] is True:
# Shut up Arun
if message.author.id == 258284765776576512:
if randint(1, 128) == 1:
logger.debug("Shut up Arun triggered by " + message.author.name) # Event log
if randint(1, 3) != 3:
await message.channel.send("shut up arun")
else:
await message.channel.send("arun, why are you still talking")
# Shut up Pablo
if message.author.id == 241772848564142080 or message.author.id == 842479806217060363:
if randint(1, 25) == 1:
logger.debug("Shut up Pablo triggered by " + message.author.name) # Event log
if randint(1, 2) == 1:
await message.channel.send("un-shut up pablo")
else:
await message.channel.send("pablo, put that big brain back on sleep mode")
if guild.id in JOKE_SERVERS:
# Gameboy mention
if "gameboy" in message.content.lower():
logger.debug("`gameboy` mentioned by " + message.author.name) # Event log
await message.channel.send("Gameboys are worthless (apart from micro. micro is cool)")
# Raspberry mention
if "raspberries" in message.content.lower() or "raspberry" in message.content.lower():
logger.debug("`raspberry racers` mentioned by " + message.author.name) # Event log
await message.channel.send(
"The Raspberry Racers are a team which debuted in the 2018 Winter Marble League. Their 2018 season was seen as the second-best rookie team of the year, behind only the Hazers. In the 2018 off-season, they won the A-Maze-ing Marble Race, making them one of the potential title contenders for the Marble League. They eventually did go on to win Marble League 2019.")
# Pycharm mention
if "pycharm" in message.content.lower():
logger.debug("`pycharm` mentioned by " + message.author.name) # Event log
await message.channel.send(
"Pycharm enthusiasts vs Sublime Text enjoyers: https://youtu.be/HrkNwjruz5k")
await message.channel.send(
"85 commits in and haha bot print funny is still our sense of humour.")
# Token command
if message.content == "token":
logger.debug("`token` called by " + message.author.name) # Event log
await message.channel.send("IdrOppED ThE TokEN gUYS!!!!")
# Summon lizzie command
if message.content == "summon lizzie":
logger.debug("`summon_lizzie` called by " + message.author.name) # Event log
for x in range(100):
await message.channel.send(guild.get_member(692684372247314445).mention)
# Summon leo command
if message.content == "summon leo":
logger.debug("`summon_leo` called by " + message.author.name) # Event log
for x in range(100):
await message.channel.send(guild.get_member(242790351524462603).mention)
# Teaching bitches how to swim
if message.content == "swim":
logger.debug("`swim` called by " + message.author.name) # Event log
await message.channel.send("/play https://youtu.be/uoZgZT4DGSY")
await message.channel.send("No swimming lessons today ):")
# Overlay Israel (Warning: DEFCON 1)
if message.content == "israeli defcon 1":
logger.debug("`israeli_defcon_1` called by " + message.author.name) # Event log
await message.channel.send("apologies in advance...")
while True:
await message.channel.send(".overlay israel")
return
else:
message.content = message.content[len(PREFIX):]
# Get level command
if message.content == "level":
logger.info("`level` called by " + message.author.name) # Event log
# Generate the rank card
if str(message.author.id) in self.data["servers"][str(guild.id)]["ranks"]:
rank = int((self.data["servers"][str(guild.id)]["ranks"][str(message.author.id)] ** 0.5) // 1)
percentage = int(round((self.data["servers"][str(guild.id)]["ranks"][str(message.author.id)] - (rank ** 2)) / (((rank + 1) ** 2) - (rank ** 2)) * 100))
else:
rank = 0
percentage = 0
generate_level_card(message.author.avatar_url_as(size=256,format="webp"), message.author.name, rank, percentage, server_picture=guild.icon_url_as(size=128,format="webp"))
# Create the rank embed
embed_level = discord.Embed()
file = discord.File("card.png")
embed_level.set_image(url="attachment://card.png")
# Send the embed
await message.channel.send(file=file)
# Level leaderboard command
if message.content == "leaderboard":
logger.info("`leaderboard` called by " + message.author.name) # Event log
leaderboard = reversed(sorted(self.data["servers"][str(guild.id)]["ranks"].items(), key=lambda item: item[1])) # Sorts rank dictionary into list
lb_message = ""
lb_count = ""
lb_no = ""
count = 1
for item in leaderboard:
try:
name = self.get_user(int(item[0])).name
lb_message += str(name) + "\n" # Reverse adds on higher scored names
lb_count += str(item[1]) + "\n" # Reverse adds on higher scores to separate string for separate embed field
lb_no += str(count) + "\n"
if count >= 100:
break
count += 1
except AttributeError:
logger.debug("Member not found in server")
embed_leaderboard = discord.Embed(title="Leaderboard", colour=self.get_server_colour(guild.id))
embed_leaderboard.add_field(name="No.", value=lb_no, inline=True)
embed_leaderboard.add_field(name="User", value=lb_message, inline=True)
embed_leaderboard.add_field(name="Count", value=lb_count, inline=True)
await message.channel.send(embed=embed_leaderboard)
# Embed command
if message.content.startswith("embed"):
logger.info("`embed` called by " + message.author.name) # Event log
try:
argument_string = message.content[len("embed "):]
arguments = re.split(",(?!\s)", argument_string) # Splits arguments when there is not a space after the comma, if there is, it is assumed to be part of a sentance.
title = discord.Embed.Empty
description = discord.Embed.Empty
colour = self.get_server_colour(guild.id)
fields = []
# Analyse argument
for argument in arguments:
argument = argument.split("=")
if len(argument) == 2:
if argument[0] == "title":
title = argument[1]
elif argument[0] == "description":
description = argument[1]
elif argument[0] == "colour":
try:
colour = int(argument[1][-6:], 16)
except ValueError:
if argument[1] in colours:
colour = colours[argument[1]]
else:
fields.append({argument[0]: argument[1]})
else:
description = argument[0]
# Create and send user's embed
embed = discord.Embed(title=title, description=description, colour=colour)
embed.set_author(name=message.author.name, url=discord.Embed.Empty, icon_url=message.author.avatar_url)
for field in fields:
embed.add_field(name=list(field.keys())[0], value=field[list(field.keys())[0]])
await message.channel.send(embed=embed)
await message.delete()
except Exception as exception:
logger.error(f"Failed understand embed command. Exception: \"{type(exception).__name__}\" : {exception.args[0]}")
await message.channel.send("Embed Failed: Check you put something to embed and that it's under 1024 character.\n" + str(exception))
# QR command
if message.content == "qr":
logger.info("`qr` called by " + message.author.name) # Event log
if len(message.attachments) == 1:
await message.attachments[0].save("qrcode.png")
img = cv2.imread("qrcode.png")
det = cv2.QRCodeDetector()
val, pts, st_code = det.detectAndDecode(img)
await message.channel.send(val)
# Help command
if message.content == "help":
logger.info("`help` called by " + message.author.name) # Event log
# Create and send the help embed
embed_help = discord.Embed(title="π€ Need help?", description="Here's a list of " + self.user.name + "'s commands!", colour=self.get_server_colour(guild.id))
embed_help.add_field(name=str(PREFIX + "__level__"), value="Creates your level card, showing your current level and progress to the next level.")
embed_help.add_field(name=str(PREFIX + "__leaderboard__"), value="Displays leaderboard for Sirius' levelling system")
embed_help.add_field(name=str(PREFIX + "__help__"), value="Creates the bot's help embed, listing the bot's commands.")
embed_help.add_field(name=str(PREFIX + "__embed__"), value="Creates an embed. Arguments: title=,description=,colour=[a colour],[name of field]=[string (Do not include commas or =)] (or just write and it'll be put in the description by deafult)")
embed_help.add_field(name=str(PREFIX + "__(/)poll__"), value="Creates a poll embed. Arguments: title=, colour=[a colour], anonymous(anon)=[true/false], [name of candidate]=[emoji]. All paramaters are optional. Admins react with π (end) to end poll) or right click>Apps>Close poll for anon poll")
embed_help.add_field(name=str("__/confess__"), value="Send your confession to the database anonymously for admins to review and post")
embed_help.add_field(name=str("__/question__"), value="Asks Sirius a question. Don't expect a very insightful response...")
embed_help.add_field(name=str("__/anonymous__"), value="Posts your message anonymously in the current channel")
embed_help.add_field(name=str(PREFIX + "__rules__"), value="Creates the server's rules embed.\n**Admin only feature.**")
embed_help.add_field(name=str(PREFIX + "__roles__"), value="Creates the server's roles embed.\n**Admin only feature.**")
embed_help.add_field(name=str(PREFIX + "__stats__"), value="Creates the server's stats embed by default. Can send csv file instead.Argument: csv=[true/false] (Optional. False by default)\n**Admin only feature.**")
embed_help.add_field(name=str(PREFIX + "__(/)purge__"), value="Deletes last x amount of messages. Argument: number of messages. **Consider using the slash command instead!**\n**Admin only feature.**")
embed_help.add_field(name=str(PREFIX + "__review confessions__"), value="Shows all unposted confessions in the channel the is sent in. Each confession has a button to remove it from " + self.user.name + "'s data.\n**Admin only feature.**")
embed_help.add_field(name=str(PREFIX + "__post confessions__"), value="Posts all unposted confessions in the channel the command is sent in.\n**Admin only feature.**")
embed_help.add_field(name=str(PREFIX + "__settings__"), value="Brings up server settings page\n**Admin only feature.**")
embed_help.add_field(name=str(PREFIX + "__config__"), value="Brings up " + self.user.name + " configuration page.\n**Dev only feature.**")
embed_help.add_field(name=str(PREFIX + "__report__"), value="Reports the value of the variable(s) given. Argument: [name of almost any variable]\n**Dev only feature. safety off to use.**")
embed_help.add_field(name=str(PREFIX + "__announce__"), value="Sends a generic announcement with a parameter for the message.\n**Dev only feature.**")
embed_help.add_field(name=str(PREFIX + "__locate__"), value="Locates the instance of " + self.user.name + ".\n**Dev only feature.**")
embed_help.add_field(name=str(PREFIX + "__kill__"), value="Ends the instance of " + self.user.name + ".\n**Dev only feature.**")
await message.channel.send(embed=embed_help)
# If the message was sent by the admins
if message.author.guild_permissions.administrator:
# Rules command
if message.content == "rules":
logger.info("`rules` called by " + message.author.name) # Event log
# If the rules have been set up
if len(self.data["servers"][str(guild.id)]["rules"]["list"]) != 0:
# Delete the command message
await message.delete()
# Create the welcome embed !!! This is messy. Decide embed format and what should be customisable
embed_welcome = discord.Embed(title="π Welcome to " + message.guild.name + ".", description="[Discord community server description]\n\nTake a moment to familiarise yourself with the rules below.\nChannel <#000000000000000000> is for this, and <#000000000000000001> is for that.", colour=self.get_server_colour(guild.id))
# Create the rules embed
embed_rules = discord.Embed(title=self.data["servers"][str(guild.id)]["rules"]["title"], description=self.data["servers"][str(guild.id)]["rules"]["description"], colour=self.get_server_colour(guild.id), inline=False)
embed_rules.set_footer(text="Rules updated β’ " + date.today().strftime("%d/%m/%Y"), icon_url=guild.icon_url_as(size=128))
embed_rules.add_field(name="Rules", value="\n".join(self.data["servers"][str(guild.id)]["rules"]["list"]), inline=True)
embed_image = discord.Embed(description="That's all.", colour=self.get_server_colour(guild.id))
image = self.data["servers"][str(guild.id)]["rules"]["image link"]
if image != None:
if image[:6] == "https:":
embed_image.set_image(url=self.data["servers"][str(guild.id)]["rules"]["image link"])
else:
logger.debug("Image link doesn't start with https for " + str(message.guild.id)) # Event log
else:
logger.debug("Image link not found for " + str(message.guild.id)) # Event log
# Send the embeds
await message.channel.send(embed=embed_welcome)
await message.channel.send(embed=embed_rules)
await message.channel.send(embed=embed_image)
# If the rules haven't been set up
else:
logger.debug("Rules have not been set up for " + str(message.guild.id)) # Event log
await message.channel.send("Uh oh, you haven't set up any rules! Get a server admin to set them up at https://www.lingscars.com/")
# Role buttons command
if message.content == "roles":
# If the roles functionality is enabled
if "roles" in self.data["servers"][str(message.guild.id)]:
# try:
# Creates and sends the roles messages
await message.channel.send("# ποΈ Role selection\nClick the button to get a role, click again to remove it.")
for category in self.data["servers"][str(message.guild.id)]["roles"]["categories"]:
buttons = []
for role in self.data["servers"][str(message.guild.id)]["roles"]["categories"][category]["list"]:
buttons.append(create_button(style=ButtonStyle.blue, emoji=await self.get_formatted_emoji(self.data["servers"][str(message.guild.id)]["roles"]["categories"][category]["list"][role]["emoji"], guild), label=self.data["servers"][str(message.guild.id)]["roles"]["categories"][category]["list"][role]["name"], custom_id=role))
components = populate_actionrows(buttons) # Puts buttons in to rows of 5 or less
category_message = await message.channel.send(content="## " + category + "\n" + "Select the roles for this category!", components=components)
# Updates the category's message id
self.data["servers"][str(message.guild.id)]["roles"]["categories"][category]["message id"] = category_message.id
# Write the updated data
self.update_data()
# except Exception as exception:
# logger.error("Failed to send roles message in " + message.guild.name + " (" + str(message.guild.id) + "). Exception: " + str(exception))
# If the roles functionality is disabled
else:
await message.channel.send("Uh oh, you haven't set up any roles! Get a server admin to set them up at https://www.lingscars.com/")
# Roles command
if message.content == "react roles":
logger.info("`roles` called by " + message.author.name) # Event log
# If the roles have been set up
if len(self.data["servers"][str(guild.id)]["roles"]["categories"]) != 0:
# Delete the command message
await message.delete()
# Send one roles message per category
await message.channel.send("ποΈ **Role selection**\nClick to get a role, click again to remove it.")
for category in self.data["servers"][str(guild.id)]["roles"]["categories"]: # For category in roles
roles = []
for role in self.data["servers"][str(guild.id)]["roles"]["categories"][category]["list"]: # For role in category
roles.append(self.data["servers"][str(guild.id)]["roles"]["categories"][category]["list"][role]["emoji"] + " - " + self.data["servers"][str(guild.id)]["roles"]["categories"][category]["list"][role]["name"] + "\n")
category_message = await message.channel.send("**" + category + "**\n\n" + "".join(roles))
# Add reactions to the roles message
for role in self.data["servers"][str(guild.id)]["roles"]["categories"][category]["list"]:
await category_message.add_reaction(self.data["servers"][str(guild.id)]["roles"]["categories"][category]["list"][role]["emoji"])
# Update the category's message id variable
self.data["servers"][str(guild.id)]["roles"]["categories"][category]["message id"] = category_message.id
# Write the updated data
self.update_data()
# If the roles haven't been set up
else:
logger.debug("Roles have not been set up for " + str(message.guild.id)) # Event log
await message.channel.send("Uh oh, you haven't set up any roles! Get a server admin to set them up at https://www.lingscars.com/")
# Stats command
if message.content.startswith("stats"):
logger.info("`stats` called by " + message.author.name) # Event log
argument = message.content[len("stats "):]
csv = False
if argument == "csv": # Changes to csv mode where the stats are saved to a csv file instead
csv = True
logger.debug("Using csv mode")
try:
# Generate statistics
if csv:
waiting_message = await message.channel.send("Processing stats for csv\nThis may take some time...")
else:
waiting_message = await message.channel.send("Processing stats to display\nThis may take some time...")
members = {}
channel_statistics = [''] * (len(guild.text_channels))
total_messages = 0
# Channel statistics info gathered
channel_count = 0
for channel in guild.text_channels:
channel_count += 1
message_count = 0
async for message_sent in channel.history(limit=None):
message_count += 1
if message_sent.author.bot is False: # Don't count messages from bots
if message_sent.author not in members:
members[message_sent.author] = 1
else:
members[message_sent.author] += 1
total_messages += message_count
if csv:
channel_statistics[channel_count // 10] += channel.name + "," + str(message_count) + "\n"
else:
channel_statistics[channel_count // 10] += channel.mention + ": " + str(message_count) + "\n"
# Member statistics gathered from the data obtained when processing channel statistics
member_statistics = [''] * (len(members))
member_count = 0
for member in members:
member_count += 1
if csv:
member_statistics[member_count // 10] += member.name + "," + str(members[member]) + "\n"
else:
member_statistics[member_count // 10] += member.mention + ": " + str(members[member]) + "\n"
logger.debug("Successfully generated statistics") # Event log
if csv:
with open("channel_statistics.csv", "w", encoding="UTF-8") as csv:
channel_string = ""
for channel in channel_statistics:
channel_string += channel
csv.write(str(channel_string))
await message.channel.send(file=discord.File("channel_statistics.csv", filename=guild.name + " channel_statistics.csv"))
with open("member_statistics.csv", "w", encoding="UTF-8") as csv:
member_string = ""
for member in member_statistics:
member_string += member
csv.write(str(member_string))
await message.channel.send(file=discord.File("member_statistics.csv", filename=guild.name + " member_statistics.csv"))
else:
# Create and send general statistics embed
embed_general = discord.Embed(title="π General Statistics for " + guild.name, colour=self.get_server_colour(guild.id))
embed_general.add_field(name="Total Members", value=len([m for m in guild.members if not m.bot]))
embed_general.add_field(name="Total Bots", value=len([m for m in guild.members if m.bot]))
embed_general.add_field(name="Total Channels", value=len(guild.text_channels))
birth = guild.created_at
embed_general.add_field(name="Server Birth", value=str(birth.day) + "." + str(birth.month) + "." + str(birth.year))
embed_general.add_field(name="Total Messages", value=total_messages)
embed_general.set_footer(text="Statistics updated β’ " + date.today().strftime("%d/%m/%Y"), icon_url=guild.icon_url_as(size=128))
await message.channel.send(embed=embed_general)
# Create and send channel statistics embed
embed_channel = discord.Embed(title="π Channel Statistics for " + guild.name, colour=self.get_server_colour(guild.id))
for x in range(len(channel_statistics) // 10 + 1):
# print("------\nChannels in set:\n" + str(channel_statistics[x]))
logger.debug("------\nChannels in set:\n" + str(channel_statistics[x]))
embed_channel.add_field(name="Channels", value=str(channel_statistics[x]))
embed_channel.set_footer(text="Statistics updated β’ " + date.today().strftime("%d/%m/%Y"), icon_url=guild.icon_url_as(size=128))
await message.channel.send(embed=embed_channel)
# Create and send members statistics embed
embed_member = discord.Embed(title="π Member Statistics for " + guild.name, colour=self.get_server_colour(guild.id))
for x in range(len(member_statistics) // 10 + 1):
embed_member.add_field(name="Members", value=str(member_statistics[x]))
embed_member.set_footer(text="Statistics updated β’ " + date.today().strftime("%d/%m/%Y"), icon_url=guild.icon_url_as(size=128))
await message.channel.send(embed=embed_member)
except discord.errors.HTTPException as exception:
logger.error("Error to send statistics. Exception: " + str(exception)) # Event log
"""await message.channel.send("Error: Something went wrong on our side...")
await message.channel.send("Trying alternative")
embed_channel_stats = discord.Embed(title="π Channel statistics for " + guild.name, colour=0xffc000)
if len(channel_statistics) <= 1024:
embed_channel_stats.add_field(name="Channels", value=str(channel_statistics))
else:
for x in range(len(channel_statistics)//1024):
embed_channel_stats.add_field(name="Channel stats prt " + str(x + 1), value=channel_statistics[0][x*1024:(x + 1)*1024])
i = x
embed_channel_stats.add_field(name="Channel stats prt " + str(i + 1), value=channel_statistics[0][(i + 1)*1024:])
print(channel_statistics)
await message.channel.send(embed=embed_channel_stats)
embed_member_stats = discord.Embed(title="π Member statistics for " + guild.name, colour=0xffc000)
if len(member_statistics) <= 1024:
embed_member_stats.add_field(name="Members", value=str(member_statistics))
else:
for x in range(len(member_statistics) // 1024):
embed_member_stats.add_field(name="Member stats prt " + str(x + 1), value=member_statistics[0][x:(x + 1) * 1024])
i = x
embed_member_stats.add_field(name="Member stats prt " + str(i + 1), value=member_statistics[0][(i + 1) * 1024:])
print(member_statistics)
await message.channel.send(embed=embed_member_stats)"""
except Exception as exception:
logger.error("Failed to generate or send statistics. Exception: " + str(exception)) # Event log
await message.channel.send("Error: Something went wrong on our side...")
await waiting_message.delete()
# Purge Command
if message.content.startswith("purge"):
logger.info("`purge` called by " + message.author.name) # Event log
argument = message.content[len("purge "):]
number = int(argument)
purge_message = await message.channel.send("React with π to confirm")
self.purge_messages[purge_message.id] = number
# Poll command
if message.content.startswith("poll"):
"""ERRORS TO TEST FOR: DONE
- Duplicate emojis
- Custom emojis
- Duplicate custom emojis
THINGS TO FIX:
- Standardise datetime format - REMOVED INSTEAD
- Remove regex secretly. IGNORE THIS!
- Trailing newlines at the end of embed - SEEMS TO BE FIXED
"""
logger.info("`poll` called by " + message.author.name) # Event log
# Delete the command message
await message.delete()
# !!! Clunky and breakable
argument_string = message.content[len("poll "):]
if len(argument_string) < 2:
logger.debug("Poll command had no viable arguments - cancelled")
return
arguments = re.split("\,\s|\,", argument_string) # Replace with arguments = argument.split(", ")
candidates = {} # Dictionary of candidates that can be voted for
candidates_string = ""
# Embed
title = discord.Embed.Empty
colour = self.get_server_colour(guild.id)
# Config
winner = "highest"
anonymous = False
try:
# Analyse argument
for argument in arguments:
argument = argument.strip()
argument = argument.split("=")
# print("Argument 0, 1:", argument[0], argument[1])
poll_time = str(datetime.now())
if argument[0] == "title":
title = argument[1]
elif argument[0] == "colour":
try:
colour = int(argument[1][-6:], 16)
except ValueError:
if argument[1] in colours:
colour = colours[argument[1]]
elif argument[0] == "winner":
winner = argument[1]
elif argument[0] == "anonymous" or argument[0] == "anon":
if argument[1].lower() == "true":
anonymous = True
else:
emoji = argument[1].rstrip()
if not (emoji in candidates):
candidates[emoji] = argument[0]
candidates_string += argument[1] + " - " + argument[0] + "\n"
else:
logger.debug("Duplicate emoji in poll detected")
await message.channel.send("Please only use an emoji once per poll")
except Exception as exception:
logger.error(f"Failed to read poll command. Exception \"{type(exception).__name__}\" : {exception.args[0]}\n")
await message.channel.send("The poll command could not be read. Please format as `\"title\" = question, \"option\" = emoji, (\"anonymous\" = True/False)`")
# Create and send poll embed
embed_poll = discord.Embed(title=title, description=candidates_string, colour=colour)
if anonymous: # Makes embed with buttons for anonymous voting
# Adds buttons
buttons = []
for candidate in candidates:
buttons.append(create_button(style=ButtonStyle.blue, label=candidates[candidate], emoji=candidate, custom_id="poll:" + candidate))
components = populate_actionrows(buttons) # Puts buttons in to rows of 5 or less
poll_message = await message.channel.send(embed=embed_poll, components=components)
# Setup candidates dict for recording votes so people can't vote multiple times
#for candidate in candidates:
# candidates[candidate] = {"name": candidates[candidate], "voters": []}
candidates = {}
else: # Makes embed with reactions for open voting
poll_message = await message.channel.send(embed=embed_poll)
# Adds reactions
for candidate in candidates:
# print("Candidate: " + str(candidate))
try:
await poll_message.add_reaction(candidate)
except discord.errors.HTTPException:
await poll_message.channel.send("Please format as `title = question, \"option\" = emoji, (anonymous = True/False)`")
await poll_message.delete()
self.poll[str(message.guild.id)].update(
{
str(poll_message.id): {
"title": title,
"voters": candidates,
"config":
{
"winner": winner,
"anonymous": anonymous,
"multi": True
}
}
}
)
logger.debug(f"New poll:{self.poll[str(message.guild.id)]}")