bot.js 19 KB

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