main.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. require('dotenv').config();
  2. const isDebug = ( process.argv[2] === 'debug' );
  3. const got = require('got').extend( {
  4. throwHttpErrors: false,
  5. timeout: 30000,
  6. headers: {
  7. 'User-Agent': 'Wiki-Bot/' + ( isDebug ? 'testing' : process.env.npm_package_version ) + ' (Discord; ' + process.env.npm_package_name + ')'
  8. }
  9. } );
  10. const {ShardingManager} = require('discord.js');
  11. const manager = new ShardingManager( './bot.js', {
  12. execArgv: ['--icu-data-dir=node_modules/full-icu'],
  13. shardArgs: ( isDebug ? ['debug'] : [] ),
  14. token: process.env.token
  15. } );
  16. var diedShards = 0;
  17. manager.on( 'shardCreate', shard => {
  18. console.log( `- Shard[${shard.id}]: Launched` );
  19. shard.on( 'spawn', message => {
  20. console.log( `- Shard[${shard.id}]: Spawned` );
  21. shard.send( {
  22. shard: {
  23. id: shard.id
  24. }
  25. } );
  26. } );
  27. shard.on( 'message', message => {
  28. if ( message === 'SIGKILL' ) {
  29. console.log( '\n- Killing all shards!\n\n' );
  30. manager.shards.forEach( shard => shard.kill() );
  31. }
  32. if ( message === 'postStats' ) postStats();
  33. } );
  34. shard.on( 'death', message => {
  35. if ( manager.respawn === false ) diedShards++;
  36. if ( ![null, 0].includes( message.exitCode ) ) {
  37. if ( !shard.ready ) {
  38. manager.respawn = false;
  39. console.log( `\n\n- Shard[${shard.id}]: Died due to fatal error, disable respawn!\n\n` );
  40. }
  41. else console.log( `\n\n- Shard[${shard.id}]: Died due to fatal error!\n\n` );
  42. }
  43. } );
  44. } );
  45. manager.spawn().then( shards => {
  46. if ( !isDebug ) {
  47. var botList = JSON.parse(process.env.botlist);
  48. for ( let [key, value] of Object.entries(botList) ) {
  49. if ( !value ) delete botList[key];
  50. }
  51. setInterval( postStats, 10800000, botList, shards.size ).unref();
  52. }
  53. }, error => {
  54. console.error( '- Error while spawning the shards: ' + error );
  55. manager.respawnAll();
  56. } );
  57. /**
  58. * Post bot statistics to bot lists.
  59. * @param {Object} botList - The list of bot lists to post to.
  60. * @param {Number} shardCount - The total number of shards.
  61. */
  62. function postStats(botList = JSON.parse(process.env.botlist), shardCount = manager.totalShards) {
  63. manager.fetchClientValues('guilds.cache.size').then( results => {
  64. var guildCount = results.reduce( (acc, val) => acc + val, 0 );
  65. console.log( '- Current server count: ' + guildCount + '\n' + results.map( (count, i) => {
  66. return '-- Shard[' + i + ']: ' + count;
  67. } ).join('\n') );
  68. got.post( 'https://botblock.org/api/count', {
  69. json: Object.assign( {
  70. bot_id: process.env.bot,
  71. server_count: guildCount,
  72. shard_count: shardCount,
  73. shards: results
  74. }, botList ),
  75. responseType: 'json'
  76. } ).then( response => {
  77. var body = response.body;
  78. if ( response.statusCode !== 200 || !body || body.error ) {
  79. console.log( '- ' + response.statusCode + ': Error while posting statistics to BotBlock.org: ' + ( body && body.message ) );
  80. return;
  81. }
  82. for ( let [key, value] of Object.entries(body.failure) ) {
  83. console.log( '- ' + value[0] + ': Error while posting statistics to ' + key + ': ' + value[1] );
  84. }
  85. }, error => {
  86. console.log( '- Error while posting statistics to BotBlock.org: ' + error );
  87. } );
  88. }, error => console.log( '- Error while getting the guild count: ' + error ) );
  89. }
  90. /**
  91. * End the process gracefully.
  92. * @param {String} signal - The signal received.
  93. */
  94. async function graceful(signal) {
  95. console.log( '- ' + signal + ': Disabling respawn...' );
  96. manager.respawn = false;
  97. }
  98. process.once( 'SIGINT', graceful );
  99. process.once( 'SIGTERM', graceful );
  100. process.on( 'exit', code => {
  101. if ( diedShards >= manager.totalShards ) process.exit(1);
  102. } );
  103. if ( isDebug && process.argv[3]?.startsWith( '--timeout:' ) ) {
  104. let timeout = process.argv[3].split(':')[1];
  105. console.log( `\n- Close process in ${timeout} seconds!\n` );
  106. setTimeout( () => {
  107. console.log( `\n- Running for ${timeout} seconds, closing process!\n` );
  108. manager.shards.forEach( shard => shard.kill() );
  109. }, timeout * 1000 ).unref();
  110. }