-
Notifications
You must be signed in to change notification settings - Fork 10
/
bot.lua
425 lines (374 loc) · 10.9 KB
/
bot.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
-- 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 discordia = require('discordia')
local enums = discordia.enums
local wrap = coroutine.wrap
discordia.extensions() -- load all helpful Lua library extensions
local client = discordia.Client({
cacheAllMembers = true,
-- logLevel = 4,
gatewayIntents = bit.bor(
-- All intents except guildIntegrations and guildPresences
enums.gatewayIntent.guilds,
enums.gatewayIntent.guildMembers,
enums.gatewayIntent.guildModeration,
enums.gatewayIntent.guildEmojis,
enums.gatewayIntent.guildWebhooks,
enums.gatewayIntent.guildInvites,
enums.gatewayIntent.guildVoiceStates,
enums.gatewayIntent.guildMessages,
enums.gatewayIntent.guildMessageReactions,
enums.gatewayIntent.guildMessageTyping,
enums.gatewayIntent.directMessage,
enums.gatewayIntent.directMessageRections,
enums.gatewayIntent.directMessageTyping
)
})
local function code(str)
return string.format('```\n%s```', str)
end
local function printLine(...)
local ret = {}
for i = 1, select('#', ...) do
local arg = tostring(select(i, ...))
table.insert(ret, arg)
end
return table.concat(ret, '\t')
end
dofile("utils.lua")
-- Config
Config = {}
local func, err = loadfile("config.lua", "bt", Config)
if (not func) then
print("Failed to load config file:\n" .. code(tostring(err)))
return
end
local ret, err = pcall(func)
if (not ret) then
print("Failed to execute config file:\n" .. code(tostring(err)))
return
end
-- Bot code
Bot = {}
Bot.Client = client
Bot.Commands = {}
Bot.Events = {}
Bot.Modules = {}
Bot.ConfigType = enums.enum {
Boolean = 0,
Category = 1,
Channel = 2,
Custom = 3,
Duration = 4,
Emoji = 5,
Guild = 6,
Integer = 7,
Member = 8,
Message = 9,
Number = 10,
Role = 11,
String = 12,
User = 13
}
Bot.ConfigTypeString = {}
for name,value in pairs(Bot.ConfigType) do
Bot.ConfigTypeString[value] = name
end
Bot.ConfigTypeToString = {
[Bot.ConfigType.Boolean] = tostring,
[Bot.ConfigType.Category] = function (value, guild)
local channel = guild:getChannel(value)
return channel and channel.mentionString or "<Invalid category>"
end,
[Bot.ConfigType.Channel] = function (value, guild)
local channel = guild:getChannel(value)
return channel and channel.mentionString or "<Invalid channel>"
end,
[Bot.ConfigType.Custom] = function (value, guild) return "<custom-type>" end,
[Bot.ConfigType.Duration] = function (value, guild) return Bot:FormatDuration(guild, value) end,
[Bot.ConfigType.Emoji] = function (value, guild)
local emojiData = Bot:GetEmojiData(guild, value)
return emojiData and emojiData.MentionString or "<Invalid emoji>"
end,
[Bot.ConfigType.Integer] = tostring,
[Bot.ConfigType.Guild] = function (value)
local guild = client:getGuild(value)
return guild and guild.name or "<Unknown guild>"
end,
[Bot.ConfigType.Member] = function (value, guild)
local member = guild:getMember(value)
return member and member.user.mentionString or "<Invalid member>"
end,
[Bot.ConfigType.Message] = tostring,
[Bot.ConfigType.Number] = function (value) return type(value) == "number" end,
[Bot.ConfigType.Role] = function (value, guild)
local role = guild:getRole(value)
return role and role.mentionString or "<Invalid role>"
end,
[Bot.ConfigType.String] = tostring,
[Bot.ConfigType.User] = function (value, guild)
local user = client:getUser(value)
return user and user.mentionString or "<Invalid user>"
end
}
Bot.ConfigTypeParameter = {
[Bot.ConfigType.Boolean] = function (value, guild)
if (value == "yes" or value == "1" or value == "true") then
return true
elseif (value == "no" or value == "0" or value == "false") then
return false
end
end,
[Bot.ConfigType.Category] = function (value, guild)
local channel, err = Bot:DecodeChannel(guild, value)
if (not channel) then
return nil, err
end
if (channel.type ~= enums.channelType.category) then
return nil, "expected category"
end
return channel
end,
[Bot.ConfigType.Channel] = function (value, guild)
return Bot:DecodeChannel(guild, value)
end,
[Bot.ConfigType.Custom] = function (value, guild)
return nil
end,
[Bot.ConfigType.Duration] = function (value, guild)
return string.ConvertToTime(value)
end,
[Bot.ConfigType.Emoji] = function (value, guild)
return Bot:DecodeEmoji(guild, value)
end,
[Bot.ConfigType.Integer] = function (value, guild)
return tonumber(value:match("^(%d+)$"))
end,
[Bot.ConfigType.Guild] = function (value)
local success, err = util.ValidateSnowflake(value)
if not success then
return nil, err
end
local guild = client:getGuild(value)
if not guild then
return nil, value .. " is not a guild I know"
end
return guild
end,
[Bot.ConfigType.Member] = function (value, guild)
return Bot:DecodeMember(guild, value)
end,
[Bot.ConfigType.Message] = function (value, guild)
return Bot:DecodeMessage(value, nil, true)
end,
[Bot.ConfigType.Number] = function (value)
return tonumber(value)
end,
[Bot.ConfigType.Role] = function (value, guild)
return Bot:DecodeRole(guild, value)
end,
[Bot.ConfigType.String] = function (value, guild)
return value
end,
[Bot.ConfigType.User] = function (value, guild)
return Bot:DecodeUser(value)
end
}
Bot.ConfigTypeParser = {
[Bot.ConfigType.Boolean] = function (value, guild)
if (value == "yes" or value == "1" or value == "true") then
return true
elseif (value == "no" or value == "0" or value == "false") then
return false
end
end,
[Bot.ConfigType.Category] = function (value, guild)
local channel, err = Bot:DecodeChannel(guild, value)
if (not channel) then
return nil, err
end
if (channel.type ~= enums.channelType.category) then
return nil, "expected category"
end
return channel.id
end,
[Bot.ConfigType.Channel] = function (value, guild)
local channel = Bot:DecodeChannel(guild, value)
return channel and channel.id
end,
[Bot.ConfigType.Custom] = function (value, guild)
return nil
end,
[Bot.ConfigType.Duration] = function (value, guild)
return string.ConvertToTime(value)
end,
[Bot.ConfigType.Emoji] = function (value, guild)
local emojiData = Bot:DecodeEmoji(guild, value)
return emojiData and emojiData.Name
end,
[Bot.ConfigType.Integer] = function (value, guild)
return tonumber(value:match("^(%d+)$"))
end,
[Bot.ConfigType.Guild] = function (value)
local success, err = util.ValidateSnowflake(value)
if not success then
return nil, err
end
local guild = client:getGuild(value)
if not guild then
return nil, value .. " is not a guild I know"
end
return guild.id
end,
[Bot.ConfigType.Member] = function (value, guild)
local member = Bot:DecodeMember(guild, value)
return member and member.id
end,
[Bot.ConfigType.Message] = function (value, guild)
local message = Bot:DecodeMessage(value, nil, true)
return message and Bot:GenerateMessageLink(message)
end,
[Bot.ConfigType.Number] = function (value)
return tonumber(value)
end,
[Bot.ConfigType.Role] = function (value, guild)
local role = Bot:DecodeRole(guild, value)
return role and role.id
end,
[Bot.ConfigType.String] = function (value, guild)
return value
end,
[Bot.ConfigType.User] = function (value, guild)
local user = Bot:DecodeUser(value)
return user and user.id
end
}
client:onSync("ready", function ()
print("Logged in as " .. client.user.username)
end)
client:on("guildAvailable", function (guild)
print(string.format("Guild %s (%d members)", guild.name, guild.totalMemberCount))
end)
client:on("guildCreate", function (guild)
client:info("Bot was added to guild %s", guild.name)
end)
client:on("guildDelete", function (guild)
client:info("Bot was removed from guild %s", guild.name)
end)
function Bot:Save()
local stopwatch = discordia.Stopwatch()
for _, moduleTable in pairs(self.Modules) do
self:ProtectedCall(string.format("Module (%s) persistent data save", moduleTable.Name), moduleTable.SavePersistentData, moduleTable)
end
client:info("Modules data saved (%.3fs)", stopwatch.milliseconds / 1000)
end
-- Why is this required Oo
local env = setmetatable({}, { __index = _G })
env.Bot = Bot
env.Client = client
env.Config = Config
env.discordia = discordia
env.require = require
local function loadbotfile(file)
local f, err = loadfile(file, "t", env)
if (not f) then
error(file .. " failed to compile: " .. err)
end
local success, err = pcall(f)
if (not success) then
error(file .. " failed to execute: " .. err)
end
end
loadbotfile("bot_emoji.lua")
loadbotfile("bot_utility.lua")
loadbotfile("bot_localization.lua")
loadbotfile("bot_commands.lua")
loadbotfile("bot_modules.lua")
loadbotfile("bot_timers.lua")
Bot:CreateRepeatTimer(5 * 60, -1, function()
Bot:Save()
end)
Bot:RegisterCommand({
Name = "exec",
Args = {
{Name = "filename", Type = Bot.ConfigType.String}
},
PrivilegeCheck = function (member) return member.id == Config.OwnerUserId end,
Help = "Executes a file",
Func = function (message, fileName)
local sandbox = setmetatable({ }, { __index = _G })
sandbox.Bot = Bot
sandbox.Client = client
sandbox.Config = Config
sandbox.CommandMessage = message
sandbox.Discordia = discordia
sandbox.require = require
local lines = {}
sandbox.print = function(...)
table.insert(lines, printLine(...))
end
local func, err = loadfile(fileName, "bt", sandbox)
if (not func) then
message:reply("Failed to load file:\n" .. code(tostring(err)))
return
end
local ret, err = pcall(func)
if (not ret) then
message:reply("Failed to call file:\n" .. code(tostring(err)))
return
end
if (#lines > 0) then
lines = table.concat(lines, '\n')
if #lines > 1990 then -- truncate long messages
lines = lines:sub(1, 1990)
end
message:reply(code(lines))
end
end
})
Bot:RegisterCommand({
Name = "save",
Args = {},
PrivilegeCheck = function (member) return member.id == Config.OwnerUserId end,
Help = "Saves bot data",
Func = function (message)
Bot:Save()
message:reply("Bot data saved")
end
})
Bot:RegisterCommand({
Name = "reboot",
Args = {},
PrivilegeCheck = function (member) return member.id == Config.OwnerUserId end,
Help = "Restart bot",
Func = function (message)
Bot:Save()
message:reply("Saving and rebooting...")
os.exit(0)
end
})
Bot:RegisterCommand({
Name = "debugtimer",
Args = {},
PrivilegeCheck = function (member) return member.id == Config.OwnerUserId end,
Help = "Gets last timer check timestamp",
Func = function (message)
message:reply(string.format("Last timer check occurred on <t:%d:f>", Bot.LastTimerExecution))
end
})
client:run('Bot ' .. Config.Token)
for k,moduleFile in pairs(Config.AutoloadModules) do
wrap(function ()
local moduleTable, err, codeErr = Bot:LoadModuleFile(moduleFile)
if (moduleTable) then
client:info("Auto-loaded module \"%s\"", moduleTable.Name)
else
local errorMessage = err
if (codeErr) then
errorMessage = errorMessage .. "\n" .. codeErr
end
client:error(errorMessage)
end
end)()
end