-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathscepter.ts
273 lines (235 loc) · 8.26 KB
/
scepter.ts
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
'use strict'
import { Client, Message } from 'discord.js'
import * as dotenv from 'dotenv'
import Enmap from 'enmap'
import * as fs from 'fs'
import * as log from './lib/log'
dotenv.config()
const client = new Client()
client['log'] = log
client['guildData'] = new Enmap({
name: 'guilds'
})
client['userData'] = new Enmap({
name: 'users'
})
client['timerData'] = new Enmap({
name: 'timers'
})
client['config'] = new Enmap({
name: 'runtimeConfig'
})
client['loadedModules'] = {}
client['loadedCommands'] = {}
if (!process.env.SCEPTER_BOT_GUILD) {
log.error('No Discord guild ID supplied. Set the SCEPTER_BOT_GUILD environment variable.')
}
if (!process.env.SCEPTER_OWNER_IDS) {
log.error('No owner user Discord ID supplied. Set the SCEPTER_OWNER_IDS environment variable.')
}
client['ownerIds'] = process.env.SCEPTER_OWNER_IDS
if (!process.env.SCEPTER_DISCORD_TOKEN) {
log.error('No Discord authentication token supplied. Set the SCEPTER_DISCORD_TOKEN environment variable.')
}
client.login(process.env.SCEPTER_DISCORD_TOKEN)
.catch(console.error)
type Command = {
name: string,
description: string,
examples: string[],
minArgs: number
maxArgs: number,
permissionLevel?: number,
secret?: boolean,
cooldown?: number,
aliases?: string[],
run (message: Message, args: string[]): Promise<Message>
}
type Event = {
trigger: string,
event (): Promise<any> // TODO: is this correct? Verify with further examples
}
type Job = {
period: number,
runInstantly: boolean,
job (client: Client): Promise<void>,
interval: NodeJS.Timeout
}
type Module = {
name: string,
commands?: Command[]
jobs?: Job[],
events?: Event[],
loadOnBoot?: boolean
}
const savedModules: string[] = []
const saveModule = (module: string) => {
if (!savedModules.includes(module)) {
savedModules.push(module)
client['config'].set('modules.loaded', savedModules)
}
}
const removeModule = (module: string) => {
if (savedModules.includes(module)) {
client['config'].set('modules.loaded', savedModules.filter(x => x !== module))
}
}
export const availableModules: string[] = []
export const loadModule = (name: string, initial: boolean = false) => {
import(`./modules/${name}`).then((module: Module) => {
if (initial && module.loadOnBoot != null && module.loadOnBoot === false && !savedModules.includes(name)) {
return
}
log.info(`Loading module ${name}`, client)
saveModule(name)
if (module.jobs) {
module.jobs.map((x: Job) => {
x.interval = setInterval(() => x.job(client), x.period * 1000)
if (x.runInstantly) {
x.job(client)
.catch(log.warn)
}
})
}
if (module.commands) {
module.commands.map(command => {
const possibleNames = command.aliases
? command.aliases.concat([command.name])
: [command.name]
possibleNames.map(name => {
client['loadedCommands'][name] = command
})
})
}
if (module.events) {
module.events.map(async (event: Event) => {
client.on(event.trigger, event.event)
})
}
client['loadedModules'][name] = module
}).catch(err => log.warn(err, client))
}
export const unloadModule = (name: string) => {
const module = client['loadedModules'][name]
let possibleNames: string[]
if (module) {
removeModule(name)
if (module.jobs && module.jobs.length > 0) {
module.jobs.forEach((job: Job) => {
clearInterval(job.interval)
})
}
if (module.events && module.events.length > 0) {
module.events.forEach((event: Event) => {
client.removeListener(event.trigger, event.event)
})
}
if (module.commands && module.commands.length > 0) {
module.commands.forEach((command: Command) => {
possibleNames = command.aliases
? command.aliases.concat([command.name])
: [command.name]
possibleNames.map(commandName => {
Reflect.deleteProperty(client['loadedCommands'], commandName)
})
})
Reflect.deleteProperty(client['loadedModules'], name)
}
}
}
const parseArgs = (messageContent: string) => {
if (!messageContent) return []
return messageContent.match(/\\?.|^$/g).reduce((p, c) => {
if (c === '"') {
p['quote'] ^= 1
} else if (!p['quote'] && c === ' ') {
p.a.push('')
} else {
p.a[p.a.length - 1] += c.replace(/\\(.)/, '$1')
}
return p
}, { a: [''] }).a
}
const runCommand = async (message: Message, command: Command, args: string[]) => {
if (command.cooldown != null) {
await client['userData'].ensure(`${message.author.id}.cooldowns.${command.name}`, new Date(0))
const cooldownExpiryDate = new Date(client['userData']
.get(`${message.author.id}.cooldowns.${command.name}`))
if (cooldownExpiryDate.getTime() > message.createdTimestamp) {
return message.channel.send(
`This command has a cooldown of ${command.cooldown} seconds.`
+ `(${new Date(+cooldownExpiryDate - Date.now()).getSeconds() + 1} left)`)
}
await client['userData'].set(`${message.author.id}.cooldowns.${command.name}`,
new Date(message.createdTimestamp + command.cooldown * 1000))
}
if (args.length > command.maxArgs) {
return message.channel.send(
`Too many arguments for \`${command.name}\`. (max: ${command.maxArgs}, `
+ `you might need to quote an argument) `)
}
if (args.length < command.minArgs) {
return message.channel.send(`Too few arguments for \`${command.name}\`. (min: ${command.minArgs})`)
}
try {
// TODO: test if shit works with an empty permissionLevel
if (command.permissionLevel && command.permissionLevel > 0) {
switch (command.permissionLevel) {
case 1:
if (!message.member.hasPermission('MANAGE_MESSAGES')) {
return message.channel.send(`You don't have permission to execute this command, which requires the Manage Messages permission.`)
}
break
case 2:
if (!message.member.hasPermission('MANAGE_GUILD')) {
return message.channel.send(`You don't have permission to execute this command, which requires the Manage Server permission.`)
}
break
case 3:
if (!client['ownerIds'].split(',').includes(message.author.id)) {
return message.channel.send(`You don't have permission to execute this command, which requires ownership of this bot.`)
}
break
default:
log.warn(`\`${command.name}\` has an invalid permissionLevel of ${command.permissionLevel}`, message.client)
return message.channel.send(`Internal error: invalid permissionLevel (${command.permissionLevel}) on command \`${command.name}\``)
}
}
return await command.run(message, args)
} catch (e) {
await message.channel.send(`Error: \`${e}\``)
return log.warn(`\`${command.name} ${args}\` errored with \`${e}\``, message.client)
}
}
client.on('ready', async () => {
client['botGuild'] = client.guilds.get(process.env.SCEPTER_BOT_GUILD)
log.info(`Logged in as ${client.user.tag}! Add bot with https://discordapp.com/api/oauth2/authorize?client_id=${client.user.id}&scope=bot`, client)
if (client['config'].has('modules.loaded')) {
savedModules.push(...client['config'].get('modules.loaded'))
}
fs.readdir('./modules/', (err, files) => {
if (err) {
return log.error('Failed to load modules folder', client)
} else {
files.forEach(async file => {
const name = file.split('.')[0]
availableModules.push(name)
loadModule(name, true)
})
}
})
})
client.on('message', async (message: Message) => {
await client['guildData'].ensure(message.guild.id, { prefix: 's.' })
const prefix: string = await client['guildData'].get(message.guild.id, 'prefix')
if (message.content.startsWith(`${prefix}`) && !message.author.bot) {
const commandName: string = message.content.split(prefix)[1].split(' ')[0]
if (client['loadedCommands'][commandName]) {
const commandArgs: string = message.content.substr(prefix.length + 1 + commandName.length)
await runCommand(message, client['loadedCommands'][commandName], parseArgs(commandArgs))
}
}
})
client.on('error', (err: Error) => {
log.warn(`Discord.js error: ${err}`)
})