-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
588 lines (584 loc) · 31.1 KB
/
index.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//"use strict";
// NPM modules and stuff
const Discord = require("discord.js");
const { env: envVars } = require("process");
const fetch = require("node-fetch");
const cFlags = require("country-flag-emoji");
const sqlite3 = require("sqlite3");
const { promisify } = require("util");
const { version: qbVersion } = require("./package.json");
const chalk = require("chalk");
let LeagueAPI = require("leagueapiwrapper");
const { startCase, escapeRegExp, camelCase, uniqBy } = require('lodash');
const opggRegions = require("./data/opggRegions.json")
const { Config: SpellCfg, SpellChecker } = require('spech');
const bot = new Discord.Client();
require("dotenv").config();
// config stuff
let configFile;
try {
configFile = require("./config.json");
} catch (e) {
if (e.code != "MODULE_NOT_FOUND") {
throw e;
}
configFile = { "help-domain": "quotobot.js.org" };
}
const authorPictures = require("./db/portraits.js");
const authorWikis = require("./db/wikis.js")
let token;
if (configFile.token == "your-token-here-inside-these-quotes") {
token = envVars.QBTOKEN;
} else if (!configFile.token) { token = envVars.QBTOKEN; }
else { token = configFile.token; } // uses env var if configFile.token isn't there or is the placeholder
// handle starting up the stocks API
let stocksEnabled = false;
if (configFile.stockToken || envVars.QBSTOCKS) {
stocksEnabled = true;
}
if (!stocksEnabled) {
console.log("Your stock API key is falsy (usually undefined). Stock lookups will not work.")
}
const helpDomain = envVars.QBSTATUS || configFile["help-domain"] || undefined;
let helpMessage;
// handle starting up the League API
let leagueEnabled;
try {
if (!envVars.QBRGKEY && !configFile.riotKey) {
throw new Error("The Riot key is falsy (usually undefined). Did you put a key?")
}
else {
// eslint-disable-next-line no-undef
LeagueAPI = new LeagueAPI(envVars.QBRGKEY || configFile.riotKey, Region.NA);
LeagueAPI.getStatus()
.then(() => {
leagueEnabled = true;
console.log("League of Legends lookups are enabled.")
})
.catch(e => {
leagueEnabled = false;
console.error(chalk`{redBright ${e}}`);
console.error(chalk`{redBright Due to the above error, League of Legends lookups won't work.}`);
});
}
}
catch (e) {
leagueEnabled = false;
console.error(chalk`{redBright ${e}}`);
console.error(chalk`{redBright Due to the above error, League of Legends lookups won't work.}`);
}
// constants and functions
const prefix = configFile.prefix || envVars.QBPREFIX || "~";
const norm = text => text
.trim()
.toLowerCase()
.replace(/\s+/, " "); //"normalize" text
const urlPattern = /^(?:http|https):\/\/[^ "]+$/;
const icons = require("./db/icons.js");
const sp = "📕 Scarlet Pimpernel by Baroness Orczy";
const randQuoteQuery = "SELECT quote, source FROM Quotes WHERE id IN (SELECT id FROM Quotes ORDER BY RANDOM() LIMIT 1);";
const usedWeatherRecently = new Set(), usedStocksRecently = new Set(), usedLeagueRecently = new Set(), usedSpellingRecently = new Set();
const asciiLogo = chalk`{blueBright
____ __ __ __
/ __ \\__ _____ / /____ / / ___ / /_
/ /_/ / // / _ \\/ __/ _ \\/ _ \\/ _ \\/ __/
\\___\\_\\_,_/\\___/\\__/\\___/_.__/\\___/\\__/}` // Quotobot in ASCII art
const db = new sqlite3.cached.Database("./db/quotes.db", sqlite3.OPEN_READONLY);
db.each = promisify(db.each);
const embed = Object.freeze({
"error": (description, code = "", title = "Error") => {
if (!code) {
code = "";
} else {
code = "`" + code + "`";
}
return new Discord.MessageEmbed()
.setColor("ff0000")
.setAuthor(title, icons.warn)
.setDescription(`${description} ${code}`);
},
"simple": (text, attr, title = "Quote") =>
new Discord.MessageEmbed()
.setColor(6765239)
.setAuthor("ㅤ", icons.quote)
.setFooter(`—${attr}`, icons.empty)
.setDescription(text)
.setTitle(title),
"stocks": ({ o: open, h: high, l: low, c: current, pc: prevClose, t: timestamp },
symbol) => new Discord.MessageEmbed()
.setTitle(`Current price for ${symbol.toUpperCase()} is \`${current.toFixed(2)}\``)
.setURL("https://finance.yahoo.com/quote/" + symbol)
.addField("High", "`" + high.toFixed(2) + "`", true)
.addField("Low", "`" + low.toFixed(2) + "`", true)
.addField("Open", "`" + open.toFixed(2) + "`", true)
.addField("Previous Close", "`" + prevClose.toFixed(2) + "`", true)
.setColor(current - prevClose >= 0 ? "4CAF50" : "F44336")
.setFooter("Data from Finnhub")
.setTimestamp(new Date(timestamp * 1000)),
"currWeather": ( // formats the embed for the weather
temp, maxTemp, minTemp,
pressure, humidity, wind,
cloudiness, icon,
author,
cityName, country, units, id, timestamp) =>
new Discord.MessageEmbed()
.setColor("ff9800") // yellow
.setAuthor(`Hello, ${author}`)
.setTitle(`It's ${temp}°${units == "metric" ? "C" : "F"} in ${cityName}, ${country}`)
.setURL(`https://openweathermap.org/city/${id}`)
.addField(`🌡 Max Temp`, `${maxTemp}°${units == "metric" ? "C" : "F"}`, true)
.addField(`🌡 Min Temp`, `${minTemp}°${units == "metric" ? "C" : "F"}`, true)
.addField(`💧 Humidity`, `${humidity}%`, true)
.addField(`💨 Wind Speed`, wind, true)
.addField(`📊 Pressure`, `${pressure} hpa`, true)
.addField(`⛅️ Cloudiness`, cloudiness, true)
.setFooter(`This is in ${units} units — you can try ${prefix}weather ${units == "metric" ? "imperial" : "metric"} ${cityName} • Data from OpenWeatherMap`, icons.bulb)
.setThumbnail(`https://openweathermap.org/img/wn/${icon}@2x.png`)
.setTimestamp(new Date(timestamp * 1000)),
})
bot.once("ready", () => {
console.log(asciiLogo);
db.each(randQuoteQuery).then(
({ quote, source }) => console.log(chalk`{blueBright "${quote}" –${source}}`)
)
let invText;
if (configFile.clientID) {
invText = `https://discordapp.com/oauth2/authorize?client_id=${configFile.clientID}&scope=bot&permissions=${configFile.permissionValue.toString() || "280576"}`;
} else {
invText = "Available in the Discord developer portal";
}
let leagueText;
if (leagueEnabled === false) leagueText = "🚫 League commands will not work"
else if (leagueEnabled) leagueText = "✅";
else leagueText = "💬 Still trying to start the League API";
console.table({
"bot version": qbVersion, prefix,
"username": "@" + bot.user.username + "#" + bot.user.discriminator,
"invite link": invText,
"status": `${prefix}help • ${helpDomain}`,
"server count": bot.guilds.cache.size,
"weather key defined?": (configFile["weather-token"] || envVars.QBWEATHER ? "✅" : "🚫 weather will not work"),
"help link": (configFile.helpURL || "default"),
"stocks enabled?": (stocksEnabled ? "✅" : "🚫 stock commands will not work"),
"league enabled?": leagueText
})
if (helpDomain) {
bot.user.setActivity(`${prefix}help • ${helpDomain}`, { type: "WATCHING" }); // Custom status "Watching example.qb"
}
helpMessage = `See this link for the commands: ${envVars.QBHELPURL || configFile.helpURL || "https://quotobot.js.org/wiki/Help"} (v${qbVersion}~${bot.guilds.cache.size})`;
});
if (!token) {
throw new Error("The token is falsy (usually undefined). Make sure you actually put a token in the config file or in the environment variable QBTOKEN.");
}
process.on("SIGTERM", async () => {
try {
if (envVars.QBEXITHOOK) {
const [id, tokn] = envVars.QBEXITHOOK.split("/");
const hook = new Discord.WebhookClient(id, tokn);
const mbed = new Discord.MessageEmbed()
.setTitle("Shutdown")
.setColor("BLUE")
.setTimestamp();
await hook.send("Quotobot is shutting down.", {
embeds: [mbed],
});
}
process.exit(0);
} catch (err) {
console.error(err);
process.exit(1);
}
})
process.on("uncaughtException", async (err) => {
if (err.name == "DiscordAPIError" && err.message == "Missing Permissions") return;
console.log(err);
try {
if (envVars.QBEXITHOOK) {
const [id, tokn] = envVars.QBEXITHOOK.split("/");
const hook = new Discord.WebhookClient(id, tokn);
const mbed = new Discord.MessageEmbed()
.setDescription(err.stack)
.setTitle("Exception")
.setColor("RED")
.setTimestamp();
await hook.send("Quotobot had an error and is shutting down.", {
embeds: [mbed],
});
}
} catch (cerr) {
console.error(cerr);
}
process.exit(1);
})
const splchecker = new SpellChecker(new SpellCfg({ ignoreCase: false, languages: ['en-us'] }));
splchecker.addDictionaryPhrase('Quotobot');
splchecker.addDictionaryPhrase('quotobot');
splchecker.addProviderByConfig({ name: 'hunspell' });
bot.login(token);
bot.on("warn", m => console.warn(chalk`{yellow Warning: ${m}}`));
bot.on("error", m => console.error(chalk`{redBright Error: ${m}}`));
bot.on("message", message => {
if (message.author.id == envVars?.QBBAN) return;
const prefixRegex = new RegExp(`^(<@!?${bot.user.id}>|${escapeRegExp(prefix)})\\s*`);
if ((!prefixRegex.test(message.content)) || message.author.bot) return;
const [matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const command = args.shift().trim().toLowerCase();
console.count("Command");
switch (command) {
case "amiadmin":
if (!message.member) return message.reply("Trick question.");
if (!message.member.hasPermission("ADMINISTRATOR")) return message.reply("you're not admin!");
else return message.reply("you are admin!");
case "testdm":
message.author.send("Looks like the DM worked! You can send commands in here.")
.catch(error => {
if (error.message == "Cannot send messages to this user") {
message.reply("Oof, you seem to have DMs off.");
} else { console.error(error); }
});
break;
case "help":
// message.channel.send(new Discord.MessageEmbed()
// .setTitle("⁉️ Click here for the commands.")
// .setColor("009688")
// .setURL(envVars.QBHELPURL || configFile.helpURL || "https://quotobot.js.org/wiki/Help")
// .setFooter(`v${qbVersion}~${bot.guilds.cache.size}`));
message.channel.send(helpMessage);
break;
case "ping":
message.channel.send("Pong!");
break;
case "randomquote":
case "randquote":
case "rquote":
case "quote":
{
(async () => {
try {
let { quote, source } = await db.each(randQuoteQuery);
let em = embed.simple(quote, source, "Random Quote");
if (authorPictures[source.trim()] && urlPattern.test(authorPictures[source.trim()])) {
em.setThumbnail(authorPictures[source.trim()]);
em.setFooter(`—${source}`, authorPictures[source.trim()]);
}
if (source.trim() in authorWikis) {
if (authorWikis[source.trim()] !== null)
em.setAuthor("Click here for author's wiki", icons.quote, "https://en.wikipedia.org/wiki/" + encodeURIComponent(authorWikis[source.trim()]));
} else {
em.setAuthor("Click here for author's wiki", icons.quote, "https://en.wikipedia.org/wiki/" + encodeURIComponent(source.trim()));
}
message.channel.send(em);
} catch (err) {
message.reply(embed.error("There was an error on our end. Try again later.", "ERR_DATABASE"));
console.error(err.message);
}
})();
// (I've given this quote ${randomQuote.usage} times before)
/* db.run(`Update Quotes set usage = ? where id = ?`,
[randomQuote.usage + 1, randomQuote.id],
(error) => { if (error) { console.log(error.message); } }
); */
break;
}
case "shortquot":
case "tweetquote":
case "shortquote":
{
(async () => {
try {
let { quote, source } = await db.each("SELECT quote, source FROM Quotes WHERE id IN (SELECT id FROM Quotes where length(quote) <= 140 ORDER BY RANDOM() LIMIT 1);");
let em = embed.simple(quote, source, "Random Quote");
if (authorPictures[source.trim()] && urlPattern.test(authorPictures[source.trim()])) {
em.setThumbnail(authorPictures[source.trim()]);
em.setFooter(`—${source}`, authorPictures[source.trim()]);
}
em.setAuthor("Click here to tweet this quote!", icons.quote, `https://twitter.com/intent/tweet?text=${encodeURIComponent(`As ${source} once said, "${quote}" (from Quotobot <${envVars.QBSTATUS || configFile.helpDomain || "quotobot.js.org"}>)`)}`);
message.channel.send(em);
} catch (err) {
message.reply(embed.error("There was an error on our end. Try again later.", "ERR_DATABASE"));
console.error(err.message);
}
})();
break;
}
case "longquote":
case "longquot":
{
(async () => {
try {
let { quote, source } = await db.each("SELECT quote, source FROM Quotes WHERE id IN (SELECT id FROM Quotes where length(quote) > 140 ORDER BY RANDOM() LIMIT 1);");
let em = embed.simple(quote, source, "Random Quote");
if (authorPictures[source.trim()] && urlPattern.test(authorPictures[source.trim()])) {
em.setThumbnail(authorPictures[source.trim()]);
em.setFooter(`—${source}`, authorPictures[source.trim()]);
}
if (source.trim() in authorWikis) {
if (authorWikis[source.trim()] !== null)
em.setAuthor("Click here for author's wiki", icons.quote, "https://en.wikipedia.org/wiki/" + encodeURIComponent(authorWikis[source.trim()]));
} else {
em.setAuthor("Click here for author's wiki", icons.quote, "https://en.wikipedia.org/wiki/" + encodeURIComponent(source.trim()));
}
message.channel.send(em);
} catch (err) {
message.reply(embed.error("There was an error on our end. Try again later.", "ERR_DATABASE"));
console.error(err.message);
}
})();
break;
}
case "bibot":
message.channel.send(embed.simple("Morbleu!", sp));
break;
case "intenselove":
message.channel.send(embed.simple(
"He seemed so devoted — a very slave — and there was a certain latent intensity in that love which had fascinated her.", sp));
break;
case "contempt":
message.channel.send(embed.simple(
"Thus human beings judge of one another, superficially, casually, throwing contempt on one another, with but little reason, and no charity.", sp));
break;
case "percysmart":
message.channel.send(embed.simple(
"He was calmly eating his soup, laughing with pleasant good-humour, as if he had come all the way to Calais for the express purpose of enjoying supper at this filthy inn, in the company of his arch-enemy.", sp));
break;
case "moneynomatter":
message.channel.send(embed.simple(
"Those friends who knew, laughed to scorn the idea that Marguerite St. Just had married a fool for the sake of the worldly advantages with which he might endow her. They knew, as a matter of fact, that Marguerite St. Just cared nothing about money, and still less about a title.", sp));
break;
case "brains":
message.channel.send(embed.simple(
'"Money and titles may be hereditary," she would say, "but brains are not."', sp));
break;
case "sppoem":
message.channel.send(embed.simple(
"We seek him here, we seek him there, those Frenchies seek him everywhere. Is he in heaven? — Is he in hell? That demmed, elusive Pimpernel?", sp));
break;
case "haters":
message.channel.send(embed.simple(
"How that stupid, dull Englishman ever came to be admitted within the intellectual circle which revolved round “the cleverest woman in Europe,” as her friends unanimously called her, no one ventured to guess—a golden key is said to open every door, asserted the more malignantly inclined.", sp));
break;
case "weathermetric":
case "weather": {
let timeout = configFile.weatherTimeout || envVars.QBWTIMEOUT || 15000
if (usedWeatherRecently.has(message.author.id)) {
message.reply(embed.error(`You need to wait ${timeout / 1000} seconds before asking for the weather again.`, "ERR_RATE_LIMIT", "Slow down!"));
} else {
(async () => {
if (!(configFile["weather-token"] || envVars.QBWEATHER)) {
message.reply(embed.error("Weather isn't currently working. Sorry about that.", "ERR_FALSY_WEATHER_KEY"));
console.error("Error: The weather key is falsy (usually undefined). Make sure you actually put a key in the config.json or in env.QBWEATHER.")
return;
}
if (!args[0]) {
message.reply(embed.error("You didn't include any arguments. Re-run the command with *metric* or *imperial* and the city name."));
return null;
}
let units = ["metric", "imperial"].includes(norm(args[0])) ? norm(args[0]) : "metric";
let city = !(["metric", "imperial"].includes(norm(args[0]))) ? args.slice(0).join(" ") : args.slice(1).join(" ");
if (!city) {
message.reply(embed.error("You didn't include a city name. Re-run the command with the city name.", `args: ${args.toString()}`));
return null;
}
let windUnits = units == "imperial" ? "mph" : "m/s";
try {
let apiData = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=${units}&APPID=${configFile["weather-token"] || envVars.QBWEATHER}`
);
let jd = await apiData.json();
if (!apiData.ok) {
message.reply(embed.error("There was an error getting the weather.", `${jd.cod || apiData.status}: ${jd.message || apiData.statusText}`));
return;
}
let { temp, temp_max, temp_min, humidity, pressure } = jd.main;
let currentTemp = Math.round(temp);
let maxTemp = Math.round(temp_max);
let minTemp = Math.round(temp_min);
let wind = jd.wind.speed + " " + windUnits;
let { username } = message.author;
let { icon, description: cloudness } = jd.weather[0];
let { id, name: displayCity, dt: timestamp } = jd;
let { country } = jd.sys;
country += cFlags.get(country).emoji ? " " + cFlags.get(country).emoji : "";
message.reply(embed.currWeather(currentTemp, maxTemp, minTemp, pressure, humidity, wind, cloudness, icon, username, displayCity, country, units, id, timestamp));
// Adds the user to the set so that they can't get weather for some time
usedWeatherRecently.add(message.author.id);
setTimeout(() => {
// Removes the user from the set after timeout
usedWeatherRecently.delete(message.author.id);
}, timeout);
} catch (err) {
message.reply(embed.error("There was an error getting the weather.", `${err.toString().replaceAll(configFile["weather-token"] || envVars.QBWEATHER, "")}`));
} finally {
if (city == "constantinople") message.reply("https://youtube.com/watch?v=vsQrKZcYtqg");
}
})();
}
break;
}
case "gotanygrapes":
message.reply("https://www.youtube.com/watch?v=MtN1YnoL46Q"); // duck song
break;
case "stocks":
case "stock": {
const timeout = configFile.stockTimeout || envVars.QBSTIMEOUT || configFile.weatherTimeout || envVars.QBWTIMEOUT || 2000;
if (usedStocksRecently.has(message.author.id)) {
message.reply(embed.error(`You need to wait ${timeout / 1000} seconds before asking for stocks again.`, "ERR_RATE_LIMIT", "Slow down!"));
} else {
(async () => {
if (!stocksEnabled) {
message.reply(embed.error("Stock lookup isn't currently working. Sorry about that.", "ERR_NO_STOCK_KEY"));
return null;
}
if (!args[0]) {
message.reply(embed.error("You didn't include any arguments. Re-run the command with the stock name."));
return null;
}
try {
let gotData = await fetch(`https://finnhub.io/api/v1/quote?symbol=${args[0].toUpperCase()}&token=${configFile.stockToken || envVars.QBSTOCKS}`);
let stockData = await gotData.json();
if (!gotData.ok) {
message.reply(embed.error("There was an error getting stock info.", `${stockData.cod || gotData.status}: ${stockData.message || gotData.statusText}`));
return;
}
if (!stockData) {
message.reply(embed.error(`${args[0]} was not found.`, "ERR_EMPTY_RESPONSE"));
return null;
} else if (stockData.error ||
(Object.keys(stockData).length == 0 && stockData.constructor === Object) ||
Object.values(stockData).includes(undefined) ||
stockData.t === 0) {
message.reply(embed.error(`${args[0]} was not found.`, (stockData.error || "ERR_ALLSTOCK_ZERO")));
return null;
}
message.reply(embed.stocks(stockData, args[0]));
} catch (err) {
message.reply(embed.error("There was an error getting stock info.", (err.toString() || "ERR_FETCH").replace(configFile.stockToken || envVars.QBSTOCKS, "")))
}
})();
usedStocksRecently.add(message.author.id);
setTimeout(() => {
// Removes the user from the set after timeout
usedStocksRecently.delete(message.author.id);
}, timeout);
}
break;
}
case "league":
case "lolstats":
case "lol":
case "leaguestats": {
const timeout = configFile.leagueTimeout || envVars.QBLEAGUETIMEOUT || 5000;
if (usedLeagueRecently.has(message.author.id)) {
message.reply(embed.error(`You need to wait ${timeout / 1000} seconds before asking for League stats again.`, "ERR_RATE_LIMIT", "Slow down!"));
return;
}
if (!leagueEnabled) {
message.reply(embed.error("League stats lookup isn't currently working. Sorry about that.", "ERR_NO_LEAGUE_KEY"));
return;
}
if (!args[0]) {
message.reply(embed.error("You didn't include any arguments. Re-run the command with the summoner name."));
return;
}
(async () => {
let reg = "NA";
if (args[1]) {
reg = args[1].toUpperCase();
}
try {
message.channel.startTyping();
if (reg != "NA") {
// eslint-disable-next-line no-undef
LeagueAPI.changeRegion(Region[reg]);
}
let acctObj = await LeagueAPI.getSummonerByName(args[0].replace(/\+/g, " "));
let profile = acctObj?.profileIconId || "";
if (profile) profile = `https://ddragon.leagueoflegends.com/cdn/${LeagueAPI.getDDragonLocalDataVersion()}/img/profileicon/${profile}.png`;
let addlData = await LeagueAPI.getLeagueRanking(acctObj) || [];
message.channel.stopTyping(true);
let mbed = embed.simple(
"", "", `League Info for ${acctObj.name}`)
.setURL(`https://${opggRegions[LeagueAPI.region]}.op.gg/summoner/userName=${acctObj.name.replace(/ /g, "+")}`)
.setFooter('Click the "League Info" title above to go to this summoner\'s OP.GG page.', icons.bulb)
.setThumbnail(profile)
.addField("Summoner Level", acctObj.summonerLevel, false);
const exclKeys = ["summonerName", "wins", "losses"];
addlData.forEach((_ranked, idx) => { // Iterate over each ranked data set
const fields = addlData[idx];
Object.keys(fields).forEach((key) => { // iterate over each field
if (key == "queueType") mbed.addField(startCase(key), startCase(camelCase(String(fields[key]))), true)
else if (!key.endsWith("Id") && !exclKeys.includes(key)) {
let val = fields[key];
if (typeof val == "boolean") val = val ? "✅ Yes" : "🚫 No";
mbed.addField(startCase(key), String(val), true)
}
});
if (fields.wins && fields.losses) {
const total = fields.wins + fields.losses;
const rate = Math.round((fields.wins / total) * 100);
mbed.addField("Win Rate", `**${rate}%** (${total}G ${fields.wins}W ${fields.losses}L)`)
}
if (idx + 1 != addlData.length) mbed.addField('\u200b', '\u200b'); // Blank field
});
message.reply(mbed);
// eslint-disable-next-line no-undef
LeagueAPI.changeRegion(Region.NA);
} catch (err) {
let errmessage = err?.status?.message || err?.message || err;
if (errmessage ==
"Error: getaddrinfo ENOTFOUND undefined.api.riotgames.com"
) errmessage = "Invalid Region";
message.reply(embed.error("There was an error getting League stats.", errmessage));
message.channel.stopTyping(true);
message.channel.stopTyping();
// eslint-disable-next-line no-undef
LeagueAPI.changeRegion(Region.NA);
return null;
}
})();
usedLeagueRecently.add(message.author.id);
setTimeout(() => {
// Removes the user from the set after timeout
usedLeagueRecently.delete(message.author.id);
}, timeout);
}
break;
case "spellcheck":
if (envVars.QBSPELL != "off") {
(async () => {
let timeout = envVars.QBSPTIMEOUT || 10000;
if (usedSpellingRecently.has(message.author.id)) return message.reply(embed.error(`You need to wait ${timeout / 1000} seconds before asking for spellcheck again.`, "ERR_RATE_LIMIT", "Slow down!"));
if (args?.length < 1) return message.reply(embed.error("You didn't include any text to spell check.", "ERR_NO_TEXT", "Where's the text?"));
if (args?.join().length > 500) return message.reply(embed.error("You can only spellcheck 500 characters at most.", "ERR_500_EXCEEDED", "Too long!"));
usedSpellingRecently.add(message.author.id);
setTimeout(() => {
usedSpellingRecently.delete(message.author.id);
}, timeout);
let { items } = await splchecker.checkText(args.join(" "));
if (!items || items.length < 1) return message.reply(new Discord.MessageEmbed().setTitle("No errors found.").setColor(6765239));
items = uniqBy(items, "fragment");
let desc = "";
const mbed = new Discord.MessageEmbed()
.setColor(6765239)
.setTitle("Spell Check");
items.some(({ fragment, suggestions }) => {
let addition = `~~${fragment}~~ → **${suggestions.join("**, **") || "No suggestions"} **\n`;
if (desc.length + addition.length > 2000) {
mbed.setFooter("This spellcheck has been shortened.");
return true;
}
else desc += addition;
});
mbed.setDescription(desc);
return message.reply(mbed);
})()
}
break;
case "github":
message.channel.send("https://github.com/Team-Gigabyte/quotobot")
break;
default:
break;
}
});