-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.ts
279 lines (222 loc) · 7.09 KB
/
bot.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
274
275
276
277
import { Client, GuildMember, Message, MessageEmbed } from "discord.js";
import importFresh from "import-fresh";
import { Command } from "./command";
import CommandHandler from "./command-handler";
import DefineCmd from "./commands/define";
import PingCmd from "./commands/ping";
import ReloadCmd from "./commands/reload";
import TestCmd from "./commands/test";
import config from './config.json';
import WallCmd from "./commands/wall";
import { SAI } from "@noumenae/sai";
import QuestionCmd from "./commands/question";
import LevelCmd from "./commands/level";
import DictionaryCmd from "./commands/dictionary";
import CoinFlipCmd from "./commands/coin-flip";
import HelpCmd from "./commands/help";
// type DiscordChannel = TextChannel|DMChannel|NewsChannel;
class Bot {
private _commands : Command[] = [];
private _cmdHandler!: CommandHandler; // Set in _onSaiInit()
// In order: matches alias, role, and channel mentions
private _mentionEx = /<@!?&?#?\d+>/g;
private _channels = config.bot.access_channels;
private _sai = new SAI('./store', (res) => this._onSaiInit(res));
private _messageHandler = (msg: Message) => {
return void this._onMessage(msg);
};
/* TODO - This might cause async issues down the road.
If this value is ever changed during an async operation, then
we'll have to fallback to passing the Message object around.
*/
curMsg!: Message;
get Embed() {
return MessageEmbed;
}
get sai() {
return this._sai;
}
get commands() {
return this._cmdHandler.commands;
}
get curContent() {
return this.curMsg.content;
}
get curChannel() {
return this.curMsg.channel;
}
constructor(private _client: Client, private _resetCallback: () => void, reset = false) {
this._client.on('message', this._messageHandler);
if (!reset)
this._client.login(config.apiKeys.discord)
;
}
private _onSaiInit(err: Error|null) {
if (err) {
console.error(err);
process.exit();
}
this._populateCommands();
this._cmdHandler =
new (importFresh('./command-handler.js') as typeof CommandHandler)(this._commands, this)
;
}
private async _onMessage(msg: Message) {
this.curMsg = msg;
if (!this.isBotMentioned()) {
return this._cmdHandler.find(msg.content);
}
if (this._isQuestionEntry()) return;
if (this._isQuestion()) return;
}
private _isQuestionEntry() {
if (!this.hasValidRole(this.curMsg.member!, Bot.Role.Admin)) return false
;
const attachments = this.curMsg.attachments.array();
if (!attachments.length) return false
;
if (attachments[0].url.substr(-3) != '.md') {
this.curMsg.delete();
this.sendMedMsg(
'Oops! :nerd: Your file is missing the `.md` extension.'
);
}
this.curMsg.content = `;question ${attachments[0].url}`;
this._cmdHandler.find(this.curMsg.content, true);
return true;
}
private _isQuestion() {
const question = this.curContent.toLowerCase().replace(this._mentionEx, '').trim();
const resp = this._sai.ask(question)
;
if (typeof resp == 'number') {
return this.sendMedMsg(
`:confused: Sorry, I don't understand that question.`
);
}
if (!resp) {
return this.sendMedMsg(
`:nerd: That question doesn't match anything in my knowledge-base.`
);
}
return void this.curChannel.send(new this.Embed()
.setTitle (resp.title)
.setDescription (`${resp.answer}\u200b\n\u200b`)
.setColor (Bot.message_levels[resp.level][2])
.setFooter (`by ${resp.authors[0]}`)
);
}
private _populateCommands() {
this._commands = [
new (importFresh('./commands/ping.js' ) as typeof PingCmd)(this),
new (importFresh('./commands/reload.js' ) as typeof ReloadCmd)(this),
new (importFresh('./commands/test.js' ) as typeof TestCmd)(this),
new (importFresh('./commands/define.js' ) as typeof DefineCmd)(this),
new (importFresh('./commands/wall.js' ) as typeof WallCmd)(this),
new (importFresh('./commands/question.js' ) as typeof QuestionCmd)(this),
new (importFresh('./commands/level.js' ) as typeof LevelCmd)(this),
new (importFresh('./commands/dictionary.js' ) as typeof DictionaryCmd)(this),
new (importFresh('./commands/coin-flip.js' ) as typeof CoinFlipCmd)(this),
new (importFresh('./commands/help.js' ) as typeof HelpCmd)(this),
];
}
reset() {
this.sendHighMsg('', 'Resetting Bot');
this._client.off('message', this._messageHandler);
this._resetCallback();
}
reloadCmdHandler() {
this._populateCommands();
this._cmdHandler = new CommandHandler(this._commands, this);
}
hasValidRole(member: GuildMember, role: Bot.Role) {
if (member.id == config.bot.creatorId) {
return true;
}
return member.roles.cache.some(r => {
return r.name == role;
});
}
isBotMentioned() {
const botId = `${config.bot.id}>`;
if (!this.curMsg.content.match(this._mentionEx)) return false;
if (!this.curMsg.content.includes(botId)) return false;
return true;
}
setMessage(title: string, priority = -1, description: string) {
return (
new this.Embed()
.setTitle(title)
.setDescription(description)
.setColor(this.colorFromPriority(priority))
);
}
sendMsg(description: string, title: string, color: string) {
this.curMsg.channel.send(
new this.Embed()
.setTitle(title)
.setDescription(description)
.setColor(color)
);
}
colorFromPriority(priority: Bot.MessagePriority) {
const p = Bot.MessagePriority;
if (p.LOW == priority) return '#57E0B8';
if (p.MEDIUM == priority) return '#FFD200';
if (p.HIGH == priority) return '#FF559D';
if (p.BLACK == priority) return '#6C00FF';
return '#aaaaaa';
}
/** Send low priority message. */
sendLowMsg(content: string, title = '') {
return void this.curChannel.send(
this.setMessage(title, Bot.MessagePriority.LOW, content)
);
}
/** Send medium priority message. */
sendMedMsg(content: string, title = '') {
return void this.curChannel.send(
this.setMessage(title, Bot.MessagePriority.MEDIUM, content)
);
}
/** Send high priority message. */
sendHighMsg(content: string, title = '') {
return void this.curChannel.send(
this.setMessage(title, Bot.MessagePriority.HIGH, content)
);
}
sendException(description: string, err: Error) {
this.sendHighMsg(
`${description}\n\n**Message**\n\`\`\`${err.message}\`\`\`\n` +
`**Stack Trace**\n\`\`\`${err.stack}\`\`\``,
'Fatal Error Occurred'
);
}
}
namespace Bot {
export enum MessageLevel {
WHITE = 0,
BLUE,
GREEN,
YELLOW,
ORANGE,
RED,
CHOCOLATE,
GRAY,
BLACK
}
export enum MessagePriority {
LOW = 0,
MEDIUM,
HIGH,
BLACK,
}
export enum Role {
Everyone = '@everyone',
Admin = 'Admin',
}
export const message_levels =
(importFresh('./config.json') as typeof config)
.bot.message_levels as [number, string, string][];
}
export = Bot;