main.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. require('dotenv').config();
  2. const child_process = require('child_process');
  3. const isDebug = ( process.argv[2] === 'debug' );
  4. if ( process.argv[2] === 'readonly' ) process.env.READONLY = true;
  5. const got = require('got').extend( {
  6. throwHttpErrors: false,
  7. timeout: 30000,
  8. headers: {
  9. 'User-Agent': 'Wiki-Bot/' + ( isDebug ? 'testing' : process.env.npm_package_version ) + ' (Discord; ' + process.env.npm_package_name + ')'
  10. },
  11. responseType: 'json'
  12. } );
  13. const {ShardingManager} = require('discord.js');
  14. const manager = new ShardingManager( './bot.js', {
  15. execArgv: ['--icu-data-dir=node_modules/full-icu'],
  16. shardArgs: ( isDebug ? ['debug'] : [] ),
  17. token: process.env.token
  18. } );
  19. var diedShards = 0;
  20. manager.on( 'shardCreate', shard => {
  21. console.log( `- Shard[${shard.id}]: Launched` );
  22. shard.on( 'spawn', message => {
  23. console.log( `- Shard[${shard.id}]: Spawned` );
  24. shard.send( {
  25. shard: {
  26. id: shard.id
  27. }
  28. } );
  29. } );
  30. shard.on( 'message', message => {
  31. if ( message === 'SIGKILL' ) {
  32. console.log( '\n- Killing all shards!\n\n' );
  33. manager.shards.forEach( shard => shard.kill() );
  34. }
  35. if ( message === 'postStats' && process.env.botlist ) postStats();
  36. } );
  37. shard.on( 'death', message => {
  38. if ( manager.respawn === false ) diedShards++;
  39. if ( message.exitCode ) {
  40. if ( !shard.ready ) {
  41. manager.respawn = false;
  42. console.log( `\n\n- Shard[${shard.id}]: Died due to fatal error, disable respawn!\n\n` );
  43. }
  44. else console.log( `\n\n- Shard[${shard.id}]: Died due to fatal error!\n\n` );
  45. }
  46. } );
  47. } );
  48. manager.spawn().then( shards => {
  49. if ( !isDebug && process.env.botlist ) {
  50. var botList = JSON.parse(process.env.botlist);
  51. for ( let [key, value] of Object.entries(botList) ) {
  52. if ( !value ) delete botList[key];
  53. }
  54. if ( Object.keys(botList).length ) {
  55. setInterval( postStats, 10800000, botList, shards.size ).unref();
  56. }
  57. }
  58. }, error => {
  59. console.error( '- Error while spawning the shards: ' + error );
  60. manager.respawnAll();
  61. } );
  62. var server;
  63. if ( process.env.dashboard ) {
  64. const dashboard = child_process.fork('./dashboard/index.js', ( isDebug ? ['debug'] : [] ));
  65. server = dashboard;
  66. dashboard.on( 'message', message => {
  67. if ( message.id ) {
  68. var data = {
  69. type: message.data.type,
  70. response: null,
  71. error: null
  72. };
  73. switch ( message.data.type ) {
  74. case 'isMember':
  75. return manager.broadcastEval(`this.guilds.cache.has('${message.data.guild}')`).then( results => {
  76. data.response = results.includes( true );
  77. }, error => {
  78. data.error = error;
  79. } ).finally( () => {
  80. return dashboard.send( {id: message.id, data} );
  81. } );
  82. break;
  83. case 'isMemberAll':
  84. return manager.broadcastEval(`${JSON.stringify(message.data.guilds)}.map( guild => {
  85. return this.guilds.cache.has(guild);
  86. } )`).then( results => {
  87. data.response = message.data.guilds.map( (guild, i) => {
  88. return results.map( result => result[i] ).includes( true );
  89. } );
  90. }, error => {
  91. data.error = error;
  92. } ).finally( () => {
  93. return dashboard.send( {id: message.id, data} );
  94. } );
  95. break;
  96. default:
  97. console.log( '- [Dashboard]: Unknown message received!', message.data );
  98. data.error = 'Unknown message type: ' + message.data.type;
  99. return dashboard.send( {id: message.id, data} );
  100. }
  101. }
  102. console.log( '- [Dashboard]: Message received!', message );
  103. } );
  104. dashboard.on( 'error', error => {
  105. console.log( '- [Dashboard]: Error received!', error );
  106. } );
  107. dashboard.on( 'exit', (code) => {
  108. if ( code ) console.log( '- [Dashboard]: Process exited!', code );
  109. } );
  110. }
  111. /**
  112. * Post bot statistics to bot lists.
  113. * @param {Object} botList - The list of bot lists to post to.
  114. * @param {Number} shardCount - The total number of shards.
  115. */
  116. function postStats(botList = JSON.parse(process.env.botlist), shardCount = manager.totalShards) {
  117. manager.fetchClientValues('guilds.cache.size').then( results => {
  118. var guildCount = results.reduce( (acc, val) => acc + val, 0 );
  119. console.log( '- Current server count: ' + guildCount + '\n' + results.map( (count, i) => {
  120. return '-- Shard[' + i + ']: ' + count;
  121. } ).join('\n') );
  122. got.post( 'https://botblock.org/api/count', {
  123. json: Object.assign( {
  124. bot_id: process.env.bot,
  125. server_count: guildCount,
  126. shard_count: shardCount,
  127. shards: results
  128. }, botList )
  129. } ).then( response => {
  130. var body = response.body;
  131. if ( response.statusCode !== 200 || !body || body.error ) {
  132. console.log( '- ' + response.statusCode + ': Error while posting statistics to BotBlock.org: ' + ( body && body.message ) );
  133. return;
  134. }
  135. for ( let [key, value] of Object.entries(body.failure) ) {
  136. console.log( '- ' + value[0] + ': Error while posting statistics to ' + key + ': ' + value[1] );
  137. }
  138. }, error => {
  139. console.log( '- Error while posting statistics to BotBlock.org: ' + error );
  140. } );
  141. }, error => console.log( '- Error while getting the guild count: ' + error ) );
  142. }
  143. /**
  144. * End the process gracefully.
  145. * @param {NodeJS.Signals} signal - The signal received.
  146. */
  147. async function graceful(signal) {
  148. console.log( '- ' + signal + ': Disabling respawn...' );
  149. manager.respawn = false;
  150. }
  151. process.once( 'SIGINT', graceful );
  152. process.once( 'SIGTERM', graceful );
  153. process.on( 'exit', code => {
  154. if ( diedShards >= manager.totalShards ) process.exit(1);
  155. } );
  156. if ( isDebug && process.argv[3]?.startsWith( '--timeout:' ) ) {
  157. let timeout = process.argv[3].split(':')[1];
  158. console.log( `\n- Close process in ${timeout} seconds!\n` );
  159. setTimeout( () => {
  160. console.log( `\n- Running for ${timeout} seconds, closing process!\n` );
  161. manager.shards.forEach( shard => shard.kill() );
  162. if ( typeof server !== 'undefined' ) server.kill('SIGTERM');
  163. }, timeout * 1000 ).unref();
  164. }