-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
239 lines (182 loc) · 6.21 KB
/
bot.js
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
const stats = require('./stats.json');
const config = require('./config.js');
const Discord = require('discord.js');
const logger = require('./util/logger')
const fs = require('fs');
const client = new Discord.Client();
const token = config.token;
var isSharded = false;
// cache audios in memory
// TODO
// set listeners
setListeners(client);
// log our bot in
client.login(token);
function setListeners(client) {
/*
Disabled because this catches all kinds of errors that should be debugged instead of ignored.
process.on('uncaughtException', function (exception) {
logger.log("Global error: " + exception);
});
process.on("unhandledRejection", err => {
logger.log("Uncaught Promise Error: \n" + err.stack);
});
*/
client.on('ready', () => {
// if != null there are shards
isSharded = (client.shard != null);
if (!isSharded) {
// write PID-file
fs.writeFile('./trump.pid', process.pid);
}
logger.log(client.shard, "Ready!");
// wait 10 seconds after ready to ensure readiness and set status
setTimeout(function () {
logger.log(client.shard, "Status set");
client.user.setStatus('online');
client.user.setPresence({ game: { name: (isSharded ? "!trump --help (" + client.shard.id + ")" : "!trump --help"), type: 0 } });
}, 10000);
// write stats every 30 seconds
// dont use if the bot is startet by sharder.js!
if (!isSharded) {
setInterval(function () {
writeStats();
}, 30000);
}
});
client.on('reconnecting', () => {
logger.log(client.shard, "Reconnecting shard");
});
client.on("disconnect", closeevent => {
logger.log(client.shard, "Disconnected with code " + closeevent.code + " (" + closeevent.reason + ")!");
// https://github.com/hammerandchisel/discord-api-docs/issues/33
// 4005 == already authenticated
// 4004 == authentication failed
if (closeevent.code == 4005 ||
closeevent.code == 4004) {
return;
}
logger.log(client.shard, "Reconnecting automatically...");
client.destroy().then(() => client.login(token));
});
client.on('error', error => {
logger.log(client.shard, error);
});
// create listener for messages
client.on('message', message => {
handleMessage(message);
});
}
function handleMessage(message) {
var content = message.content.toLowerCase();
var textChannel = message.channel;
var guild = message.guild;
var author = message.author;
var politician;
if (content.startsWith("!trump")) {
politician = "trump";
}
if (content.startsWith("!clinton")) {
politician = "clinton";
}
if (content.startsWith("!merkel")) {
politician = "merkel";
}
if (content.startsWith("!erdogan")) {
politician = "erdogan";
}
if (content.startsWith("!farage")) {
politician = "farage";
}
if (content.startsWith("!adolf")) {
politician = "adolf";
}
if (politician == null) {
return;
}
// make sure the text channel is a guild channel (type = text)
if (textChannel.type != "text") {
textChannel.send("I can't be invoked in private messages, only in guilds.");
return;
}
logger.log(client.shard, " Handling message: '" + content + "'")
var options = new Object();
// default, will be overwritten by argument if needed
options.voiceChannel = message.member.voiceChannel;
options.play = true;
options.file = getRandomAudio(politician);
// has arguments?
content = content.replace("!" + politician, "").trim();
if (content != "") {
var argumentParser = require("./util/argumentParser");
argumentParser.parse(options, client, content, politician, guild, author, textChannel);
}
if (options.leave) {
var voiceConnection = client.voiceConnections.get(guild.id);
if (voiceConnection) {
voiceConnection.disconnect();
voiceConnection.channel.leave();
}
}
var isBusy = isBusyInGuild(guild);
if (isBusy) {
textChannel.send("I am currently needed in Channel '" + isBusy.name + "'.");
options.play = false;
}
if (options.play && options.file !== "") {
if (options.voiceChannel) {
playAudio(options.voiceChannel, options.file, politician, textChannel);
} else {
textChannel.send("You have to be in a voice channel to do this.");
}
}
}
function isBusyInGuild(guild) {
var connections = Array.from(client.voiceConnections.values());
for (i = 0; i < connections.length; i++) {
var connection = connections[i];
if (connection.channel.guild == guild) {
return connection.channel;
}
}
return false;
}
function playAudio(voiceChannel, file, politician, textChannel) {
// check for permissions first
if (!voiceChannel.permissionsFor(client.user.id).has("CONNECT")) {
textChannel.send("No permission to join this channel.")
return;
};
if (!voiceChannel.permissionsFor(client.user.id).has("SPEAK")) {
textChannel.send("No permission to speak in this channel.")
return;
};
logger.log(client.shard, "Playing " + file);
voiceChannel.join().then(connection => {
connection.playFile(file).on("end", () => {
connection.disconnect();
voiceChannel.leave();
});
}).catch(error => {
logger.log(client.shard, JSON.stringify(error));
});
}
function getRandomAudio(politician) {
var fs = require('fs');
var files = fs.readdirSync("./audio/" + politician);
var index = Math.floor(Math.random() * (files.length));
return "./audio/" + politician + "/" + files[index];
}
function writeStats() {
// write current stats
var fileName = './stats.json';
var file = require(fileName);
file.guildCount = client.guilds.size;
fs.writeFile(
fileName,
JSON.stringify(file, null, 2),
function (error) {
if (error) return logger.log(client.shard, error);
}
);
}