-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBot.js
More file actions
79 lines (65 loc) · 1.96 KB
/
Bot.js
File metadata and controls
79 lines (65 loc) · 1.96 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
const fs = require(`fs`);
const Discord = require(`discord.js`);
class Bot {
/**
* Initializes all modules, a Discord client, binds events.
* @constructor
*/
constructor() {
this.client = new Discord.Client();
// Dynamically load commands from files
this.commands = new Discord.Collection();
fs.readdirSync(`./Commands`)
.filter(file => file.endsWith(`.js`))
.filter(file => file !== `Command.js`)
.map(file => require(`./Commands/${file}`))
.filter(cmd => cmd.name)
.forEach(cmd => this.commands.set(cmd.name.toLowerCase(), new cmd()), this);
this.bindEvents();
}
/**
* Bind event functions.
*/
bindEvents() {
this.client.on(`ready`, this.onReady.bind(this));
this.client.on(`message`, this.onMessage.bind(this));
}
/**
* Login client to Discord.
*/
connect() {
this.client.login(process.env.AUTH_TOKEN);
}
/**
* Destroy Discord client.
*/
destroy() {
console.log(`Shutting down.`);
this.client.destroy();
}
/**
* Bot is connected to Discord.
*/
onReady() {
console.log(`Connected to Discord as ${this.client.user.username}#${this.client.user.discriminator} <@${this.client.user.id}>`);
}
/**
* Handles messages.
* @param {Message} Message Discord message object.
*/
onMessage(Message) {
// Ignore system, bot messages
if (Message.system || Message.author.bot) return;
// Ignore if message doesn't start with command character
if (!Message.content.startsWith(`!`)) return;
// Parse message, see if it matches command name or alias
const args = Message.content.slice(1).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = this.commands.get(commandName) || this.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
// If no command found, ignore
if (!command) return;
// Execute command
command.execute(Message, args);
}
}
module.exports = Bot;