forked from DigitalPulseSoftware/NotaBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot_modules.lua
1152 lines (976 loc) · 33.4 KB
/
bot_modules.lua
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
-- Copyright (C) 2018 Jérôme Leclercq
-- This file is part of the "Not a Bot" application
-- For conditions of distribution and use, see copyright notice in LICENSE
local enums = discordia.enums
local fs = require("coro-fs")
local wrap = coroutine.wrap
local isReady = false
local function code(str)
return string.format('```\n%s```', str)
end
-- Maps event name to function to retrieve its guild
local discordiaEvents = {
["channelCreate"] = function (channel) return channel.guild end,
["channelDelete"] = function (channel) return channel.guild end,
["channelUpdate"] = function (channel) return channel.guild end,
["debug"] = function (message) end,
["emojisUpdate"] = function (guild) return guild end,
["error"] = function (message) end,
["guildAvailable"] = function (guild) return guild end,
["guildCreate"] = function (guild) return guild end,
["guildDelete"] = function (guild) return guild end,
["guildUnavailable"] = function (guild) return guild end,
["guildUpdate"] = function (guild) return guild end,
["heartbeat"] = function (shardId, latency) end,
["info"] = function (message) end,
["memberJoin"] = function (member) return member.guild end,
["memberLeave"] = function (member) return member.guild end,
["memberUpdate"] = function (member) return member.guild end,
["messageCreate"] = function (message) return message.guild end,
["messageDelete"] = function (message) return message.guild end,
["messageDeleteUncached"] = function (channel, messageId) return channel.guild end,
["messageUpdate"] = function (message) return message.guild end,
["messageUpdateUncached"] = function (channel, messageId) return channel.guild end,
["pinsUpdate"] = function (channel) return channel.guild end,
["presenceUpdate"] = function (member) return member.guild end,
["raw"] = function (string) end,
["reactionAdd"] = function (reaction, userId) return reaction.message.guild end,
["reactionAddUncached"] = function (channel, messageId, hash, userId) return channel.guild end,
["reactionRemove"] = function (reaction, userId) return reaction.message.guild end,
["reactionRemoveUncached"] = function (channel, messageId, hash, userId) return channel.guild end,
["ready"] = function () end,
["recipientAdd"] = function (relationship) end,
["recipientRemove"] = function (relationship) end,
["relationshipAdd"] = function (relationship) end,
["relationshipRemove"] = function (relationship) end,
["relationshipUpdate"] = function (relationship) end,
["roleCreate"] = function (role) return role.guild end,
["roleDelete"] = function (role) return role.guild end,
["roleUpdate"] = function (role) return role.guild end,
["shardReady"] = function (shardId) end,
["shardResumed"] = function (shardId) end,
["typingStart"] = function (userId, channelId, timestamp, client)
local channel = client:getChannel(channelId)
if (not channel) then
return
end
return channel.guild
end,
["userBan"] = function (user, guild) return guild end,
["userUnban"] = function (user, guild) return guild end,
["userUpdate"] = function (user) end,
["voiceChannelJoin"] = function (member, channel) return channel.guild end,
["voiceChannelLeave"] = function (member, channel) return channel.guild end,
["voiceConnect"] = function (member) return member.guild end,
["voiceDisconnect"] = function (member) return member.guild end,
["voiceUpdate"] = function (member) return member.guild end,
["warning"] = function (message) end,
["webhooksUpdate"] = function (channel) return channel.guild end
}
local botModuleEvents = {
["disable"] = true,
["enable"] = true,
["loaded"] = true,
["ready"] = true,
["unload"] = true
}
local ConfigMetatable = {}
function ConfigMetatable:__newindex(key, value)
print(debug.traceback())
error("Invalid config key " .. tostring(key) .. " for writing")
end
local ModuleMetatable = {}
ModuleMetatable["__index"] = ModuleMetatable
-- Config validation
local validateSnowflake = function (snowflake)
if (type(snowflake) ~= "string") then
return false
end
return string.match(snowflake, "%d+")
end
local configTypeValidation = {
[Bot.ConfigType.Boolean] = function (value) return type(value) == "boolean" end,
[Bot.ConfigType.Category] = validateSnowflake,
[Bot.ConfigType.Channel] = validateSnowflake,
[Bot.ConfigType.Custom] = function (value) return true end,
[Bot.ConfigType.Duration] = function (value) return type(value) == "number" end,
[Bot.ConfigType.Emoji] = function (value) return type(value) == "string" end,
[Bot.ConfigType.Integer] = function (value) return type(value) == "number" and math.floor(value) == value end,
[Bot.ConfigType.Number] = function (value) return type(value) == "number" end,
[Bot.ConfigType.Role] = validateSnowflake,
[Bot.ConfigType.String] = function (value) return type(value) == "string" end,
[Bot.ConfigType.User] = validateSnowflake,
}
local validateConfigType = function (configTable, value)
local validator = configTypeValidation[configTable.Type]
assert(validator)
if (configTable.Array) then
if (type(value) ~= "table") then
return false
end
for _, arrayValue in pairs(value) do
if (not validator(arrayValue)) then
return false
end
end
return true
else
return validator(value)
end
end
function ModuleMetatable:_PrepareConfig(context, config, values, global)
for optionIndex, configTable in pairs(config) do
local reset = false
local value = rawget(values, configTable.Name)
if (value == nil) then
reset = true
elseif (not validateConfigType(configTable, value)) then
self:LogWarning("%s has invalid value for option %s, resetting...", context, configTable.Name)
reset = true
end
if (reset) then
local default = configTable.Default
if (type(default) == "table") then
rawset(values, configTable.Name, table.deepcopy(default))
else
rawset(values, configTable.Name, default)
end
end
end
end
function ModuleMetatable:_PrepareGlobalConfig()
if (not self.GlobalConfig) then
self.GlobalConfig = {}
end
setmetatable(self.GlobalConfig, ConfigMetatable)
return self:_PrepareConfig("Global config", self._GlobalConfig, self.GlobalConfig, true)
end
function ModuleMetatable:_PrepareGuildConfig(guildId, guildConfig)
setmetatable(guildConfig, ConfigMetatable)
return self:_PrepareConfig("Guild " .. guildId, self._GuildConfig, guildConfig, false)
end
function ModuleMetatable:DisableForGuild(guild, dontSave)
if (not self:IsEnabledForGuild(guild)) then
return true
end
local success, err
if (self.OnDisable) then
success, err = Bot:CallModuleFunction(self, "OnDisable", guild)
else
success = true
end
if (success) then
local config = self:GetConfig(guild)
config._Enabled = false
if (not dontSave) then
self:SaveGuildConfig(guild)
end
self:LogInfo(guild, "Module disabled")
return true
else
return false, err
end
end
function ModuleMetatable:EnableForGuild(guild, ignoreCheck, dontSave)
if (not ignoreCheck and self:IsEnabledForGuild(guild)) then
return true
end
local stopwatch = discordia.Stopwatch()
local success, ret
if (self.OnEnable) then
local success, retOrErr, err = Bot:CallModuleFunction(self, "OnEnable", guild)
if (not success) then
return false, retOrErr
end
if (not retOrErr) then
return false, err or "OnEnable hook returned false"
end
end
local guildData = self:GetGuildData(guild.id)
guildData._Ready = true
guildData.Config._Enabled = true
if (not dontSave) then
self:SaveGuildConfig(guild)
end
self:LogInfo(guild, "Module enabled (%.3fs)", stopwatch.milliseconds / 1000)
return true
end
function ModuleMetatable:ForEachGuild(callback, evenDisabled, evenNonReady, evenNonLoaded)
for guildId, data in pairs(self._Guilds) do
local guild = Bot.Client:getGuild(guildId)
if ((guild or evenNonLoaded) and (evenNonReady or data._Ready) and (evenDisabled or data.Config._Enabled)) then
callback(guildId, data.Config, data.Data, data.PersistentData, guild)
end
end
end
function ModuleMetatable:GetConfig(guild, noCreate)
local guildData = self:GetGuildData(guild.id, noCreate)
if (not guildData) then
return nil
end
return guildData.Config
end
function ModuleMetatable:GetData(guild, noCreate)
local guildData = self:GetGuildData(guild.id, noCreate)
if (not guildData) then
return nil
end
return guildData.Data
end
function ModuleMetatable:GetGuildData(guildId, noCreate)
local guildData = self._Guilds[guildId]
if (not guildData and not noCreate) then
guildData = {}
guildData.Config = {
_Enabled = false
}
guildData.Data = {}
guildData.PersistentData = {}
guildData._Ready = false
self:_PrepareGuildConfig(guildId, guildData.Config)
self._Guilds[guildId] = guildData
end
return guildData
end
function ModuleMetatable:GetPersistentData(guild, noCreate)
if (not guild) then
if (not self.GlobalPersistentData) then
self.GlobalPersistentData = {}
end
return self.GlobalPersistentData
end
local guildData = self:GetGuildData(guild.id, noCreate)
if (not guildData) then
return nil
end
return guildData.PersistentData
end
function ModuleMetatable:IsEnabledForGuild(guild)
local config = self:GetConfig(guild, true)
return config and config._Enabled or false
end
-- Log functions (LogError, LogInfo, LogWarning)
for k, func in pairs({"error", "info", "warning"}) do
ModuleMetatable["Log" .. string.UpperizeFirst(func)] = function (moduleTable, guild, ...)
if (type(guild) == "string") then
Bot.Client[func](Bot.Client, "[%s][%s] %s", "<*>", moduleTable.Name, string.format(guild, ...))
else
Bot.Client[func](Bot.Client, "[%s][%s] %s", guild and guild.name or "<Invalid guild>", moduleTable.Name, string.format(...))
end
end
end
function ModuleMetatable:RegisterCommand(values)
local privilegeCheck = values.PrivilegeCheck
if (privilegeCheck) then
values.PrivilegeCheck = function (member)
if (not self:IsEnabledForGuild(member.guild)) then
return false
end
return privilegeCheck(member)
end
else
values.PrivilegeCheck = function (member)
return self:IsEnabledForGuild(member.guild)
end
end
table.insert(self._Commands, values.Name)
return Bot:RegisterCommand(values)
end
function ModuleMetatable:Save(guild)
self:SaveGuildConfig(guild)
self:SavePersistentData(guild)
end
function ModuleMetatable:SaveGlobalConfig()
local filepath = string.format("data/module_%s/global_config.json", self.Name)
local success, err = Bot:SerializeToFile(filepath, self.GlobalConfig, true)
if (not success) then
self:LogWarning(nil, "Failed to save global config: %s", err)
end
end
function ModuleMetatable:SaveGlobalPersistentData()
if (not self.GlobalPersistentData) then
return
end
local filepath = string.format("data/module_%s/global_data.json", self.Name)
local success, err = Bot:SerializeToFile(filepath, self.GlobalPersistentData, true)
if (not success) then
self:LogWarning(nil, "Failed to save global data: %s", err)
end
end
function ModuleMetatable:LoadGuildConfig(guild)
local guildData = self:GetGuildData(guild.id)
local config, err = Bot:UnserializeFromFile(string.format("data/module_%s/guild_%s/config.json", self.Name, guild.id))
if (config) then
self:_PrepareGuildConfig(guild.id, config)
guildData.Config = config
return true
else
self:LogError(guild, "Failed to load config: %s", err)
return false, err
end
end
function ModuleMetatable:SaveGuildConfig(guild)
local save = function (guildId, guildConfig)
local filepath = string.format("data/module_%s/guild_%s/config.json", self.Name, guildId)
local success, err = Bot:SerializeToFile(filepath, guildConfig, true)
if (not success) then
self:LogWarning(guild, "Failed to save persistent data: %s", err)
end
end
if (guild) then
local guildConfig = self:GetConfig(guild, true)
if (guildConfig) then
save(guild.id, guildConfig)
end
else
self:ForEachGuild(function (guildId, config, data, persistentData)
save(guildId, config)
end)
end
end
function ModuleMetatable:SavePersistentData(guild)
local save = function (guildId, persistentData)
local filepath = string.format("data/module_%s/guild_%s/persistentdata.json", self.Name, guildId)
local success, err = Bot:SerializeToFile(filepath, persistentData)
if (not success) then
self:LogWarning(guild, "Failed to save persistent data: %s", err)
end
end
if (guild) then
local guildData = self:GetPersistentData(guild, true)
if (guildData) then
save(guild.id, guildData)
end
else
self:SaveGlobalPersistentData()
self:ForEachGuild(function (guildId, config, data, persistentData)
save(guildId, persistentData)
end)
end
end
function Bot:CallModuleFunction(moduleTable, functionName, ...)
return self:ProtectedCall(string.format("Module (%s) function (%s)", moduleTable.Name, functionName), moduleTable[functionName], moduleTable, ...)
end
function Bot:CallOnReady(moduleTable)
if (moduleTable.OnReady) then
wrap(function () self:CallModuleFunction(moduleTable, "OnReady") end)()
end
end
function Bot:DisableModule(moduleName, guild)
local moduleTable = self.Modules[moduleName]
if (moduleTable) then
if (not moduleTable:IsEnabledForGuild(guild)) then
return false, "Module is already disabled on this server"
end
return moduleTable:DisableForGuild(guild)
end
return false, "Module not loaded"
end
function Bot:EnableModule(moduleName, guild)
local moduleTable = self.Modules[moduleName]
if (moduleTable) then
if (moduleTable:IsEnabledForGuild(guild)) then
return false, "Module is already enabled on this server"
end
return moduleTable:EnableForGuild(guild)
end
return false, "Module not loaded"
end
function Bot:LoadModule(moduleTable)
self:UnloadModule(moduleTable.Name)
local stopwatch = discordia.Stopwatch()
-- Load config
local guildConfig = {}
local globalConfig = {}
if (moduleTable.GetConfigTable) then
local success, ret = self:CallModuleFunction(moduleTable, "GetConfigTable")
if (not success) then
return false, "Failed to load config: " .. ret
end
if (type(ret) ~= "table") then
return false, "Invalid config"
end
local config = ret
-- Validate config
local validConfigOptions = {
-- Field = {type, mandatory, default}
["Array"] = {"boolean", false, false},
["Default"] = {"any", false},
["Description"] = {"string", true},
["Global"] = {"boolean", false, false},
["Optional"] = {"boolean", false, false},
["Name"] = {"string", true},
["Sensitive"] = {"boolean", false, false},
["Type"] = {"number", true}
}
for optionIndex, configTable in pairs(config) do
for configName, configValue in pairs(configTable) do
local expectedType = validConfigOptions[configName][1]
if (not expectedType) then
return false, string.format("[%s] Option #%s has invalid key \"%s\"", configTable.Name, optionIndex, configName)
end
if (expectedType ~= "any" and type(configValue) ~= expectedType) then
return false, string.format("[%s] Option #%s has key \"%s\" which has invalid type %s (expected %s)", configTable.Name, optionIndex, configName, type(configValue), expectedType)
end
end
for key, value in pairs(validConfigOptions) do
local mandatory = value[2]
if (mandatory) then
if (not configTable[key]) then
return false, string.format("Option #%s has no \"%s\" key", optionIndex, key)
end
else
if (configTable[key] == nil) then
local defaultValue = value[3]
configTable[key] = defaultValue
end
end
end
if (configTable.Default == nil and not configTable.Optional) then
return false, string.format("[%s] Option #%s is not optional and has no default value", configTable.Name, optionIndex)
end
if (configTable.Global) then
table.insert(globalConfig, configTable)
else
table.insert(guildConfig, configTable)
end
end
end
moduleTable._GlobalConfig = globalConfig
moduleTable._GuildConfig = guildConfig
-- Parse events
local moduleEvents = {}
for key,func in pairs(moduleTable) do
if (key:startswith("On") and type(func) == "function") then
local eventName = key:sub(3, 3):lower() .. key:sub(4)
if (not botModuleEvents[eventName]) then
if (not discordiaEvents[eventName]) then
return false, "Module tried to bind hook \"" .. eventName .. "\" which doesn't exist"
end
moduleEvents[eventName] = {Module = moduleTable, Callback = function (moduleTable, ...) self:CallModuleFunction(moduleTable, key, ...) end}
end
end
end
moduleTable._Events = moduleEvents
moduleTable._Commands = {}
moduleTable._Guilds = {}
setmetatable(moduleTable, ModuleMetatable)
-- Load module persistent data from disk
self:LoadModuleData(moduleTable)
moduleTable:_PrepareGlobalConfig()
-- Loading finished, call callback
self.Modules[moduleTable.Name] = moduleTable
if (moduleTable.OnLoaded) then
local success, err = self:CallModuleFunction(moduleTable, "OnLoaded")
if (not success or not err) then
self.Modules[moduleTable.Name] = nil
err = err or "OnLoaded hook returned false"
return false, err
end
end
local loadTime = stopwatch.milliseconds / 1000
self.Client:info("[<*>][%s] Loaded module (%.3fs)", moduleTable.Name, stopwatch.milliseconds / 1000)
if (isReady) then
self:CallOnReady(moduleTable)
self:MakeModuleReady(moduleTable)
end
return moduleTable
end
function Bot:LoadModuleFile(fileName)
local sandbox = setmetatable({ }, { __index = _G })
sandbox.Bot = self
sandbox.Client = self.Client
sandbox.Config = Config
sandbox.Discordia = discordia
sandbox.Module = {}
sandbox.require = require -- I still don't understand why we have to do this
local func, err = loadfile(fileName, "bt", sandbox)
if (not func) then
return false, "Failed to load module:", err
end
local ret, err = pcall(func)
if (not ret) then
return false, "Failed to call module:", err
end
local moduleName = sandbox.Module.Name
if (not moduleName or type(moduleName) ~= "string") then
return false, "Module has an invalid name"
end
return self:LoadModule(sandbox.Module)
end
function Bot:LoadModuleData(moduleTable)
-- Must be called from within a coroutine
local dataFolder = string.format("data/module_%s", moduleTable.Name)
local dataIt = fs.scandir(dataFolder)
if (dataIt) then
for entry in assert(dataIt) do
local path = dataFolder .. "/" .. entry.name
if (entry.type == "directory") then
local guildId = entry.name:match("guild_(%d+)")
if (guildId) then
local guildData = moduleTable:GetGuildData(guildId)
local config, err = self:UnserializeFromFile(path .. "/config.json")
if (config) then
guildData.Config = config
moduleTable:_PrepareGuildConfig(guildId, guildData.Config)
else
self.Client:error("Failed to load config of guild %s (%s module): %s", guildId, moduleTable.Name, err)
end
local persistentData, err = self:UnserializeFromFile(path .. "/persistentdata.json")
if (persistentData) then
guildData.PersistentData = persistentData
else
self.Client:error("Failed to load persistent data of guild %s (%s module): %s", guildId, moduleTable.Name, err)
end
end
elseif (entry.type == "file") then
if (entry.name == "global_config.json") then
local config, err = self:UnserializeFromFile(path)
if (config) then
moduleTable.GlobalConfig = config
self.Client:info("Global config of module %s has been loaded", moduleTable.Name)
else
self.Client:error("Failed to load global config module %s: %s", moduleTable.Name, err)
end
elseif (entry.name == "global_data.json") then
local data, err = self:UnserializeFromFile(path)
if (data) then
moduleTable.GlobalPersistentData = data
self.Client:info("Global data of module %s has been loaded", moduleTable.Name)
else
self.Client:error("Failed to load global config module %s: %s", moduleTable.Name, err)
end
end
end
end
end
end
function Bot:MakeModuleReady(moduleTable)
moduleTable:ForEachGuild(function (guildId, config, data, persistentData, guild)
moduleTable:EnableForGuild(guild, true, true)
end, false, true)
for eventName,eventData in pairs(moduleTable._Events) do
local eventTable = self.Events[eventName]
if (not eventTable) then
eventTable = {}
self.Client:onSync(eventName, function (...)
local parameters = {...}
table.insert(parameters, self.Client)
local eventGuild = discordiaEvents[eventName](table.unpack(parameters))
for _, eventData in pairs(eventTable) do
if (not eventGuild or eventData.Module:IsEnabledForGuild(eventGuild)) then
wrap(eventData.Callback)(eventData.Module, ...)
end
end
end)
self.Events[eventName] = eventTable
end
table.insert(eventTable, eventData)
end
end
function Bot:UnloadModule(moduleName)
local moduleTable = self.Modules[moduleName]
if (moduleTable) then
if (isReady and moduleTable.OnUnload) then
moduleTable:OnUnload()
end
moduleTable:SavePersistentData()
for eventName,func in pairs(moduleTable._Events) do
local eventTable = self.Events[eventName]
assert(eventTable)
local i = table.search(eventTable, func)
assert(i)
table.remove(eventTable, i)
end
for _, commandName in pairs(moduleTable._Commands) do
Bot:UnregisterCommand(commandName)
end
self.Modules[moduleName] = nil
self.Client:info("[<*>][%s] Unloaded module", moduleTable.Name)
return true
end
return false
end
Bot.Client:onSync("ready", function ()
if (isReady) then
for moduleName,moduleTable in pairs(Bot.Modules) do
Bot:CallOnReady(moduleTable)
end
else
for moduleName,moduleTable in pairs(Bot.Modules) do
Bot:CallOnReady(moduleTable)
Bot:MakeModuleReady(moduleTable)
end
end
isReady = true
end)
Bot:RegisterCommand({
Name = "modulelist",
Args = {},
PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end,
Help = "Configures a module",
Func = function (message)
local moduleList = {}
for moduleName, moduleTable in pairs(Bot.Modules) do
table.insert(moduleList, moduleTable)
end
table.sort(moduleList, function (a, b) return a.Name < b.Name end)
local moduleListStr = {}
for _, moduleTable in pairs(moduleList) do
local enabledEmoji
if (moduleTable.Global) then
enabledEmoji = ":globe_with_meridians:"
elseif (moduleTable:IsEnabledForGuild(message.guild)) then
enabledEmoji = ":white_check_mark:"
else
enabledEmoji = ":x:"
end
table.insert(moduleListStr, string.format("%s **%s**", enabledEmoji, moduleTable.Name))
end
message:reply({
embed = {
title = "Module list",
fields = {
{name = "Loaded modules", value = table.concat(moduleListStr, '\n')},
},
timestamp = discordia.Date():toISO('T', 'Z')
}
})
end
})
Bot:RegisterCommand({
Name = "config",
Args = {
{Name = "module", Type = Bot.ConfigType.String},
{Name = "action", Type = Bot.ConfigType.String, Optional = true},
{Name = "key", Type = Bot.ConfigType.String, Optional = true},
{Name = "value", Type = Bot.ConfigType.String, Optional = true}
},
PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end,
Help = "Configures a module",
Func = function (message, moduleName, action, key, value)
moduleName = moduleName:lower()
local moduleTable = Bot.Modules[moduleName]
if (not moduleTable) then
message:reply("Invalid module \"" .. moduleName .. "\"")
return
end
action = action and action:lower() or "list"
local globalConfig = moduleTable.GlobalConfig
local guild = message.guild
local guildConfig = moduleTable:GetConfig(guild)
local StringifyConfigValue = function (configTable, value)
if (value ~= nil) then
local valueToString = Bot.ConfigTypeToString[configTable.Type]
if (configTable.Array) then
local valueStr = {}
for _, value in pairs(value) do
table.insert(valueStr, valueToString(value, guild))
end
return table.concat(valueStr, ", ")
else
return valueToString(value, guild)
end
else
if (not configTable.Optional) then
error("Config " .. configTable.Name .. " has no value but is not optional")
end
return "<None>"
end
end
local GenerateField = function (configTable, value, allowSensitive, wasModified)
local valueStr
if (not configTable.Sensitive or allowSensitive) then
valueStr = StringifyConfigValue(configTable, value)
else
valueStr = "*<sensitive>*"
end
local fieldType = Bot.ConfigTypeString[configTable.Type]
if (configTable.Array) then
fieldType = fieldType .. " array"
end
return {
name = string.format("%s:gear: %s", configTable.Global and ":globe_with_meridians: " or "", configTable.Name),
value = string.format("**Description:** %s\n**Value (%s):** %s", configTable.Description, fieldType, valueStr)
}
end
local GetConfigByKey = function (key)
for k,configData in pairs(moduleTable._GuildConfig) do
if (configData.Name == key) then
return configData
end
end
for k,configData in pairs(moduleTable._GlobalConfig) do
if (configData.Name == key) then
return configData
end
end
end
if (action == "list") then
local fields = {}
local globalFields = {}
for k,configTable in pairs(moduleTable._GuildConfig) do
table.insert(fields, GenerateField(configTable, rawget(guildConfig, configTable.Name)))
end
if (message.member.id == Config.OwnerUserId) then
for k,configTable in pairs(moduleTable._GlobalConfig) do
table.insert(fields, GenerateField(configTable, rawget(moduleTable.GlobalConfig, configTable.Name)))
end
end
local enabledText
if (moduleTable.Global) then
enabledText = ":globe_with_meridians: This module is global and cannot be enabled nor disabled on a guild basis"
elseif (moduleTable:IsEnabledForGuild(guild)) then
enabledText = ":white_check_mark: Module **enabled** (use `!disable " .. moduleTable.Name .. "` to disable it)"
else
enabledText = ":x: Module **disabled** (use `!enable " .. moduleTable.Name .. "` to enable it)"
end
message:reply({
embed = {
title = "Configuration for " .. moduleTable.Name .. " module",
description = string.format("%s\n\nConfiguration list:", enabledText, moduleTable.Name),
fields = fields,
footer = {text = string.format("Use `!config %s add/remove/reset/set/show ConfigName <value>` to change configuration settings.", moduleTable.Name)}
}
})
elseif (action == "show") then
local configTable = GetConfigByKey(key)
if (not configTable or (configTable.Global and message.member.id ~= Config.OwnerUserId)) then
message:reply(string.format("Module %s has no config key \"%s\"", moduleTable.Name, key))
return
end
local config = configTable.Global and globalConfig or guildConfig
message:reply({
embed = {
title = "Configuration of " .. moduleTable.Name .. " module",
fields = {
GenerateField(configTable, rawget(config, configTable.Name), true)
},
timestamp = discordia.Date():toISO('T', 'Z')
}
})
elseif (action == "add" or action == "remove" or action == "reset" or action == "set") then
if (not key) then
message:reply("Missing config key name")
return
end
local configTable = GetConfigByKey(key)
if (not configTable) then
message:reply(string.format("Module %s has no config key \"%s\"", moduleTable.Name, key))
return
end
if (not configTable.Array and (action == "add" or action == "remove")) then
message:reply("Configuration **" .. configTable.Name .. "** is not an array, use the *set* action to change its value")
return
end
local newValue
if (action ~= "reset") then
if (not value or #value == 0) then
if (configTable.Optional and action == "set") then
value = nil
else
message:reply("Missing config value")
return
end
end
if (value) then
local valueParser = Bot.ConfigTypeParser[configTable.Type]
newValue = valueParser(value, guild)
if (newValue == nil) then
message:reply("Failed to parse new value (type: " .. Bot.ConfigTypeString[configTable.Type] .. ")")
return
end
end
else
local default = configTable.Default
if (type(default) == "table") then
newValue = table.deepcopy(default)
else
newValue = default
end
end
local wasModified = false
local config = configTable.Global and globalConfig or guildConfig
if (action == "add") then
assert(configTable.Array)
-- Insert value (if not present)
local found = false
local values = rawget(config, configTable.Name)
if (not values) then
assert(configTable.Optional)
values = {}
rawset(config, configTable.Name, values)
end
for _, value in pairs(values) do
if (value == newValue) then
found = true
break
end
end
if (not found) then
table.insert(values, newValue)
wasModified = true
end
elseif (action == "remove") then
assert(configTable.Array)
-- Remove value (if present)
local values = rawget(config, configTable.Name)
if (values) then
for i = 1, #values do
if (values[i] == newValue) then
table.remove(values, i)
wasModified = true
break
end
end
else
assert(configTable.Optional)
end
elseif (action == "reset" or action == "set") then
-- Replace value
if (configTable.Array and action ~= "reset") then
rawset(config, configTable.Name, {newValue})
else
rawset(config, configTable.Name, newValue)
end
wasModified = true
end
if (wasModified) then
if (configTable.Global) then
moduleTable:SaveGlobalConfig()
else