-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
1403 lines (1147 loc) · 55.7 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = ""
import responses
import globalInfos
import blueprints
import operationGraph
import utils
import gameInfos
import researchViewer
import guildSettings
import shapeCodeGenerator
import autoMessages
import shapeViewer
import discord
import json
import sys
import traceback
import io
import typing
import datetime
async def globalLogMessage(message:str,sendInCodeBlock:bool=False) -> None:
if globalInfos.GLOBAL_LOG_CHANNEL is None:
print(message)
else:
logChannel = client.get_channel(globalInfos.GLOBAL_LOG_CHANNEL)
await logChannel.send(**getCommandResponse(
message,None,logChannel.guild,True,
("```","```") if sendInCodeBlock else ("","")
))
async def globalLogError() -> None:
await globalLogMessage(("".join(traceback.format_exception(*sys.exc_info())))[:-1],True)
async def useShapeViewer(userMessage:str,sendErrors:bool) -> tuple[bool,str,tuple[discord.File,int]|None]:
try:
response = responses.handleResponse(userMessage)
msgParts = []
hasErrors = False
file = None
if response is None:
if sendErrors:
msgParts.append("No potential shape codes detected")
else:
response, hasInvalid, errorMsgs = response
if hasInvalid:
hasErrors = True
if sendErrors:
msgParts.append("**Error messages :**\n"+"\n".join(f"- {msg}" for msg in errorMsgs))
if response is not None:
(image, imageSize), spoiler, resultingShapeCodes, viewer3dLinks = response
file = discord.File(image,"shapes.png",spoiler=spoiler)
if resultingShapeCodes is not None:
msgParts.append(
"**Resulting shape codes :**\n"+
"\n".join(
" ".join(f"{{{code}}}" for code in codeGroup)
for codeGroup in discord.utils.as_chunks(resultingShapeCodes,globalInfos.SHAPES_PER_ROW)
)
)
if viewer3dLinks is not None:
msgParts.append(
"**3D viewer links :**\n"+
"\n".join(
" ".join(f"{{{link}}}" for link in linkGroup)
for linkGroup in discord.utils.as_chunks(viewer3dLinks,globalInfos.SHAPES_PER_ROW)
)
)
responseMsg = "\n\n".join(msgParts)
return hasErrors, responseMsg, (None if file is None else (file, imageSize))
except Exception as e:
await globalLogError()
return True, f"{globalInfos.UNKNOWN_ERROR_TEXT} ({e.__class__.__name__})" if sendErrors else "", None
def getCurrentTime() -> datetime.datetime:
return discord.utils.utcnow()
def isDisabledInGuild(guildId:int|None) -> bool:
if globalInfos.RESTRICT_TO_GUILDS is None:
return False
if guildId in globalInfos.RESTRICT_TO_GUILDS:
return False
return True
def exitCommandWithoutResponse(interaction:discord.Interaction) -> bool:
if globalPaused:
return True
if isDisabledInGuild(interaction.guild_id):
return True
return False
async def isInCooldown(userId:int,guildId:int|None) -> bool:
lastTriggered = usageCooldownLastTriggered.get((userId,guildId))
if lastTriggered is None:
return False
if guildId is None:
cooldown = globalInfos.NO_GUILD_USAGE_COOLDOWN_SECONDS
else:
cooldown = (await guildSettings.getGuildSettings(guildId))["usageCooldown"]
delta = getCurrentTime() - lastTriggered
if delta < datetime.timedelta(seconds=cooldown):
return True
return False
def setUserCooldown(userId:int,guildId:int|None) -> None:
usageCooldownLastTriggered[(userId,guildId)] = getCurrentTime()
class PermissionLvls:
PUBLIC_FEATURE = 0
REACTION = 1
PRIVATE_FEATURE = 2
ADMIN = 3
OWNER = 4
async def hasPermission(requestedLvl:int,*,message:discord.Message|None=None,interaction:discord.Interaction|None=None) -> bool:
IGNORE_MEMBERS_BEING_USERS = [
1008776202191634432 # automod
]
if message is not None:
userId = message.author.id
channelId = message.channel.id
if message.guild is None:
guildId = None
else:
if type(message.author) == discord.User:
if userId in IGNORE_MEMBERS_BEING_USERS:
return False
raise ValueError(
f"Author ({userId} {message.author.mention})"
f"of message ({message.id} {message.jump_url} )"
f"is not a member despite being in a guild ({message.guild.id} {message.guild.name})"
)
guildId = message.guild.id
userRoles = message.author.roles[1:]
adminPerm = message.author.guild_permissions.administrator
elif interaction is not None:
userId = interaction.user.id
channelId = interaction.channel_id
guildId = interaction.guild_id
if interaction.guild is not None:
if type(interaction.user) == discord.User:
if userId in IGNORE_MEMBERS_BEING_USERS:
return False
raise ValueError(
f"Author ({userId} {interaction.user.mention})"
f"of interaction (in channel {channelId})"
f"is not a member despite being in a guild ({guildId} {interaction.guild.name})"
)
userRoles = interaction.user.roles[1:]
adminPerm = interaction.user.guild_permissions.administrator
else:
raise ValueError("No message or interaction in 'hasPermission' function")
async def inner() -> bool:
if (guildId is None) and (requestedLvl == PermissionLvls.ADMIN):
return False
if userId in globalInfos.OWNER_USERS:
return True
else:
if requestedLvl == PermissionLvls.OWNER:
return False
if globalPaused:
return False
if isDisabledInGuild(guildId):
return False
if guildId is None:
if await isInCooldown(userId,guildId):
return False
return requestedLvl < PermissionLvls.ADMIN
curGuildSettings = await guildSettings.getGuildSettings(guildId)
if adminPerm:
isAdmin = True
else:
isAdmin = False
adminRoles = curGuildSettings["adminRoles"]
for role in userRoles:
if role.id in adminRoles:
isAdmin = True
break
if isAdmin:
if requestedLvl <= PermissionLvls.ADMIN:
return True
else:
if requestedLvl == PermissionLvls.ADMIN:
return False
if await isInCooldown(userId,guildId):
return False
if requestedLvl == PermissionLvls.PRIVATE_FEATURE:
return True
if curGuildSettings["paused"]:
return False
if requestedLvl == PermissionLvls.REACTION:
return True
# requestedLvl = public feature
if curGuildSettings["restrictToChannel"] not in (None,channelId):
return False
restrictToRoles = curGuildSettings["restrictToRoles"]
if restrictToRoles == []:
return True
restrictToRolesInverted = curGuildSettings["restrictToRolesInverted"]
for role in userRoles:
roleInRestrictToRoles = role.id in restrictToRoles
if restrictToRolesInverted and (not roleInRestrictToRoles):
return True
if (not restrictToRolesInverted) and roleInRestrictToRoles:
return True
return False
toReturn = await inner()
if toReturn:
setUserCooldown(userId,guildId)
return toReturn
def msgToFile(msg:str,filename:str,guild:discord.Guild|None) -> discord.File|None:
msgBytes = msg.encode()
if isFileTooBig(len(msgBytes),guild):
return None
return discord.File(io.BytesIO(msgBytes),filename)
async def decodeAttachment(file:discord.Attachment) -> str|None:
if file.size > globalInfos.MAX_DOWNLOAD_TEXT_FILE_SIZE:
return None
try:
fileBytes = await file.read()
except (discord.HTTPException,discord.NotFound):
return None
try:
fileStr = fileBytes.decode()
except UnicodeDecodeError:
return None
return fileStr
def isFileTooBig(fileSize:int,guild:discord.Guild|None) -> bool:
if guild is None:
return fileSize > discord.utils.DEFAULT_FILE_SIZE_LIMIT_BYTES
return fileSize > guild.filesize_limit
def detectBPVersion(potentialBPCodes:list[str]) -> list[str|int]|None:
versions = []
for bp in potentialBPCodes:
try:
version = blueprints.getBlueprintVersion(bp)
except blueprints.BlueprintError:
continue
versionReaction = gameInfos.versions.versionNumToReactions(version)
if versionReaction is None:
continue
versions.append(versionReaction)
if len(versions) != 1:
return None
return versions[0]
def safenString(string:str) -> str:
return discord.utils.escape_mentions(string)
async def getBPFromStringOrFile(string:str|None,file:discord.Attachment|None) -> str|None:
if file is None:
toReturn = string
else:
toReturn = await decodeAttachment(file)
if toReturn is None:
return None
return toReturn.strip()
def getCommandResponse(text:str,file:tuple[discord.File,int]|None,guild:discord.Guild|None,public:bool,
notInFileFormat:tuple[str,str]=("","")) -> dict[str,str|discord.File]:
kwargs = {}
if len(notInFileFormat[0])+len(text)+len(notInFileFormat[1]) > globalInfos.MESSAGE_MAX_LENGTH:
if file is None:
textFile = msgToFile(text,"response.txt",guild)
if textFile is None:
kwargs["content"] = globalInfos.MESSAGE_TOO_LONG_TEXT
else:
kwargs["file"] = textFile
else:
kwargs["content"] = globalInfos.MESSAGE_TOO_LONG_TEXT
else:
text = notInFileFormat[0] + text + notInFileFormat[1]
if public:
text = safenString(text)
kwargs["content"] = text
if file is not None:
if isFileTooBig(file[1],guild):
kwargs["file"] = discord.File(globalInfos.FILE_TOO_BIG_PATH)
else:
kwargs["file"] = file[0]
return kwargs
# port of sbe's antispam feature with difference of being separated per server and possiblity of sending an alert when triggered
async def antiSpam(message:discord.Message) -> None|bool:
global antiSpamLastMessages
async def sendAlert() -> None:
curAlertChannel = curGuildSettings["antispamAlertChannel"]
if curAlertChannel is None:
return
curAlertChannel = client.get_channel(curAlertChannel)
if curAlertChannel is None:
return
alertMsg = f"{message.author.mention} triggered the antispam :"
msgContentFile = msgToFile(msgContent,"messageContent.txt",curAlertChannel.guild)
if msgContentFile is None:
alertMsg += " <couldn't put message content in a file>"
await curAlertChannel.send(alertMsg,file=msgContentFile)
if globalPaused:
return
if message.author.bot:
return
if message.guild is None:
return
if isDisabledInGuild(message.guild.id):
return
curGuildSettings = await guildSettings.getGuildSettings(message.guild.id)
if not curGuildSettings["antispamEnabled"]:
return
userId = message.author.id
guildId = message.guild.id
curGuildMember = (userId,guildId)
msgContent = message.content
curTime = getCurrentTime()
for guildMember in list(antiSpamLastMessages.keys()):
if (curTime - antiSpamLastMessages[guildMember]["timestamp"]) > datetime.timedelta(seconds=globalInfos.ANTISPAM_TIME_INTERVAL_SECONDS):
antiSpamLastMessages.pop(guildMember)
curInfo = antiSpamLastMessages.get(curGuildMember)
if (curInfo is not None) and (curInfo["content"] == msgContent):
curInfo["messages"].append(message)
curInfo["count"] += 1
curInfo["timestamp"] = curTime
if curInfo["count"] >= globalInfos.ANTISPAM_MSG_COUNT_TRESHOLD:
messages:list[discord.Message] = curInfo["messages"]
curInfo["messages"] = []
if not message.author.is_timed_out():
try:
await message.author.timeout(
datetime.timedelta(seconds=globalInfos.ANTISPAM_TIMEOUT_SECONDS),
reason=f"antispam: {msgContent}" # seems like no errors happen if the reason string is more than the 512 char limit in discord's UI
)
for msg in messages: # port difference : only delete if permission to timeout
await msg.delete()
except (discord.Forbidden,discord.NotFound) as e:
await globalLogMessage(
f"Failed to timeout user ({message.author.id}) or delete messages for antispam ({e.__class__.__name__})"
)
else:
await sendAlert()
return True
return
newInfo = {
"content" : msgContent,
"messages" : [message],
"count" : 1,
"timestamp" : curTime
}
antiSpamLastMessages[curGuildMember] = newInfo
async def concatMsgContentAndAttachments(content:str,attachments:list[discord.Attachment]) -> str:
for file in attachments:
fileContent = await decodeAttachment(file)
if fileContent is None:
continue
content += fileContent
return content
def getBPInfoText(blueprint:blueprints.Blueprint,advanced:bool) -> str:
def formatCounts(bp:blueprints.BuildingBlueprint|blueprints.IslandBlueprint|None,name:str) -> str:
output = f"\n**{name} counts :**\n"
if bp is None:
output += "None"
else:
if type(bp) == blueprints.BuildingBlueprint:
counts = bp.getBuildingCounts()
lines = []
for iv,bc in gameInfos.buildings.getCategorizedBuildingCounts(counts).items():
lines.append(f"- `{gameInfos.buildings.allInternalVariantLists[iv].title}` : `{utils.sepInGroupsNumber(sum(bc.values()))}`")
for b,c in bc.items():
lines.append(f" - `{b}` : `{utils.sepInGroupsNumber(c)}`")
output += "\n".join(lines)
else:
counts = bp.getIslandCounts()
output += "\n".join(f"- `{gameInfos.islands.allIslands[k].title}` : `{utils.sepInGroupsNumber(v)}`" for k,v in counts.items())
return output
versionTxt = gameInfos.versions.versionNumToText(blueprint.version,advanced)
if versionTxt is None:
versionTxt = "Unknown"
elif advanced:
versionTxt = f"[{', '.join(f'`{txt}`' for txt in versionTxt)}]"
else:
versionTxt = f"`{versionTxt}`"
bpTypeTxt = "Platform" if blueprint.type == blueprints.ISLAND_BP_TYPE else "Building"
try:
bpCost = f"`{utils.sepInGroupsNumber(blueprint.getCost())}`"
except blueprints.BlueprintError:
bpCost = f"<Failed to compute>"
responseParts = [[
f"Version : `{blueprint.version}` / {versionTxt}",
f"Blueprint type : `{bpTypeTxt}`",
f"Blueprint cost : {bpCost}",
f"Platform unit cost : `{utils.sepInGroupsNumber(blueprint.getIslandUnitCost())}`"
]]
if blueprint.buildingBP is not None:
buildingSize = blueprint.buildingBP.getSize()
responseParts.append([
f"Building count : `{utils.sepInGroupsNumber(blueprint.buildingBP.getBuildingCount())}`",
f"Building size : `{buildingSize.width}`x`{buildingSize.height}`x`{buildingSize.depth}`",
f"Building tiles : `{utils.sepInGroupsNumber(blueprint.buildingBP.getTileCount())}`"
])
if blueprint.islandBP is not None:
islandSize = blueprint.islandBP.getSize()
responseParts.append([
f"Platform count : `{utils.sepInGroupsNumber(blueprint.islandBP.getIslandCount())}`",
f"Platform size : `{islandSize.width}`x`{islandSize.height}`",
f"Platform tiles : `{utils.sepInGroupsNumber(blueprint.islandBP.getTileCount())}`"
])
blueprintIcons = (blueprint.buildingBP if blueprint.type == blueprints.BUILDING_BP_TYPE else blueprint.islandBP).getValidIcons()
blueprintIconsStr = []
for icon in blueprintIcons:
if icon.type == "empty":
blueprintIconsStr.append("<empty>")
elif icon.type == "icon":
blueprintIconsStr.append(f"`{icon.value}`")
else:
blueprintIconsStr.append(f"{{{icon.value}}}")
responseParts.append([
f"Icons : {', '.join(blueprintIconsStr)}"
])
finalOutput = "\n".join(", ".join(part) for part in responseParts)
if advanced:
finalOutput += formatCounts(blueprint.buildingBP,"Building")
finalOutput += formatCounts(blueprint.islandBP,"Platform")
return finalOutput
def getAccessBPTextAndFiles(
blueprint:blueprints.Blueprint,
blueprintCode:str,
guild:discord.Guild|None,
formatConversionFiles:bool
) -> tuple[str,list[discord.File]]:
infoText = getBPInfoText(blueprint,False)
infoTextFormatted = "**Blueprint Infos :**\n" + "\n".join(f"> {l}" for l in infoText.split("\n"))
bpCodeLinkSafe = blueprintCode
for old,new in globalInfos.LINK_CHAR_REPLACEMENT.items():
bpCodeLinkSafe = bpCodeLinkSafe.replace(old,new)
bpCode3dViewLink = f"{globalInfos.BLUEPRINT_3D_VIEWER_LINK_START}{bpCodeLinkSafe}"
bpCode3dViewLinkFormatted = f"**Actions :**\n> [[View in 3D]](<{bpCode3dViewLink}>)"
responseMsg = infoTextFormatted + "\n" + bpCode3dViewLinkFormatted
toCreateFiles:list[tuple[str,str]] = []
if len(responseMsg) > globalInfos.MESSAGE_MAX_LENGTH:
if len(infoTextFormatted) <= globalInfos.MESSAGE_MAX_LENGTH:
responseMsg = infoTextFormatted
toCreateFiles.append((bpCode3dViewLink,"3D viewer link.txt"))
elif len(bpCode3dViewLinkFormatted) <= globalInfos.MESSAGE_MAX_LENGTH:
responseMsg = bpCode3dViewLinkFormatted
toCreateFiles.append((infoText,"blueprint infos.txt"))
else:
responseMsg = ""
toCreateFiles.append(("\n".join([
"Blueprint Infos :",
infoText,
"3D Viewer Link :",
bpCode3dViewLink
]),"blueprint infos.txt"))
if formatConversionFiles:
toCreateFiles.append((blueprintCode,"blueprint.txt"))
toCreateFiles.append((blueprintCode,"blueprint.spz2bp"))
files = []
fileTooBig = False
for fileContent,fileName in toCreateFiles:
file = msgToFile(fileContent,fileName,guild)
if file is None:
fileTooBig = True
else:
files.append(file)
if fileTooBig:
files.append(discord.File(globalInfos.FILE_TOO_BIG_PATH))
return responseMsg, files
async def accessBlueprintCommandInnerPart(
interaction:discord.Interaction,
getBPCode:typing.Callable[[],typing.Coroutine[typing.Any,typing.Any,tuple[str,bool]]]
) -> None:
if exitCommandWithoutResponse(interaction):
return
async def inner() -> None:
nonlocal responseMsg, files
files = []
await interaction.response.defer(ephemeral=True)
if not await hasPermission(PermissionLvls.PRIVATE_FEATURE,interaction=interaction):
responseMsg = globalInfos.NO_PERMISSION_TEXT
return
toProcessBlueprint, bpCodeValid = await getBPCode()
if not bpCodeValid:
responseMsg = toProcessBlueprint
return
try:
decodedBP = blueprints.decodeBlueprint(toProcessBlueprint)
except blueprints.BlueprintError as e:
responseMsg = f"Error while decoding blueprint : {e}"
return
responseMsg, files = getAccessBPTextAndFiles(decodedBP,toProcessBlueprint,interaction.guild,True)
responseMsg:str; files:list[discord.File]
await inner()
await interaction.followup.send(responseMsg,files=files)
async def getSinglePotentialBPCodeInMessage(message:discord.Message) -> str|None:
potentialBPCodes = blueprints.getPotentialBPCodesInString(
await concatMsgContentAndAttachments(message.content,message.attachments)
)
if len(potentialBPCodes) != 1:
return None
return potentialBPCodes[0]
##################################################
def runDiscordBot() -> None:
global client, msgCommandMessages
client = discord.Client(intents=discord.Intents.all(),activity=discord.Game("shapez 2"))
tree = discord.app_commands.CommandTree(client)
with open(globalInfos.MSG_COMMAND_MESSAGES_PATH,encoding="utf-8") as f:
msgCommandMessages = json.load(f)
@client.event
async def on_ready() -> None:
global executedOnReady
if not executedOnReady:
await tree.sync()
print(f"{client.user} is now running")
executedOnReady = True
@client.event
async def on_message(message:discord.Message) -> None:
try:
if message.author == client.user:
return
if (await antiSpam(message)) is True:
return
reactedToBPCodeInMsg = False
publicPerm = await hasPermission(PermissionLvls.PUBLIC_FEATURE,message=message)
if publicPerm:
# shape viewer
hasErrors, responseMsg, file = await useShapeViewer(message.content,False)
if hasErrors:
await message.add_reaction(globalInfos.INVALID_SHAPE_CODE_REACTION)
if (responseMsg != "") or (file is not None):
await message.channel.send(**getCommandResponse(responseMsg,file,message.guild,True))
# automatic messages
autoMsgResult = await autoMessages.checkMessage(message)
if autoMsgResult != []:
responseMsg = "\n".join(autoMsgResult)
try:
await message.reply(safenString(responseMsg),mention_author=False)
except discord.HTTPException: # error raised when og message was deleted
pass
# bp info message
async def bpInfoMessageLogic() -> None:
nonlocal reactedToBPCodeInMsg
if message.guild is None:
return
curBlueprintsChannels = (await guildSettings.getGuildSettings(message.guild.id))["blueprintsChannels"]
if type(message.channel) == discord.Thread:
if message.channel.parent_id not in curBlueprintsChannels:
return
else:
if message.channel.id not in curBlueprintsChannels:
return
potentialBP = await getSinglePotentialBPCodeInMessage(message)
if potentialBP is None:
return
try:
decodedBP = blueprints.decodeBlueprint(potentialBP)
except blueprints.BlueprintError:
return
responseMsg, files = getAccessBPTextAndFiles(decodedBP,potentialBP,message.guild,False)
try:
await message.reply(safenString(responseMsg),files=files,mention_author=False)
except discord.HTTPException:
return
reactedToBPCodeInMsg = True
await bpInfoMessageLogic()
if publicPerm or (await hasPermission(PermissionLvls.REACTION,message=message)):
# equivalent of a /ping
if client.user.mention in message.content:
try:
await message.add_reaction(globalInfos.BOT_MENTIONED_REACTION)
except discord.HTTPException:
pass
# blueprint version reaction
if not reactedToBPCodeInMsg:
msgContent = await concatMsgContentAndAttachments(message.content,message.attachments)
bpReactions = detectBPVersion(blueprints.getPotentialBPCodesInString(msgContent))
if bpReactions is not None:
for reaction in bpReactions:
if type(reaction) == int:
reaction = client.get_emoji(reaction)
try:
await message.add_reaction(reaction)
except discord.HTTPException:
pass
except Exception:
await globalLogError()
@tree.error
async def on_error(interaction:discord.Interaction,error:discord.app_commands.AppCommandError) -> None:
await globalLogError()
responseMsg = f"{globalInfos.UNKNOWN_ERROR_TEXT} ({error.__cause__.__class__.__name__})"
if interaction.response.is_done():
await interaction.followup.send(responseMsg)
else:
await interaction.response.send_message(responseMsg,ephemeral=True)
# owner only commands
@tree.command(name="stop",description=f"{globalInfos.OWNER_ONLY_BADGE} Stops the bot")
async def stopCommand(interaction:discord.Interaction) -> None:
if await hasPermission(PermissionLvls.OWNER,interaction=interaction):
try:
await interaction.response.send_message("Stopping bot",ephemeral=True)
except Exception:
print("Error while attempting to comfirm bot stopping")
await client.close()
else:
if exitCommandWithoutResponse(interaction):
return
await interaction.response.send_message(globalInfos.NO_PERMISSION_TEXT,ephemeral=True)
@tree.command(name="global-pause",description=f"{globalInfos.OWNER_ONLY_BADGE} Globally pauses the bot")
async def globalPauseCommand(interaction:discord.Interaction) -> None:
global globalPaused
if await hasPermission(PermissionLvls.OWNER,interaction=interaction):
globalPaused = True
responseMsg = "Bot is now globally paused"
else:
if exitCommandWithoutResponse(interaction):
return
responseMsg = globalInfos.NO_PERMISSION_TEXT
await interaction.response.send_message(responseMsg,ephemeral=True)
@tree.command(name="global-unpause",description=f"{globalInfos.OWNER_ONLY_BADGE} Globally unpauses the bot")
async def globalUnpauseCommand(interaction:discord.Interaction) -> None:
global globalPaused
if await hasPermission(PermissionLvls.OWNER,interaction=interaction):
globalPaused = False
responseMsg = "Bot is now globally unpaused"
else:
if exitCommandWithoutResponse(interaction):
return
responseMsg = globalInfos.NO_PERMISSION_TEXT
await interaction.response.send_message(responseMsg,ephemeral=True)
# admin only commands
class RegisterCommandType:
SINGLE_CHANNEL = "singleChannel"
ROLE_LIST = "roleList"
BOOL_VALUE = "boolValue"
def registerAdminCommand(type_:str,cmdName:str,guildSettingsKey:str,cmdDesc:str="") -> None:
if type_ == RegisterCommandType.SINGLE_CHANNEL:
@tree.command(name=cmdName,description=f"{globalInfos.ADMIN_ONLY_BADGE} {cmdDesc}")
@discord.app_commands.describe(channel="The channel. Don't provide this parameter to clear it")
async def generatedCommand(interaction:discord.Interaction,channel:discord.TextChannel|discord.Thread|None=None) -> None:
if exitCommandWithoutResponse(interaction):
return
if await hasPermission(PermissionLvls.ADMIN,interaction=interaction):
if channel is None:
setParamTo = None
responseMsgEnd = "cleared"
else:
setParamTo = channel.id
responseMsgEnd = f"set to {channel.mention}"
await guildSettings.setGuildSetting(interaction.guild_id,guildSettingsKey,setParamTo)
responseMsg = f"'{guildSettingsKey}' parameter {responseMsgEnd}"
else:
responseMsg = globalInfos.NO_PERMISSION_TEXT
await interaction.response.send_message(responseMsg,ephemeral=True)
elif type_ == RegisterCommandType.BOOL_VALUE:
@tree.command(name=cmdName,description=f"{globalInfos.ADMIN_ONLY_BADGE} {cmdDesc}")
async def generatedCommand(interaction:discord.Interaction,value:bool) -> None:
if exitCommandWithoutResponse(interaction):
return
if await hasPermission(PermissionLvls.ADMIN,interaction=interaction):
await guildSettings.setGuildSetting(interaction.guild_id,guildSettingsKey,value)
responseMsg = f"'{guildSettingsKey}' parameter has been set to {value}"
else:
responseMsg = globalInfos.NO_PERMISSION_TEXT
await interaction.response.send_message(responseMsg,ephemeral=True)
elif type_ == RegisterCommandType.ROLE_LIST:
@tree.command(name=cmdName,description=f"{globalInfos.ADMIN_ONLY_BADGE} Modifys the '{guildSettingsKey}' list")
@discord.app_commands.describe(role="Only provide this if using 'add' or 'remove' subcommand")
async def generatedCommand(interaction:discord.Interaction,
operation:typing.Literal["add","remove","view","clear"],role:discord.Role|None=None) -> None:
if exitCommandWithoutResponse(interaction):
return
if await hasPermission(PermissionLvls.ADMIN,interaction=interaction):
roleList = (await guildSettings.getGuildSettings(interaction.guild_id))[guildSettingsKey].copy()
if (operation in ("add","remove")) and (role is None):
responseMsg = "A role must be provided when using the 'add' or 'remove' subcommand"
elif operation == "add":
if len(roleList) >= globalInfos.MAX_ROLES_PER_LIST:
responseMsg = f"Can't have more than {globalInfos.MAX_ROLES_PER_LIST} roles per list"
else:
if role.id in roleList:
responseMsg = f"{role.mention} is already in the list"
else:
roleList.append(role.id)
await guildSettings.setGuildSetting(interaction.guild_id,guildSettingsKey,roleList)
responseMsg = f"Added {role.mention} to the '{guildSettingsKey}' list"
elif operation == "remove":
if role.id in roleList:
roleList.remove(role.id)
await guildSettings.setGuildSetting(interaction.guild_id,guildSettingsKey,roleList)
responseMsg = f"Removed {role.mention} from the '{guildSettingsKey}' list"
else:
responseMsg = "Role is not present in the list"
elif operation == "view":
roleList = [interaction.guild.get_role(r) for r in roleList]
if roleList== []:
responseMsg = "Empty list"
else:
responseMsg = "\n".join(f"- {role.mention} : {role.id}" for role in roleList)
elif operation == "clear":
await guildSettings.setGuildSetting(interaction.guild_id,guildSettingsKey,[])
responseMsg = f"'{guildSettingsKey}' list cleared"
else:
responseMsg = "Unknown operation"
else:
responseMsg = globalInfos.NO_PERMISSION_TEXT
await interaction.response.send_message(responseMsg,ephemeral=True)
else:
raise ValueError(f"Unknown type : '{type_}' in 'registerAdminCommand' function")
registerAdminCommand(
RegisterCommandType.SINGLE_CHANNEL,
"restrict-to-channel",
"restrictToChannel",
"Restricts the use of the bot in public messages to one channel only"
)
registerAdminCommand(
RegisterCommandType.SINGLE_CHANNEL,
"set-antispam-alert-channel",
"antispamAlertChannel",
"Sets the channel for alerting when the antispam is triggered"
)
registerAdminCommand(
RegisterCommandType.BOOL_VALUE,
"restrict-to-roles-set-inverted",
"restrictToRolesInverted",
"Sets if the restrict to roles list should be inverted"
)
registerAdminCommand(
RegisterCommandType.BOOL_VALUE,
"set-paused",
"paused",
"Sets if the bot should be paused on this server"
)
registerAdminCommand(
RegisterCommandType.BOOL_VALUE,
"set-antispam-enabled",
"antispamEnabled",
"Sets if the antispam feature should be enabled on this server"
)
registerAdminCommand(RegisterCommandType.ROLE_LIST,"admin-roles","adminRoles")
registerAdminCommand(RegisterCommandType.ROLE_LIST,"restrict-to-roles","restrictToRoles")
@tree.command(name="usage-cooldown",description=f"{globalInfos.ADMIN_ONLY_BADGE} Sets the cooldown for usage of the bot publicly and privatley")
@discord.app_commands.describe(cooldown="The cooldown in seconds")
async def usageCooldownCommand(interaction:discord.Interaction,cooldown:int) -> None:
if exitCommandWithoutResponse(interaction):
return
if await hasPermission(PermissionLvls.ADMIN,interaction=interaction):
if cooldown < 0:
responseMsg = "Cooldown value can't be negative"
else:
try:
datetime.timedelta(seconds=cooldown)
except OverflowError:
responseMsg = "Cooldown value too big"
else:
await guildSettings.setGuildSetting(interaction.guild_id,"usageCooldown",cooldown)
responseMsg = f"'usageCooldown' parameter has been set to {cooldown}"
else:
responseMsg = globalInfos.NO_PERMISSION_TEXT
await interaction.response.send_message(responseMsg,ephemeral=True)
# public commands
@tree.command(name="view-shapes",description="View shapes, useful if the bot says a shape code is invalid and you want to know why")
@discord.app_commands.describe(message="The message like you would normally send it")
async def viewShapesCommand(interaction:discord.Interaction,message:str) -> None:
if exitCommandWithoutResponse(interaction):
return
await interaction.response.defer(ephemeral=True)
if await hasPermission(PermissionLvls.PRIVATE_FEATURE,interaction=interaction):
_, responseMsg, file = await useShapeViewer(message,True)
else:
responseMsg = globalInfos.NO_PERMISSION_TEXT
file = None
await interaction.followup.send(**getCommandResponse(responseMsg,file,interaction.guild,False))
@tree.command(name="change-blueprint-version",description="Change a blueprint's version")
@discord.app_commands.describe(
blueprint=globalInfos.SLASH_CMD_BP_PARAM_DESC,
version=f"The blueprint version number (latest : {gameInfos.versions.LATEST_GAME_VERSION})",
blueprint_file=globalInfos.SLASH_CMD_BP_FILE_PARAM_DESC,
advanced="Whether or not to fully decode and encode the blueprint"
)
async def changeBlueprintVersionCommand(
interaction:discord.Interaction,
blueprint:str,
version:int,
blueprint_file:discord.Attachment|None=None,
advanced:bool=False
) -> None:
if exitCommandWithoutResponse(interaction):
return
async def runCommand() -> None:
nonlocal responseMsg, noErrors
noErrors = False
if not await hasPermission(PermissionLvls.PRIVATE_FEATURE,interaction=interaction):
responseMsg = globalInfos.NO_PERMISSION_TEXT
return
toProcessBlueprint = await getBPFromStringOrFile(blueprint,blueprint_file)
if toProcessBlueprint is None:
responseMsg = "Error while processing file"
return
try:
if advanced:
decodedBP = blueprints.decodeBlueprint(toProcessBlueprint)
decodedBP.version = version
responseMsg = blueprints.encodeBlueprint(decodedBP)
else:
responseMsg = blueprints.changeBlueprintVersion(toProcessBlueprint,version)
noErrors = True
except blueprints.BlueprintError as e:
responseMsg = f"Error happened : {e}"
responseMsg:str; noErrors:bool
await runCommand()
await interaction.response.send_message(ephemeral=True,**getCommandResponse(responseMsg,None,interaction.guild,False,
("```","```") if noErrors else ("","")))
@tree.command(name="member-count",description="Display the number of members in this server")
async def memberCountCommand(interaction:discord.Interaction) -> None:
if exitCommandWithoutResponse(interaction):
return
def fillText(text:str,desiredLen:int,align:str) -> str:
if align == "l":
return text.ljust(desiredLen)
if align == "r":