-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathXiao.js
435 lines (402 loc) · 15 KB
/
Xiao.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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
require('dotenv').config();
const { XIAO_TOKEN, OWNERS, XIAO_PREFIX, INVITE } = process.env;
const { mkdir } = require('fs/promises');
const path = require('path');
const math = require('mathjs');
const {
GatewayIntentBits,
Partials,
AllowedMentionsTypes,
PermissionFlagsBits,
EmbedBuilder,
ActivityType
} = require('discord.js');
const Client = require('./structures/Client');
const client = new Client({
commandPrefix: XIAO_PREFIX,
mentionPrefix: true,
owner: OWNERS.split(','),
invite: INVITE,
allowedMentions: {
parse: [AllowedMentionsTypes.User],
repliedUser: true
},
partials: [Partials.GuildMember, Partials.Channel],
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildEmojisAndStickers,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.MessageContent
]
});
const { formatNumber, list, checkFileExists } = require('./util/Util');
client.registry
.registerDefaultTypes()
.registerTypesIn(path.join(__dirname, 'types'))
.registerGroups([
['util', 'Utility (Owner)'],
['util-public', 'Utility'],
['util-voice', 'Utility (Voice)'],
['info', 'Discord Information'],
['random-res', 'Random Response'],
['random-img', 'Random Image'],
['random-seed', 'Seeded Randomizers'],
['single', 'Single Response'],
['auto', 'Automatic Response'],
['events', 'Events'],
['search', 'Search'],
['pokedex', 'Pokédex'],
['analyze', 'Analyzers'],
['games-sp', 'Single-Player Games'],
['games-mp', 'Multi-Player Games'],
['edit-face', 'Face Manipulation'],
['edit-image', 'Image Manipulation'],
['edit-image-text', 'Image Text Manipulation'],
['edit-avatar', 'Avatar Manipulation'],
['edit-meme', 'Meme Generators'],
['edit-text', 'Text Manipulation'],
['edit-number', 'Number Manipulation'],
['voice', 'Play Audio'],
['remind', 'Reminders'],
['phone', 'Phone'],
['cleverbot', 'Cleverbot'],
['other', 'Other']
])
.registerCommandsIn(path.join(__dirname, 'commands'));
client.on('ready', async () => {
client.logger.info(`[READY] Logged in as ${client.user.tag}! ID: ${client.user.id}`);
// Make temp directories
const tmpFolderExists = await checkFileExists(path.join(__dirname, 'tmp'));
if (!tmpFolderExists) await mkdir(path.join(__dirname, 'tmp'));
const decTalkTmpFolderExists = await checkFileExists(path.join(__dirname, 'tmp', 'dec-talk'));
if (!decTalkTmpFolderExists) await mkdir(path.join(__dirname, 'tmp', 'dec-talk'));
// Check for DECTalk files and disable it if not present
const dectalkFolderExists = await checkFileExists(path.join(__dirname, 'dectalk'));
if (dectalkFolderExists) {
const sayExists = await checkFileExists(path.join(__dirname, 'dectalk', 'say.exe'));
const dicExists = await checkFileExists(path.join(__dirname, 'dectalk', 'dtalk_us.dic'));
const dllExists = await checkFileExists(path.join(__dirname, 'dectalk', 'dectalk.dll'));
const msvExists = await checkFileExists(path.join(__dirname, 'dectalk', 'MSVCRTd.DLL'));
if (!sayExists || !dicExists || !dllExists || !msvExists) {
const missing = [];
if (!sayExists) missing.push('say.exe');
if (!dicExists) missing.push('dtalk_us.dic');
if (!dllExists) missing.push('dectalk.dll');
if (!msvExists) missing.push('MSVCRTd.DLL');
client.registry.commands.get('dec-talk').disable();
client.logger.info(`[DISABLED] ${list(missing)} not present in dectalk/ folder. dectalk has been disabled.`);
}
} else {
client.registry.commands.get('dec-talk').disable();
client.logger.info('[DISABLED] No dectalk/ folder. dectalk has been disabled.');
}
// Check for API keys and disable commands that need them if not present
if (!process.env.REDIS_HOST || !process.env.REDIS_PASS) {
client.logger.error('[REDIS] No REDIS_HOST or REDIS_PASS in env. Exiting process.');
process.exit(1);
}
if (!process.env.BITLY_KEY) {
client.registry.commands.get('shorten-url').disable();
client.logger.info('[DISABLED] No BITLY_KEY in env. shorten-url has been disabled.');
}
if (!process.env.CLEVERBOT_KEY) {
client.registry.commands.get('cleverbot').disable();
client.registry.commands.get('cleverbot-end').disable();
client.logger.info('[DISABLED] No CLEVERBOT_KEY in env. cleverbot and cleverbot-end have been disabled.');
}
if (!process.env.GITHUB_ACCESS_TOKEN) {
client.registry.commands.get('github').disable();
client.registry.commands.get('changelog').disable();
client.logger.info('[DISABLED] No GITHUB_ACCESS_TOKEN in env. github and changelog have been disabled.');
}
if (!process.env.GOV_KEY) {
client.registry.commands.get('apod').disable();
client.logger.info('[DISABLED] No GOV_KEY in env. apod has been disabled.');
}
if (!process.env.SPOTIFY_KEY || !process.env.SPOTIFY_SECRET) {
client.registry.commands.get('guess-song').disable();
client.logger.info('[DISABLED] No SPOTIFY_KEY or SPOTIFY_SECRET in env. guess-song has been disabled.');
}
if (!process.env.THECATAPI_KEY) {
client.registry.commands.get('cat').disable();
client.logger.info('[DISABLED] No THECATAPI_KEY in env. cat has been disabled.');
}
if (!process.env.THEDOGAPI_KEY) {
client.registry.commands.get('dog').disable();
client.logger.info('[DISABLED] No THEDOGAPI_KEY in env. dog has been disabled.');
}
if (!process.env.WEBSTER_KEY) {
client.registry.commands.get('word-of-the-day').disable();
client.registry.commands.get('word-chain').disable();
client.registry.commands.get('define').disable();
client.logger.info('[DISABLED] No WEBSTER_KEY in env. word-of-the-day, word-chain, and define have been disabled.');
}
// Interval to change activity every minute
client.user.setActivity('Good morning, world!', { type: ActivityType.Custom });
setInterval(() => {
const activity = client.activities[Math.floor(Math.random() * client.activities.length)];
const text = typeof activity.text === 'function' ? activity.text(client) : activity.text;
client.user.setActivity(text, { type: activity.type });
}, 60000);
// Set up disabled commands
try {
const disabled = await client.redis.db.hgetall('disabled');
for (const command of Object.keys(disabled)) {
client.registry.commands.get(command).disable();
client.logger.info(`[DISABLED] Disabled the ${command} command.`);
}
} catch (err) {
client.logger.error(`[DISABLED] Error while disabling commands:\n${err.stack}`);
}
// Import command-leaderboard.json
try {
const results = client.importCommandLeaderboard();
if (results) {
client.logger.info('[LEADERBOARD] command-leaderboard.json successfully loaded.');
} else {
client.logger.error('[LEADERBOARD] command-leaderboard.json is not formatted correctly.');
}
} catch (err) {
client.logger.error(`[LEADERBOARD] Could not parse command-leaderboard.json:\n${err.stack}`);
}
// Import command-last-run.json
try {
const results = client.importLastRun();
if (results) {
client.logger.info('[LASTRUN] command-last-run.json successfully loaded.');
} else {
client.logger.error('[LASTRUN] command-last-run.json is not formatted correctly.');
}
} catch (err) {
client.logger.error(`[LASTRUN] Could not parse command-last-run.json:\n${err.stack}`);
}
// Export command-leaderboard.json and command-last-run.json every 30 minutes
setInterval(() => {
try {
client.exportCommandLeaderboard();
client.logger.info('[LEADERBOARD] command-leaderboard.json successfully exported.');
} catch (err) {
client.logger.error(`[LEADERBOARD] Failed to export command-leaderboard.json:\n${err.stack}`);
}
try {
client.exportLastRun();
client.logger.info('[LASTRUN] command-last-run.json successfully exported.');
} catch (err) {
client.logger.error(`[LASTRUN] Failed to export command-last-run.json:\n${err.stack}`);
}
}, 1.8e+6);
// Import blacklist
try {
const results = client.importBlacklist();
if (results) {
client.logger.info('[BLACKLIST] blacklist.json successfully loaded.');
} else {
client.logger.error('[BLACKLIST] blacklist.json is not formatted correctly.');
}
} catch (err) {
client.logger.error(`[BLACKLIST] Could not parse blacklist.json:\n${err.stack}`);
}
// Make sure bot is not in any blacklisted guilds
for (const id of client.blacklist.guild) {
try {
const guild = await client.guilds.fetch(id, false);
await guild.leave();
client.logger.info(`[BLACKLIST] Left blacklisted guild ${id}.`);
} catch {
if (!client.guilds.cache.has(id)) continue;
client.logger.info(`[BLACKLIST] Failed to leave blacklisted guild ${id}.`);
}
}
// Make sure bot is not in any guilds owned by a blacklisted user
let guildsLeft = 0;
for (const guild of client.guilds.cache.values()) {
if (client.blacklist.user.includes(guild.ownerID)) {
try {
await guild.leave();
guildsLeft++;
} catch {
client.logger.info(`[BLACKLIST] Failed to leave blacklisted guild ${guild.id}.`);
}
}
}
if (guildsLeft > 0) client.logger.info(`[BLACKLIST] Left ${guildsLeft} guilds owned by blacklisted users.`);
// Set up existing timers
try {
await client.timers.fetchAll();
client.logger.info('[TIMERS] All timers imported.');
} catch (err) {
client.logger.error(`[TIMERS] Failed to import timers\n${err.stack}`);
}
// Register all canvas fonts
try {
await client.fonts.registerFontsIn(path.join(__dirname, 'assets', 'fonts'));
client.logger.info('[FONTS] All fonts loaded.');
} catch (err) {
client.logger.error(`[FONTS] Failed to load fonts\n${err.stack}`);
}
// Set up moment timezones
try {
client.setTimezones();
client.logger.info('[TIMEZONES] Set all custom timezones.');
} catch (err) {
client.logger.error(`[TIMEZONES] Failed to set timezones\n${err.stack}`);
}
// Add bananas unit to mathjs
math.createUnit('banana', {
definition: '0.178 meters',
aliases: ['bananas']
});
// Fetch adult site list
try {
await client.fetchAdultSiteList();
client.logger.info('[ADULT SITES] Fetched adult site list.');
} catch (err) {
client.logger.error(`[ADULT SITES] Failed to fetch list\n${err.stack}`);
}
// Set up nsfwjs
try {
await client.tensorflow.loadNSFWJS();
client.logger.info('[NSFWJS] Loaded NSFWJS.');
} catch (err) {
client.logger.error(`[NSFWJS] Failed to load NSFWJS\n${err.stack}`);
}
// Set up face detection
try {
await client.tensorflow.loadFaceDetector();
client.logger.info('[FACE DETECTOR] Loaded face detector.');
} catch (err) {
client.logger.error(`[FACE DETECTOR] Failed to load face detector\n${err.stack}`);
}
// Set up stylize models
try {
await client.tensorflow.loadStyleModel();
await client.tensorflow.loadTransformerModel();
client.logger.info('[STYLIZE] Loaded stylize models.');
} catch (err) {
client.logger.error(`[STYLIZE] Failed to load stylize models\n${err.stack}`);
}
// Fetch all members
try {
for (const guild of client.guilds.cache.values()) {
await guild.members.fetch();
}
client.logger.info('[MEMBERS] Fetched all guild members.');
} catch (err) {
client.logger.error(`[MEMBERS] Failed to fetch guild members\n${err.stack}`);
}
});
client.on('messageCreate', async msg => {
const hasText = Boolean(msg.content);
const hasImage = msg.attachments.size !== 0;
const hasEmbed = msg.embeds.length !== 0;
if (msg.author.bot || (!hasText && !hasImage && !hasEmbed)) return;
if (client.blacklist.user.includes(msg.author.id)) return;
if (client.dispatcher.isCommand(msg)) return;
if (client.games.has(msg.channel.id)) return;
// Cleverbot handler
const cleverbot = client.cleverbots.get(msg.channel.id);
if (cleverbot) {
if (!cleverbot.shouldRespond(msg)) return;
client.registry.commands.get('cleverbot').uses++;
msg.channel.sendTyping().catch(() => null);
try {
const response = await cleverbot.respond(msg.cleanContent);
await msg.reply(response);
return;
} catch (err) {
if (err.status === 503) {
await msg.reply('Monthly API limit reached. Ending conversation.');
client.cleverbots.delete(msg.channel.id);
return;
}
await msg.reply('Sorry, blacked out there for a second. Come again?');
return;
}
}
// Phone message handler
const origin = client.phone.find(call => call.origin.id === msg.channel.id);
const recipient = client.phone.find(call => call.recipient.id === msg.channel.id);
if (!origin && !recipient) return;
const call = origin || recipient;
if (call.originDM && call.startUser.id !== msg.author.id) return;
if (msg.guild && (!msg.channel.topic || !msg.channel.topic.includes('<xiao:phone>'))) return;
if (!call.active) return;
try {
await call.send(origin ? call.recipient : call.origin, msg, hasText, hasImage, hasEmbed);
} catch {
return; // eslint-disable-line no-useless-return
}
});
client.on('guildCreate', async guild => {
if (client.blacklist.guild.includes(guild.id) || client.blacklist.user.includes(guild.ownerID)) {
try {
await guild.leave();
return;
} catch {
return;
}
}
try {
await guild.members.fetch();
client.logger.info('[MEMBERS] Fetched all guild members for new server.');
} catch (err) {
client.logger.error(`[MEMBERS] Failed to fetch guild members for new server\n${err.stack}`);
}
if (guild.systemChannel && guild.systemChannel.permissionsFor(client.user).has(PermissionFlagsBits.SendMessages)) {
try {
const usage = client.registry.commands.get('help').usage('');
await guild.systemChannel.send(`Hi! I'm Xiao, use ${usage} to see my commands, yes?`);
} catch {
// Nothing!
}
}
const joinLeaveChannel = await client.fetchJoinLeaveChannel();
if (joinLeaveChannel) {
const owner = await guild.fetchOwner();
const embed = new EmbedBuilder()
.setColor(0x7CFC00)
.setThumbnail(guild.iconURL({ extension: 'png' }))
.setTitle(`Joined ${guild.name}!`)
.setFooter({ text: `ID: ${guild.id}` })
.setTimestamp()
.addField('❯ Members', formatNumber(guild.memberCount))
.addField('❯ Owner', owner.user.tag);
await joinLeaveChannel.send({ embeds: [embed] });
}
});
client.on('guildDelete', async guild => {
const joinLeaveChannel = await client.fetchJoinLeaveChannel();
if (joinLeaveChannel) {
const owner = client.users.cache.get(guild.ownerID);
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setThumbnail(guild.iconURL({ extension: 'png' }))
.setTitle(`Left ${guild.name}...`)
.setFooter({ text: `ID: ${guild.id}` })
.setTimestamp()
.addField('❯ Members', formatNumber(guild.memberCount))
.addField('❯ Owner', owner ? owner.tag : guild.ownerID);
await joinLeaveChannel.send({ embeds: [embed] });
}
});
client.on('disconnect', event => {
client.logger.error(`[DISCONNECT] Disconnected with code ${event.code}.`);
client.exportCommandLeaderboard();
client.exportLastRun();
process.exit(0);
});
client.on('error', err => client.logger.error(err.stack));
client.on('warn', warn => client.logger.warn(warn));
client.on('commandRun', command => {
if (command.unknown) return;
client.logger.info(`[COMMAND] ${command.name} was used.`);
});
client.on('commandError', (command, err) => client.logger.error(`[COMMAND:${command.name}]\n${err.stack}`));
client.login(XIAO_TOKEN);