main.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. if ( typeof server !== 'undefined' ) server.kill();
  35. }
  36. if ( message === 'postStats' && process.env.botlist ) postStats();
  37. } );
  38. shard.on( 'death', message => {
  39. if ( manager.respawn === false ) diedShards++;
  40. if ( message.exitCode ) {
  41. if ( !shard.ready ) {
  42. manager.respawn = false;
  43. console.log( `\n\n- Shard[${shard.id}]: Died due to fatal error, disable respawn!\n\n` );
  44. }
  45. else console.log( `\n\n- Shard[${shard.id}]: Died due to fatal error!\n\n` );
  46. }
  47. } );
  48. } );
  49. manager.spawn().then( shards => {
  50. if ( !isDebug && process.env.botlist ) {
  51. var botList = JSON.parse(process.env.botlist);
  52. for ( let [key, value] of Object.entries(botList) ) {
  53. if ( !value ) delete botList[key];
  54. }
  55. if ( Object.keys(botList).length ) {
  56. setInterval( postStats, 10800000, botList, shards.size ).unref();
  57. }
  58. }
  59. }, error => {
  60. console.error( '- Error while spawning the shards: ' + error );
  61. manager.respawnAll();
  62. } );
  63. var server;
  64. if ( process.env.dashboard ) {
  65. const dashboard = child_process.fork('./dashboard/index.js', ( isDebug ? ['debug'] : [] ));
  66. server = dashboard;
  67. dashboard.on( 'message', message => {
  68. if ( message.id ) {
  69. var data = {
  70. type: message.data.type,
  71. response: null,
  72. error: null
  73. };
  74. switch ( message.data.type ) {
  75. case 'getGuilds':
  76. return manager.broadcastEval(`Promise.all(
  77. ${JSON.stringify(message.data.guilds)}.map( id => {
  78. if ( this.guilds.cache.has(id) ) {
  79. let guild = this.guilds.cache.get(id);
  80. return guild.members.fetch('${message.data.member}').then( member => {
  81. return {
  82. patreon: guild.id in global.patreons,
  83. botPermissions: guild.me.permissions.bitfield,
  84. channels: guild.channels.cache.filter( channel => {
  85. return channel.isGuild();
  86. } ).sort( (a, b) => {
  87. return a.rawPosition - b.rawPosition;
  88. } ).map( channel => {
  89. return {
  90. id: channel.id,
  91. name: channel.name,
  92. permissions: member.permissionsIn(channel).bitfield
  93. };
  94. } ),
  95. roles: guild.roles.cache.filter( role => {
  96. return ( role.id !== guild.id );
  97. } ).sort( (a, b) => {
  98. return b.rawPosition - a.rawPosition;
  99. } ).map( role => {
  100. return {
  101. id: role.id,
  102. name: role.name,
  103. lower: ( guild.me.roles.highest.comparePositionTo(role) > 0 && !role.managed )
  104. };
  105. } )
  106. };
  107. }, error => {
  108. return 'noMember';
  109. } )
  110. }
  111. } )
  112. )`).then( results => {
  113. data.response = message.data.guilds.map( (guild, i) => {
  114. return results.find( result => result[i] )?.[i];
  115. } );
  116. }, error => {
  117. data.error = error;
  118. } ).finally( () => {
  119. return dashboard.send( {id: message.id, data} );
  120. } );
  121. break;
  122. case 'getMember':
  123. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  124. let guild = this.guilds.cache.get('${message.data.guild}');
  125. guild.members.fetch('${message.data.member}').then( member => {
  126. return {
  127. patreon: guild.id in global.patreons,
  128. permissions: member.permissions.bitfield
  129. };
  130. }, error => {
  131. return 'noMember';
  132. } );
  133. }`).then( results => {
  134. data.response = results.find( result => result );
  135. }, error => {
  136. data.error = error;
  137. } ).finally( () => {
  138. return dashboard.send( {id: message.id, data} );
  139. } );
  140. break;
  141. case 'notifyGuild':
  142. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  143. let channel = this.guilds.cache.get('${message.data.guild}').publicUpdatesChannel;
  144. if ( channel ) channel.send('${message.data.text}').catch( error => {
  145. console.log( '- ' + error.name + ': ' + error.message );
  146. } );
  147. }`).then( results => {
  148. data.response = results.find( result => result );
  149. }, error => {
  150. data.error = error;
  151. } ).finally( () => {
  152. return dashboard.send( {id: message.id, data} );
  153. } );
  154. break;
  155. default:
  156. console.log( '- [Dashboard]: Unknown message received!', message.data );
  157. data.error = 'Unknown message type: ' + message.data.type;
  158. return dashboard.send( {id: message.id, data} );
  159. }
  160. }
  161. console.log( '- [Dashboard]: Message received!', message );
  162. } );
  163. dashboard.on( 'error', error => {
  164. console.log( '- [Dashboard]: Error received!', error );
  165. } );
  166. dashboard.on( 'exit', (code) => {
  167. if ( code ) console.log( '- [Dashboard]: Process exited!', code );
  168. } );
  169. }
  170. /**
  171. * Post bot statistics to bot lists.
  172. * @param {Object} botList - The list of bot lists to post to.
  173. * @param {Number} shardCount - The total number of shards.
  174. */
  175. function postStats(botList = JSON.parse(process.env.botlist), shardCount = manager.totalShards) {
  176. manager.fetchClientValues('guilds.cache.size').then( results => {
  177. var guildCount = results.reduce( (acc, val) => acc + val, 0 );
  178. console.log( '- Current server count: ' + guildCount + '\n' + results.map( (count, i) => {
  179. return '-- Shard[' + i + ']: ' + count;
  180. } ).join('\n') );
  181. got.post( 'https://botblock.org/api/count', {
  182. json: Object.assign( {
  183. bot_id: process.env.bot,
  184. server_count: guildCount,
  185. shard_count: shardCount,
  186. shards: results
  187. }, botList )
  188. } ).then( response => {
  189. var body = response.body;
  190. if ( response.statusCode !== 200 || !body || body.error ) {
  191. console.log( '- ' + response.statusCode + ': Error while posting statistics to BotBlock.org: ' + ( body && body.message ) );
  192. return;
  193. }
  194. for ( let [key, value] of Object.entries(body.failure) ) {
  195. console.log( '- ' + value[0] + ': Error while posting statistics to ' + key + ': ' + value[1] );
  196. }
  197. }, error => {
  198. console.log( '- Error while posting statistics to BotBlock.org: ' + error );
  199. } );
  200. }, error => console.log( '- Error while getting the guild count: ' + error ) );
  201. }
  202. /**
  203. * End the process gracefully.
  204. * @param {NodeJS.Signals} signal - The signal received.
  205. */
  206. function graceful(signal) {
  207. console.log( '- ' + signal + ': Disabling respawn...' );
  208. manager.respawn = false;
  209. }
  210. process.once( 'SIGINT', graceful );
  211. process.once( 'SIGTERM', graceful );
  212. process.on( 'exit', code => {
  213. if ( diedShards >= manager.totalShards ) process.exit(1);
  214. } );
  215. if ( isDebug && process.argv[3]?.startsWith( '--timeout:' ) ) {
  216. let timeout = process.argv[3].split(':')[1];
  217. console.log( `\n- Close process in ${timeout} seconds!\n` );
  218. setTimeout( () => {
  219. console.log( `\n- Running for ${timeout} seconds, closing process!\n` );
  220. manager.shards.forEach( shard => shard.kill() );
  221. if ( typeof server !== 'undefined' ) server.kill();
  222. }, timeout * 1000 ).unref();
  223. }