1
0

bot.js 20 KB

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