-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
288 lines (237 loc) · 8.46 KB
/
index.js
File metadata and controls
288 lines (237 loc) · 8.46 KB
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
'use strict'
require('toml-require').install()
const {copyFile, readdir} = require('fs/promises')
const {Client, GatewayIntentBits, Partials} = require('discord.js')
const {parseUsage, parseArguments, UsageSyntaxError} = require('./arguments')
const {info, fatal, checkFatal, logDiscordMessage} = require('./log')
const {PermissionSet} = require('./permissions')
const configFileName = './config.toml'
const defaultConfigFileName = './config.default.toml'
const pluginDirectoryName = './plugins'
const prettyUsage = (prefix, name, usage) => {
const argStrings = []
const typeExplanations = []
for (const arg of usage) {
if (arg.type === 'rest') {
argStrings.push(`<${arg.name}>`)
typeExplanations.push(`${arg.name} is some text`)
} else if (arg.type === 'literal') {
argStrings.push(arg.name)
} else {
argStrings.push(`<${arg.name}>`)
typeExplanations.push(`${arg.name} is ${arg.type.prettyName}`)
}
}
let result = `\`${prefix}${name}`
if (argStrings.length !== 0) {
result += ' ' + argStrings.join(' ')
}
result += '`'
if (typeExplanations.length !== 0) {
result += `\n where ${typeExplanations.join(', ')}`
}
return result
}
const checkGuildAgainstConfiguration = async (guild) => {
if (guild.id !== bot.config.guildId) {
console.warn(
`Leaving guild ${guild.name} (${guild.id}) because it does not match the configured guild ID (${bot.config.guildId}).`
)
await guild.leave()
}
}
let lastMembersUpdate
// Cache all guild members, but only at most once every 30 minutes.
const updateMembersCache = async (guild) => {
const now = Date.now()
if (lastMembersUpdate == null || now - lastMembersUpdate >= 1000 * 60 * 30) {
await guild.members.fetch()
lastMembersUpdate = now
}
}
const bot = {
formatUsage: (plugin) => {
let usages = plugin._usage
if (usages === undefined) {
return '(There is no command associated with this plugin.)'
}
usages = usages.map((usage) => {
const result =
prettyUsage(bot.config.commandPrefix, plugin.name, usage)
return result.split('\n').map((line) => ' ' + line).join('\n')
})
return `Usage:\n${usages.join('\n')}`
},
}
const onReady = async (client) => {
// Make sure the configured guild ID is reasonable before doing anything
// destructive.
const guild = bot.guild = await client.guilds.fetch(bot.config.guildId)
// Leave all the "wrong" guilds.
for (const [_, guild] of client.guilds.cache) {
await checkGuildAgainstConfiguration(guild)
}
updateMembersCache(guild)
for (const [_, plugin] of bot.plugins) {
if (plugin.ready !== undefined) {
await plugin.ready(bot)
}
}
client.on('guildCreate', checkGuildAgainstConfiguration)
client.on('messageCreate', onMessageCreate)
info('Done.')
}
const onMessageCreate = async (message) => {
// Ignore all messages that:
// - are from any bot, since this would be susceptible to exploits;
// - don't begin with the command prefix.
if (
message.guild === null ||
message.author.bot ||
message.content === null ||
!message.content.startsWith(bot.config.commandPrefix)
) {
return
}
updateMembersCache(message.guild)
logDiscordMessage(message)
const command = message.content.replace(bot.config.commandPrefix, '')
const [name, argsString = ''] = command.split(/\s+(.*)/s, 2)
const plugin = bot.plugins.get(name)
if (plugin === undefined) { return }
if (!bot.permissions.allows({
roles: Array.from(message.member.roles.cache.keys()),
command: name,
channel: message.channel.id})) {
info(
'The preceding command was ignored due to insufficient permissions.'
)
return
}
try {
const args = await parseArguments(
argsString,
plugin._usage,
message,
)
if (args === null) {
message.reply(bot.formatUsage(plugin))
return
}
await plugin.run(args, message, bot, plugin)
} catch (error) {
console.error(error)
await message.reply(
'An unhandled exception was encountered while running that command. A stack trace has been printed to the attached terminal for a maintainer to see.'
)
}
checkFatal()
}
void (async () => {
info('Loading configuration...')
let config
try {
config = require(configFileName)
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
// The config is missing. Create one.
await copyFile(defaultConfigFileName, configFileName)
config = require(configFileName)
info(
`A new config file was created for you, ${configFileName}. You will need to edit it to configure the bot.`
)
} else {
throw error
}
}
bot.config = config
if (config.token == null) {
fatal(
`Please provide a bot token by editing the "token" field in ${configFileName}. This is required so the bot can authenticate with Discord.`
)
}
if (config.guildId == null) {
fatal(
`Please provide a guild ID by editing the "guildId" field in ${configFileName}. This is required because the bot is designed to work with only one guild.`
)
}
bot.permissions = new PermissionSet(config.permissions)
// Load all plugins.
// Loading a plugin consists of:
// - requiring it as a module;
// - running its initialize function if it has one.
// This happens before connection so that any plugin can abort at any point
// if its needs aren't met.
console.group('Loading plugins...')
// Decide which plugins to load.
// If discoverPlugins is set to true, find plugins by reading the plugins
// directory.
const pluginFileNames =
config.discoverPlugins ? new Set((await readdir(pluginDirectoryName)).map((fileName) => fileName.match(/^[^.]*/)[0]))
: /* otherwise */ new Set
if (config.plugins === undefined) {
config.plugins = Object.create(null)
}
// Handle all plugins that are explicitly enabled or disabled.
// Note that plugins are resolved by their module name, not the plugin name
// given in their exports, because they're not required in the first place
// if they're disabled.
for (const pluginName of Object.keys(config.plugins)) {
if (config.plugins[pluginName]) {
pluginFileNames.add(pluginName)
} else {
pluginFileNames.delete(pluginName)
}
}
const plugins = bot.plugins = new Map
for (const pluginFileName of pluginFileNames) {
console.group(pluginFileName)
const plugin = require(`${pluginDirectoryName}/${pluginFileName}`)
plugin.fileName = pluginFileName
plugins.set(plugin.name, plugin)
if (plugin.usage !== undefined) {
const usage = Array.isArray(plugin.usage) ? plugin.usage
: /* otherwise */ [plugin.usage]
try {
plugin._usage = usage.map(parseUsage)
} catch (error) {
if (error instanceof UsageSyntaxError) {
fatal(`Syntax error in usage: ${error.message}`)
} else {
throw error
}
}
}
if (plugin.initialize !== undefined) {
await plugin.initialize(bot)
}
console.groupEnd()
}
console.groupEnd()
checkFatal()
// Connect to Discord.
info('Connecting...')
const client = bot.client = new Client({
intents: [
GatewayIntentBits.DirectMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
partials: [
Partials.Channel,
],
/* Default Message Options */
// Replying to a non-existent message creates a non-reply instead.
failIfNotExists: false,
// Turn off mentioning the replied-to user but allow explicit user
// mentions by default.
allowedMentions: {
parse: ['users'],
repliedUser: false,
},
})
client.login(config.token)
client.on('ready', onReady)
})()