bot.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. const util = require('util');
  2. util.inspect.defaultOptions = {compact:false,breakLength:Infinity};
  3. global.isDebug = ( process.argv[2] === 'debug' );
  4. global.shardId = null;
  5. process.on( 'message', message => {
  6. if ( !message.shard ) return;
  7. shardId = message.shard.id;
  8. } );
  9. const Lang = require('./util/i18n.js');
  10. const Wiki = require('./util/wiki.js');
  11. const newMessage = require('./util/newMessage.js');
  12. const {slashCommands, allowDelete} = require('./util/functions.js');
  13. global.patreons = {};
  14. global.voice = {};
  15. const db = require('./util/database.js');
  16. const Discord = require('discord.js');
  17. const client = new Discord.Client( {
  18. messageEditHistoryMaxSize: 1,
  19. messageCacheLifetime: 300,
  20. messageSweepInterval: 300,
  21. allowedMentions: {
  22. parse: []
  23. },
  24. presence: ( process.env.READONLY ? {
  25. status: 'dnd',
  26. activity: {
  27. type: 'PLAYING',
  28. name: 'READONLY: ' + process.env.prefix + 'test'
  29. }
  30. } : {
  31. status: 'online',
  32. activity: {
  33. type: 'STREAMING',
  34. name: process.env.prefix + 'help',
  35. url: 'https://www.twitch.tv/wikibot'
  36. }
  37. } ),
  38. ws: {
  39. large_threshold: 1000,
  40. intents: [
  41. 'GUILDS',
  42. 'GUILD_MESSAGES',
  43. 'GUILD_MESSAGE_REACTIONS',
  44. 'GUILD_VOICE_STATES',
  45. 'GUILD_INTEGRATIONS',
  46. 'DIRECT_MESSAGES',
  47. 'DIRECT_MESSAGE_REACTIONS'
  48. ]
  49. }
  50. } );
  51. client.api.applications(process.env.bot).commands.get().then( response => {
  52. console.log( '- ' + shardId + ': Slash commands successfully loaded.' );
  53. response.forEach( command => {
  54. var slashCommand = slashCommands.find( slashCommand => slashCommand.name === command.name );
  55. if ( slashCommand ) {
  56. slashCommand.id = command.id;
  57. slashCommand.application_id = command.application_id;
  58. }
  59. else slashCommands.push(slashCommand);
  60. } );
  61. }, error => {
  62. console.log( '- ' + shardId + ': Error while getting the global slash commands: ' + error );
  63. } );
  64. global.pause = {};
  65. var isStop = false;
  66. client.on( 'ready', () => {
  67. console.log( '\n- ' + shardId + ': Successfully logged in as ' + client.user.username + '!\n' );
  68. Object.keys(voice).forEach( guild => {
  69. if ( !client.guilds.cache.has(guild) ) delete voice[guild];
  70. } );
  71. } );
  72. String.prototype.isMention = function(guild) {
  73. var text = this.trim();
  74. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  75. };
  76. Discord.Channel.prototype.isGuild = function() {
  77. return ['text', 'news'].includes( this.type );
  78. }
  79. Discord.Message.prototype.isAdmin = function() {
  80. return this.channel.isGuild() && this.member && ( this.member.permissions.has('MANAGE_GUILD') || ( this.isOwner() && this.evalUsed ) );
  81. };
  82. Discord.Message.prototype.isOwner = function() {
  83. return process.env.owner.split('|').includes( this.author.id );
  84. };
  85. Discord.Message.prototype.showEmbed = function() {
  86. return !this.channel.isGuild() || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  87. };
  88. Discord.Message.prototype.uploadFiles = function() {
  89. return !this.channel.isGuild() || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  90. };
  91. String.prototype.replaceSave = function(pattern, replacement) {
  92. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  93. };
  94. Discord.APIMessage.prototype._resolveDataOld = Discord.APIMessage.prototype.resolveData;
  95. Discord.APIMessage.prototype.resolveData = function() {
  96. this._resolveDataOld();
  97. if ( this.options.components ) this.data.components = this.options.components;
  98. return this;
  99. };
  100. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  101. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  102. var emoji = ':error:440871715938238494';
  103. switch ( name ) {
  104. case 'nowiki':
  105. emoji = ':unknown_wiki:505884572001763348';
  106. break;
  107. case 'error':
  108. emoji = ':error:440871715938238494';
  109. break;
  110. default:
  111. emoji = name;
  112. }
  113. return this.react(emoji).catch(log_error);
  114. } else {
  115. console.log( '- Aborted, paused.' );
  116. return Promise.resolve();
  117. }
  118. };
  119. Discord.MessageReaction.prototype.removeEmoji = function() {
  120. return this.users.remove().catch(log_error);
  121. };
  122. Discord.Message.prototype.sendChannel = function(content, options = {}, ignorePause = false) {
  123. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  124. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  125. return this.channel.send(content, options).then( msg => {
  126. if ( msg.length ) msg.forEach( message => allowDelete(message, this.author.id) );
  127. else allowDelete(msg, this.author.id);
  128. return msg;
  129. }, error => {
  130. log_error(error);
  131. this.reactEmoji('error');
  132. } );
  133. } else {
  134. console.log( '- Aborted, paused.' );
  135. return Promise.resolve();
  136. }
  137. };
  138. Discord.Message.prototype.sendChannelError = function(content, options = {}) {
  139. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  140. return this.channel.send(content, options).then( msg => {
  141. if ( msg.length ) msg.forEach( message => {
  142. message.reactEmoji('error');
  143. allowDelete(message, this.author.id);
  144. } );
  145. else {
  146. msg.reactEmoji('error');
  147. allowDelete(msg, this.author.id);
  148. }
  149. return msg;
  150. }, error => {
  151. log_error(error);
  152. this.reactEmoji('error');
  153. } );
  154. };
  155. Discord.Message.prototype.replyMsg = function(content, options = {}, ignorePause = false, letDelete = true) {
  156. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  157. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  158. return this.reply(content, options).then( msg => {
  159. if ( letDelete ) {
  160. if ( msg.length ) msg.forEach( message => allowDelete(message, this.author.id) );
  161. else allowDelete(msg, this.author.id);
  162. }
  163. return msg;
  164. }, error => {
  165. log_error(error);
  166. this.reactEmoji('error');
  167. } );
  168. } else {
  169. console.log( '- Aborted, paused.' );
  170. return Promise.resolve();
  171. }
  172. };
  173. String.prototype.hasPrefix = function(prefix, flags = '') {
  174. var suffix = '';
  175. if ( prefix.endsWith( ' ' ) ) {
  176. prefix = prefix.trim();
  177. suffix = '(?: |$)';
  178. }
  179. var regex = new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + suffix, flags );
  180. return regex.test(this.replace( /\u200b/g, '' ).toLowerCase());
  181. };
  182. const fs = require('fs');
  183. var slash = {};
  184. var buttons = {};
  185. var buttonsMap = {
  186. verify_again: 'verify'
  187. };
  188. fs.readdir( './interactions', (error, files) => {
  189. if ( error ) return error;
  190. files.filter( file => file.endsWith('.js') ).forEach( file => {
  191. var command = require('./interactions/' + file);
  192. if ( command.hasOwnProperty('run') ) slash[command.name] = command.run;
  193. if ( command.hasOwnProperty('button') ) buttons[command.name] = command.button;
  194. } );
  195. } );
  196. /*
  197. !test eval msg.client.api.applications(msg.client.user.id).commands.post( {
  198. data: require('../interactions/commands.json')[0]
  199. } )
  200. */
  201. client.ws.on( 'INTERACTION_CREATE', interaction => {
  202. if ( interaction.version !== 1 ) return;
  203. interaction.client = client;
  204. /** @type {Discord.TextChannel} */
  205. var channel = client.channels.cache.get(interaction.channel_id);
  206. if ( interaction.guild_id ) {
  207. interaction.user = interaction.member.user;
  208. interaction.member.permissions = new Discord.Permissions(+interaction.member.permissions);
  209. channel?.guild?.members.add(interaction.member);
  210. }
  211. if ( interaction.type === 2 ) return slash_command(interaction, channel);
  212. if ( interaction.type === 3 ) return message_button(interaction, channel);
  213. } );
  214. /**
  215. * Handle slash commands.
  216. * @param {Object} interaction - The interaction.
  217. * @param {Discord.Client} interaction.client - The client of the interaction.
  218. * @param {Discord.TextChannel} [channel] - The channel for the interaction.
  219. */
  220. function slash_command(interaction, channel) {
  221. if ( interaction.data.name !== 'inline' ) {
  222. console.log( ( interaction.guild_id || '@' + interaction.user.id ) + ': Slash: /' + interaction.data.name + ' ' + ( interaction.data.options?.map( option => {
  223. return option.name + ':' + option.value;
  224. } ).join(' ') || '' ) );
  225. }
  226. else console.log( ( interaction.guild_id || '@' + interaction.user.id ) + ': Slash: /' + interaction.data.name );
  227. if ( !slash.hasOwnProperty(interaction.data.name) ) {
  228. console.log( '- Slash: Unknown command: ' + ( isDebug ? JSON.stringify(interaction, null, '\t') : interaction.data.name ) );
  229. return client.api.interactions(interaction.id, interaction.token).callback.post( {
  230. data: {
  231. type: 4,
  232. data: {
  233. content: '<:error:440871715938238494> [Unknown Command!](<' + process.env.invite + '>) <:error:440871715938238494>',
  234. allowed_mentions: {
  235. parse: []
  236. },
  237. flags: 64
  238. }
  239. }
  240. } ).catch(log_error);
  241. }
  242. if ( !interaction.guild_id ) {
  243. return slash[interaction.data.name](interaction, new Lang(), new Wiki(), channel);
  244. }
  245. db.query( 'SELECT wiki, lang FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', [interaction.guild_id, interaction.channel_id, '#' + channel?.parentID] ).then( ({rows:[row]}) => {
  246. return slash[interaction.data.name](interaction, new Lang(( row?.lang || channel?.guild?.preferredLocale )), new Wiki(row?.wiki), channel);
  247. }, dberror => {
  248. console.log( '- Slash: Error while getting the wiki: ' + dberror );
  249. return client.api.interactions(interaction.id, interaction.token).callback.post( {
  250. data: {
  251. type: 4,
  252. data: {
  253. content: '<:error:440871715938238494> [Error!](<' + process.env.invite + '>) <:error:440871715938238494>',
  254. allowed_mentions: {
  255. parse: []
  256. },
  257. flags: 64
  258. }
  259. }
  260. } ).catch(log_error);
  261. } );
  262. }
  263. /**
  264. * Handle message components.
  265. * @param {Object} interaction - The interaction.
  266. * @param {Discord.Client} interaction.client - The client of the interaction.
  267. * @param {Discord.TextChannel} [channel] - The channel for the interaction.
  268. */
  269. function message_button(interaction, channel) {
  270. if ( interaction.data.component_type !== 2 ) return;
  271. var cmd = ( buttonsMap.hasOwnProperty(interaction.data.custom_id) ? buttonsMap[interaction.data.custom_id] : interaction.data.custom_id );
  272. if ( !buttons.hasOwnProperty(cmd) ) {
  273. console.log( '- Button: Unknown command: ' + ( isDebug ? JSON.stringify(interaction, null, '\t') : interaction.data.custom_id ) );
  274. return client.api.interactions(interaction.id, interaction.token).callback.post( {
  275. data: {type: 6}
  276. } ).then( () => {
  277. client.api.webhooks(interaction.application_id, interaction.token).post( {
  278. data: {
  279. content: '<:error:440871715938238494> [Unknown Button!](<' + process.env.invite + '>) <:error:440871715938238494>',
  280. allowed_mentions: {
  281. parse: []
  282. },
  283. flags: 64
  284. }
  285. } ).catch(log_error);
  286. }, log_error);
  287. }
  288. if ( !interaction.guild_id ) {
  289. return buttons[cmd](interaction, new Lang(), new Wiki(), channel);
  290. }
  291. db.query( 'SELECT wiki, lang FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', [interaction.guild_id, interaction.channel_id, '#' + channel?.parentID] ).then( ({rows:[row]}) => {
  292. return buttons[cmd](interaction, new Lang(( row?.lang || channel?.guild?.preferredLocale )), new Wiki(row?.wiki), channel);
  293. }, dberror => {
  294. console.log( '- Button: Error while getting the wiki: ' + dberror );
  295. return client.api.interactions(interaction.id, interaction.token).callback.post( {
  296. data: {type: 6}
  297. } ).catch(log_error);
  298. } );
  299. }
  300. client.on( 'message', msg => {
  301. if ( isStop || msg.type !== 'DEFAULT' || msg.system || msg.webhookID || msg.author.bot || msg.author.id === msg.client.user.id ) return;
  302. if ( !msg.content.hasPrefix(( msg.channel.isGuild() && patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  303. if ( msg.content === process.env.prefix + 'help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  304. if ( msg.channel.permissionsFor(msg.client.user).has('SEND_MESSAGES') ) {
  305. console.log( msg.guild.name + ': ' + msg.content );
  306. db.query( 'SELECT lang FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', [msg.guild.id, msg.channel.id, '#' + msg.channel.parentID] ).then( ({rows:[row]}) => {
  307. msg.replyMsg( new Lang(( row?.lang || msg.guild.preferredLocale ), 'general').get('prefix', patreons[msg.guild.id]), {}, true );
  308. }, dberror => {
  309. console.log( '- Error while getting the lang: ' + dberror );
  310. msg.replyMsg( new Lang(msg.guild.preferredLocale, 'general').get('prefix', patreons[msg.guild.id]), {}, true );
  311. } );
  312. }
  313. return;
  314. }
  315. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  316. }
  317. if ( msg.channel.isGuild() ) {
  318. var permissions = msg.channel.permissionsFor(msg.client.user);
  319. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  320. if ( missing.length ) {
  321. if ( ( msg.isAdmin() || msg.isOwner() ) && msg.content.hasPrefix(( patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  322. console.log( msg.guild.id + ': Missing permissions - ' + missing.join(', ') );
  323. if ( !missing.includes( 'SEND_MESSAGES' ) ) {
  324. db.query( 'SELECT lang FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', [msg.guild.id, msg.channel.id, '#' + msg.channel.parentID] ).then( ({rows:[row]}) => {
  325. msg.replyMsg( new Lang(( row?.lang || msg.guild.preferredLocale ), 'general').get('missingperm') + ' `' + missing.join('`, `') + '`', {}, true );
  326. }, dberror => {
  327. console.log( '- Error while getting the lang: ' + dberror );
  328. msg.replyMsg( new Lang(msg.guild.preferredLocale, 'general').get('missingperm') + ' `' + missing.join('`, `') + '`', {}, true );
  329. } );
  330. }
  331. }
  332. return;
  333. }
  334. db.query( 'SELECT wiki, lang, role, inline FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', [msg.guild.id, msg.channel.id, '#' + msg.channel.parentID] ).then( ({rows:[row]}) => {
  335. if ( row ) {
  336. if ( msg.guild.roles.cache.has(row.role) && msg.guild.roles.cache.get(row.role).comparePositionTo(msg.member.roles.highest) > 0 && !msg.isAdmin() ) {
  337. msg.onlyVerifyCommand = true;
  338. }
  339. newMessage(msg, new Lang(row.lang), row.wiki, patreons[msg.guild.id], row.inline);
  340. }
  341. else {
  342. msg.defaultSettings = true;
  343. newMessage(msg, new Lang(msg.guild.preferredLocale));
  344. }
  345. }, dberror => {
  346. console.log( '- Error while getting the wiki: ' + dberror );
  347. msg.sendChannel( new Lang(msg.guild.preferredLocale, 'general').get('database') + '\n' + process.env.invite, {}, true );
  348. } );
  349. }
  350. else newMessage(msg, new Lang());
  351. } );
  352. client.on( 'voiceStateUpdate', (olds, news) => {
  353. if ( isStop || !( voice.hasOwnProperty(olds.guild.id) ) || !olds.guild.me.permissions.has('MANAGE_ROLES') || olds.channelID === news.channelID ) return;
  354. var lang = new Lang(voice[olds.guild.id], 'voice');
  355. if ( olds.member && olds.channel ) {
  356. var oldrole = olds.member.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + olds.channel.name );
  357. if ( oldrole && oldrole.comparePositionTo(olds.guild.me.roles.highest) < 0 ) {
  358. console.log( olds.guild.id + ': ' + olds.member.id + ' left the voice channel "' + olds.channel.id + '".' );
  359. olds.member.roles.remove( oldrole, lang.get('left', olds.member.displayName, olds.channel.name) ).catch(log_error);
  360. }
  361. }
  362. if ( news.member && news.channel ) {
  363. var newrole = news.guild.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + news.channel.name );
  364. if ( newrole && newrole.comparePositionTo(news.guild.me.roles.highest) < 0 ) {
  365. console.log( news.guild.id + ': ' + news.member.id + ' joined the voice channel "' + news.channel.id + '".' );
  366. news.member.roles.add( newrole, lang.get('join', news.member.displayName, news.channel.name) ).catch(log_error);
  367. }
  368. }
  369. } );
  370. const leftGuilds = new Map();
  371. client.on( 'guildCreate', guild => {
  372. console.log( '- ' + guild.id + ': I\'ve been added to a server.' );
  373. if ( leftGuilds.has(guild.id) ) {
  374. client.clearTimeout(leftGuilds.get(guild.id));
  375. leftGuilds.delete(guild.id);
  376. }
  377. } );
  378. client.on( 'guildDelete', guild => {
  379. if ( !guild.available ) {
  380. console.log( '- ' + guild.id + ': This server isn\'t responding.' );
  381. return;
  382. }
  383. console.log( '- ' + guild.id + ': I\'ve been removed from a server.' );
  384. leftGuilds.set(guild.id, client.setTimeout(removeSettings, 300000, guild.id));
  385. } );
  386. function removeSettings(guild) {
  387. leftGuilds.delete(guild);
  388. if ( client.guilds.cache.has(guild) ) return;
  389. db.query( 'DELETE FROM discord WHERE main = $1', [guild] ).then( ({rowCount}) => {
  390. if ( patreons.hasOwnProperty(guild) ) client.shard.broadcastEval( `delete global.patreons['${guild}']` );
  391. if ( voice.hasOwnProperty(guild) ) delete voice[guild];
  392. if ( rowCount ) console.log( '- ' + guild + ': Settings successfully removed.' );
  393. }, dberror => {
  394. console.log( '- ' + guild + ': Error while removing the settings: ' + dberror );
  395. } );
  396. }
  397. client.on( 'error', error => log_error(error, true) );
  398. client.on( 'warn', warning => log_warn(warning, false) );
  399. client.login(process.env.token).catch( error => {
  400. log_error(error, true, 'LOGIN-');
  401. return client.login(process.env.token).catch( error => {
  402. log_error(error, true, 'LOGIN-');
  403. return client.login(process.env.token).catch( error => {
  404. log_error(error, true, 'LOGIN-');
  405. process.exit(1);
  406. } );
  407. } );
  408. } );
  409. if ( isDebug ) client.on( 'debug', debug => {
  410. if ( isDebug ) console.log( '- ' + shardId + ': Debug: ' + debug );
  411. } );
  412. global.log_error = function(error, isBig = false, type = '') {
  413. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  414. if ( isDebug ) {
  415. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  416. } else {
  417. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  418. else console.log( '- ' + error.name + ': ' + error.message );
  419. }
  420. }
  421. const common_warnings = {
  422. main: [
  423. 'Unrecognized parameters: piprop, explaintext, exsectionformat, exlimit.',
  424. 'Unrecognized parameters: explaintext, exsectionformat, exlimit.',
  425. 'Unrecognized parameter: piprop.'
  426. ],
  427. query: [
  428. 'Unrecognized values for parameter "prop": pageimages, extracts.',
  429. 'Unrecognized values for parameter "prop": pageimages, extracts',
  430. 'Unrecognized value for parameter "prop": extracts.',
  431. 'Unrecognized value for parameter "prop": extracts',
  432. 'Unrecognized value for parameter "prop": pageimages.',
  433. 'Unrecognized value for parameter "prop": pageimages'
  434. ]
  435. }
  436. global.log_warn = function(warning, api = true) {
  437. if ( isDebug ) {
  438. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  439. }
  440. else if ( api ) {
  441. if ( common_warnings.main.includes( warning?.main?.['*'] ) ) delete warning.main;
  442. if ( common_warnings.query.includes( warning?.query?.['*'] ) ) delete warning.query;
  443. var warningKeys = Object.keys(warning);
  444. if ( warningKeys.length ) console.warn( '- Warning: ' + warningKeys.join(', ') );
  445. }
  446. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  447. }
  448. /**
  449. * End the process gracefully.
  450. * @param {NodeJS.Signals} signal - The signal received.
  451. */
  452. function graceful(signal) {
  453. isStop = true;
  454. console.log( '- ' + shardId + ': ' + signal + ': Preparing to close...' );
  455. setTimeout( () => {
  456. console.log( '- ' + shardId + ': ' + signal + ': Destroying client...' );
  457. client.destroy();
  458. db.end().then( () => {
  459. console.log( '- ' + shardId + ': ' + signal + ': Closed the database connection.' );
  460. process.exit(0);
  461. }, dberror => {
  462. console.log( '- ' + shardId + ': ' + signal + ': Error while closing the database connection: ' + dberror );
  463. } );
  464. }, 1000 ).unref();
  465. }
  466. process.once( 'SIGINT', graceful );
  467. process.once( 'SIGTERM', graceful );