Skip to content

Commit 8267754

Browse files
committed
General improvements, v2.3.0 beta 4
- Removed unnecessary Promises nesting - Used ES6 class syntax for NodeModule class - Forbid timeout larger than or equal to 2147483648ms for "/remindme" command due to the hard limit of Node.js Timer API. See https://nodejs.org/api/timers.html#timers_settimeout_callback_delay_args - Forbid timeout of 0ms for "/remindme" command as it doesn't make sense to be reminded immediately... and because of the hard limit of Node.js Timer API. See https://nodejs.org/api/timers.html#timers_settimeout_callback_delay_args - Added handler for unhandledRejection event, errors from unhandled rejected Promises will be logged - Added missing command variations to help string - Changed program flag "restartOnFatalError" to "--restart-on-fatal-error" to be consistent with node flag syntax. See https://nodejs.org/api/cli.html#cli_options - Added handlers for "SIGHUP", "SIGINT", "SIGTERM", and "SIGBREAK" for clean shutdown - Added "inviteURL" configuration, /invite command will only work if configuration is set. This is part of the effort to gradually phase out customization on Chillbot and commit back to upstream or sibling branches - Added "--throw-deprecation" node flag to npm start script, as deprecated usages aren't encouraged especially for small projects like Chillbot - Fixed version format, there's a "." between alpha/beta/rc and the number now. See https://semver.org/#spec-item-9 - Changed accepted format of version number for "/changelog" to reflect the change stated above - Replaced if... return... statements with condition shorthand syntax - Removed unused args at line 429 (now 434) and line 615 (now 620) - Bumped version to v2.3.0-beta.4
1 parent 983257a commit 8267754

File tree

3 files changed

+57
-38
lines changed

3 files changed

+57
-38
lines changed

configurations/configuration.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,6 @@
1313
"511620513643364353"
1414
],
1515
"developmentEnvironment": false,
16-
"cliProcessTimeout": 5000
16+
"cliProcessTimeout": 5000,
17+
"inviteURL": "https://discordapp.com/api/oauth2/authorize?client_id=511463919399731201&scope=bot&permissions=3136"
1718
}

index.js

Lines changed: 53 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,19 @@ process.on("uncaughtException", error => {
4444
let shouldRestart = false;
4545
if (process.env.RESTARTED !== unexpectedRestartIdentifier) {
4646
for (const arg of process.argv) {
47-
if (arg === "restartOnFatalError") {
47+
if (/^\-{2}restart(\-|_)on(\-|_)fatal(\-|_)error$/g.test(arg)) {
4848
shouldRestart = true;
4949
break;
5050
}
5151
}
5252
}
5353
exitProcess(1, shouldRestart);
54-
});
54+
}).on("unhandledRejection", reason => {
55+
handleGenerically(reason instanceof Error ? reason : new Error(reason));
56+
}).on("SIGHUP", () => exitProcess(0, false))
57+
.on("SIGINT", () => exitProcess(0, false))
58+
.on("SIGTERM", () => exitProcess(0, false))
59+
.on("SIGBREAK", () => exitProcess(0, false));
5560

5661
const ms = require("ms");
5762
const https = require("https");
@@ -76,6 +81,7 @@ const developmentGuildIDs = getConfiguration("developmentGuildIDs");
7681
const token = getConfiguration("token");
7782
const developmentEnvironment = getConfiguration("developmentEnvironment");
7883
const cliProcessTimeout = getConfiguration("cliProcessTimeout");
84+
const inviteURL = getConfiguration("inviteURL");
7985
const remindmeMaxTimeStringLength = 100;
8086
// 100 is the limit for ms library, see https://github.com/zeit/ms/blob/2.1.1/index.js#L50
8187
const licenseInfoCooldown = 1000 * 60 * 30;
@@ -90,11 +96,11 @@ const sendOptionsForLongMessage = {
9096
}
9197
};
9298

93-
const helpString = `Prefix: ${bold("/")}\n\n${bold("/help")},\n${bold("/ping")},\n${bold("/ship")} [me],\n(${bold("/reminder")}\|${bold("/remind")}\|${bold("/remindme")}) <time> <value>,\n${bold("/give")} <mention> <amount> <item>,\n(${bold("/eightball")}\|${bold("/8ball")}) <value>,\n(${bold("/source")}\|${bold("/github")}\|${bold("/repo")}\|${bold("/repository")}),\n${bold("/stop")},\n${bold("/restart")},\n${bold("/osslicenses")}\|${bold("/opensourcelicenses")},\n(${bold("/changes")}\|${bold("/changelog")}\|${bold("/changelogs")}) [tagName],\n${bold("/invite")}`;
99+
const helpString = `Prefix: ${bold("/")}\n\n${bold("/help")},\n${bold("/ping")},\n${bold("/ship")} [me],\n(${bold("/reminder")}\|${bold("/remind")}\|${bold("/remindme")}) <time> <value>,\n${bold("/give")} <mention> <amount> <item>,\n(${bold("/eightball")}\|${bold("/8ball")}) <value>,\n(${bold("/source")}\|${bold("/github")}\|${bold("/repo")}\|${bold("/repository")}),\n${bold("/stop")},\n${bold("/restart")},\n${bold("/osslicenses")}\|${bold("/osslicences")}\|${bold("/opensourcelicenses")}\|${bold("/opensourcelicences")},\n(${bold("/changes")}\|${bold("/changelog")}\|${bold("/changelogs")}) [tagName],\n${bold("/invite")}`;
94100
const dmUnavailableString = "I'm unable to send message to you in DM. Please make sure \"Allow direct messages from server members.\" is on in the \"Privacy & Safety\" settings in Discord settings!";
95101
const repositoryString = "Original repository owned by DMCPlayer, no longer maintained: https://github.com/DMCPlayer/chill\nForked repository owned by original ChillBot author VanishedApps, no longer maintained: https://github.com/VanishedApps/chill\nForked repository owned by LightWayUp, still maintained: https://github.com/LightWayUp/chill";
96102
const errorFetchingChangelogString = "Sorry, an error occured while fetching changelog. You can visit https://github.com/LightWayUp/chill/releases to see all changes.";
97-
const inviteString = "Invite ChillBot to other servers!\nhttps://discordapp.com/api/oauth2/authorize?client_id=511463919399731201&scope=bot&permissions=3136";
103+
const inviteString = inviteURL === undefined ? undefined : `Invite ChillBot to other servers!\n${inviteURL}`;
98104
const botUnavailableString = "Sorry, ChillBot is currently unavailable, most likely due to a new and not yet deployed update. Please check back later.";
99105
const githubAPIBaseURL = "https://api.github.com/";
100106
const changelogBaseURL = `${githubAPIBaseURL}repos/LightWayUp/chill/releases/`;
@@ -205,17 +211,12 @@ client.on("ready", () => {
205211
const ping = client.ping;
206212
const messageToSend = "Pinging.";
207213
channel.send(bold(messageToSend))
208-
.then(message => message.edit(bold("Pinging.."))
209-
.then(message => message.edit(bold("Pinging..."))
210-
.then(message => message.edit(bold("Pinging."))
211-
.then(message => message.edit(bold("Pinging.."))
212-
.then(message => message.edit(`${bold("Pong!")} ${code(`${ping < 0 ? "0" : ping.toFixed()} ms`)}`)
213-
.catch(error => console.error(`An error occured while editing message "${message.content}"!\n\nFull details:\n${error}`)),
214-
error => console.error(`An error occured while editing message "${message.content}"!\n\nFull details:\n${error}`)),
215-
error => console.error(`An error occured while editing message "${message.content}"!\n\nFull details:\n${error}`)),
216-
error => console.error(`An error occured while editing message "${message.content}"!\n\nFull details:\n${error}`)),
217-
error => console.error(`An error occured while editing message "${message.content}"!\n\nFull details:\n${error}`)),
218-
error => console.error(`An error occured while sending message "${messageToSend}"!\n\nFull details:\n${error}`));
214+
.then(message => message.edit(bold("Pinging..")))
215+
.then(message => message.edit(bold("Pinging...")))
216+
.then(message => message.edit(bold("Pinging.")))
217+
.then(message => message.edit(bold("Pinging..")))
218+
.then(message => message.edit(`${bold("Pong!")} ${code(`${ping < 0 ? "0" : ping.toFixed()} ms`)}`))
219+
.catch(error => console.error(`An error occured while sending or editing message for ping command!\n\nFull details:\n${error}`));
219220
break;
220221
}
221222

@@ -257,8 +258,12 @@ client.on("ready", () => {
257258
timeout = ms(args[1]);
258259
if (timeout === undefined) {
259260
messageToSend = "You need to specify a valid time with unit!";
260-
} else if (timeout < 0) {
261-
messageToSend = "Time can not be negative!";
261+
} else if (timeout <= 0) {
262+
messageToSend = "Time can not be negative or 0!";
263+
} else if (timeout > 2147483647) {
264+
messageToSend = "The time is too large!";
265+
// 2147483647 is the maximum for Node.js setTimeout(),
266+
// see https://nodejs.org/api/timers.html#timers_settimeout_callback_delay_args
262267
} else if (args.length === 2) {
263268
messageToSend = `Please provide a value to remind you for. Example: ${code("/remindme 3d Do homework")}`;
264269
}
@@ -426,7 +431,7 @@ client.on("ready", () => {
426431
messageToSend += "\nLicense:";
427432
}
428433
await channel.send(messageToSend, sendOptionsForLongMessage)
429-
.then(async message => {
434+
.then(async () => {
430435
if (libraryLicense === undefined) {
431436
return;
432437
}
@@ -459,7 +464,7 @@ client.on("ready", () => {
459464
let messageToSend;
460465
let tagName;
461466
if (args.length > 1) {
462-
if (/^v?((0|([1-9]\d*))\.){2}(0|([1-9]\d*))(\-((alpha)|(beta)|(rc))([1-9]\d*))?$/gi.test(args[1])) {
467+
if (/^v?((0|([1-9]\d*))\.){2}(0|([1-9]\d*))(\-((alpha)|(beta)|(rc))\.([1-9]\d*))?$/gi.test(args[1])) {
463468
tagName = args[1].toLowerCase();
464469
if (!tagName.startsWith("v")) {
465470
tagName = `v${tagName}`;
@@ -546,7 +551,7 @@ client.on("ready", () => {
546551
}
547552

548553
case "invite": {
549-
if (!canSendMessages || shouldReject) {
554+
if (!canSendMessages || shouldReject || inviteString === undefined) {
550555
return;
551556
}
552557
channel.send(inviteString)
@@ -612,7 +617,7 @@ function exitProcess(exitCode, shouldRestart) {
612617
}
613618
if (!(client === undefined || client === null || client.user === undefined || client.user === null)) {
614619
client.user.setStatus("invisible")
615-
.then(clientUser => client.destroy()
620+
.then(() => client.destroy()
616621
.catch(error => console.error(`An error occured while logging out!\n\nFull details:\n${error}`)),
617622
error => console.error(`An error occured while setting status!\n\nFull details:\n${error}`));
618623
}
@@ -788,24 +793,40 @@ function getConfiguration(configurationType) {
788793
break;
789794
}
790795

796+
case "inviteURL": {
797+
if (result === useProcessEnvIdentifier) {
798+
result = process.env.BOT_INVITE_URL;
799+
} else if (!(result === undefined || result === null || typeof result === "string")) {
800+
throw new TypeError("Invalid inviteURL value!");
801+
}
802+
if (typeof result === "string" && (result.length === 0 || result.includes(" "))) {
803+
throw new Error("Invalid inviteURL value!");
804+
}
805+
if (result === null) {
806+
result = undefined;
807+
}
808+
break;
809+
}
810+
791811
default: {
792812
throw new Error("Invalid configuration to fetch!");
793813
}
794814
}
795815
return result;
796816
}
797817

798-
function NodeModule(name, version, license) {
799-
if (!((typeof name === "string" || name instanceof String) && (version === undefined || version === null || typeof version === "string" || version instanceof String) && (license === undefined || license === null || typeof license === "string" || license instanceof String))) {
800-
throw new TypeError("Incorrect type(s) for NodeModule arguments!");
818+
class NodeModule {
819+
constructor(name, version, license) {
820+
if (!((typeof name === "string" || name instanceof String) && (version === undefined || version === null || typeof version === "string" || version instanceof String) && (license === undefined || license === null || typeof license === "string" || license instanceof String))) {
821+
throw new TypeError("Incorrect type(s) for NodeModule arguments!");
822+
}
823+
this.name = name;
824+
this.version = version;
825+
this.license = license;
826+
}
827+
toString() {
828+
return `${this.name}@${this.version}`;
801829
}
802-
this.name = name;
803-
this.version = version;
804-
this.license = license;
805-
}
806-
807-
NodeModule.prototype.toString = function() {
808-
return `${this.name}@${this.version}`;
809830
}
810831

811832
function getModuleFromPath(directoryPath) {
@@ -871,10 +892,7 @@ function getLicenseByRepository(repository) {
871892
.on("error", error => {
872893
console.error(`An error occured while attempting to fetch license for ${repository}!\n\nFull details:\n${error}`);
873894
}).on("end", () => {
874-
if (!response.complete) {
875-
return reject(new Error(`Unable to get license for ${repository}, connection was terminated while response was still not fully received!`));
876-
}
877-
resolve(raw.replace(/\r/gi, ""));
895+
response.complete ? resolve(raw.replace(/\r/gi, "")) : reject(new Error(`Unable to get license for ${repository}, connection was terminated while response was still not fully received!`));
878896
});
879897
}).on("timeout", () => {
880898
request.abort();

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "chillbot",
3-
"version": "2.3.0-beta3",
3+
"version": "2.3.0-beta.4",
44
"description": "Chill!",
55
"keywords": [
66
"discord",
@@ -33,7 +33,7 @@
3333
"url": "https://github.com/LightWayUp/chill.git"
3434
},
3535
"scripts": {
36-
"start": "node index.js",
36+
"start": "node --throw-deprecation index.js",
3737
"test": "echo \"No test to run\" && exit 0"
3838
},
3939
"dependencies": {

0 commit comments

Comments
 (0)