main.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. require('dotenv').config();
  2. const isDebug = ( process.argv[2] === 'debug' );
  3. if ( process.argv[2] === 'readonly' ) process.env.READONLY = true;
  4. require('./database.js').then( () => {
  5. const child_process = require('child_process');
  6. const got = require('got').extend( {
  7. throwHttpErrors: false,
  8. timeout: 30000,
  9. headers: {
  10. 'User-Agent': 'Wiki-Bot/' + ( isDebug ? 'testing' : process.env.npm_package_version ) + ' (Discord; ' + process.env.npm_package_name + ')'
  11. },
  12. responseType: 'json'
  13. } );
  14. const {ShardingManager} = require('discord.js');
  15. const manager = new ShardingManager( './bot.js', {
  16. execArgv: ['--icu-data-dir=node_modules/full-icu'],
  17. shardArgs: ( isDebug ? ['debug'] : [] ),
  18. token: process.env.token
  19. } );
  20. var diedShards = 0;
  21. manager.on( 'shardCreate', shard => {
  22. console.log( `- Shard[${shard.id}]: Launched` );
  23. shard.on( 'spawn', message => {
  24. console.log( `- Shard[${shard.id}]: Spawned` );
  25. shard.send( {
  26. shard: {
  27. id: shard.id
  28. }
  29. } );
  30. } );
  31. shard.on( 'message', message => {
  32. if ( message === 'SIGKILL' ) {
  33. console.log( '\n- Killing all shards!\n\n' );
  34. manager.shards.forEach( shard => shard.kill() );
  35. if ( typeof server !== 'undefined' ) server.kill();
  36. }
  37. if ( message === 'postStats' && process.env.botlist ) postStats();
  38. } );
  39. shard.on( 'death', message => {
  40. if ( manager.respawn === false ) diedShards++;
  41. if ( message.exitCode ) {
  42. if ( !shard.ready ) {
  43. manager.respawn = false;
  44. console.log( `\n\n- Shard[${shard.id}]: Died due to fatal error, disable respawn!\n\n` );
  45. }
  46. else console.log( `\n\n- Shard[${shard.id}]: Died due to fatal error!\n\n` );
  47. }
  48. } );
  49. } );
  50. manager.spawn().then( shards => {
  51. if ( !isDebug && process.env.botlist ) {
  52. var botList = JSON.parse(process.env.botlist);
  53. for ( let [key, value] of Object.entries(botList) ) {
  54. if ( !value ) delete botList[key];
  55. }
  56. if ( Object.keys(botList).length ) {
  57. setInterval( postStats, 10800000, botList, shards.size ).unref();
  58. }
  59. }
  60. }, error => {
  61. console.error( '- Error while spawning the shards: ' + error );
  62. manager.respawnAll();
  63. } );
  64. var server;
  65. if ( process.env.dashboard ) {
  66. const dashboard = child_process.fork('./dashboard/index.js', ( isDebug ? ['debug'] : [] ));
  67. server = dashboard;
  68. dashboard.on( 'message', message => {
  69. if ( message.id ) {
  70. var data = {
  71. type: message.data.type,
  72. response: null,
  73. error: null
  74. };
  75. switch ( message.data.type ) {
  76. case 'getGuilds':
  77. return manager.broadcastEval(`Promise.all(
  78. ${JSON.stringify(message.data.guilds)}.map( id => {
  79. if ( this.guilds.cache.has(id) ) {
  80. let guild = this.guilds.cache.get(id);
  81. return guild.members.fetch('${message.data.member}').then( member => {
  82. return {
  83. patreon: guild.id in global.patreons,
  84. botPermissions: guild.me.permissions.bitfield,
  85. channels: guild.channels.cache.filter( channel => {
  86. return channel.isGuild();
  87. } ).sort( (a, b) => {
  88. return a.rawPosition - b.rawPosition;
  89. } ).map( channel => {
  90. return {
  91. id: channel.id,
  92. name: channel.name,
  93. userPermissions: member.permissionsIn(channel).bitfield,
  94. botPermissions: guild.me.permissionsIn(channel).bitfield
  95. };
  96. } ),
  97. roles: guild.roles.cache.filter( role => {
  98. return ( role.id !== guild.id );
  99. } ).sort( (a, b) => {
  100. return b.rawPosition - a.rawPosition;
  101. } ).map( role => {
  102. return {
  103. id: role.id,
  104. name: role.name,
  105. lower: ( guild.me.roles.highest.comparePositionTo(role) > 0 && !role.managed )
  106. };
  107. } )
  108. };
  109. }, error => {
  110. return 'noMember';
  111. } )
  112. }
  113. } )
  114. )`).then( results => {
  115. data.response = message.data.guilds.map( (guild, i) => {
  116. return results.find( result => result[i] )?.[i];
  117. } );
  118. }, error => {
  119. data.error = error.toString();
  120. } ).finally( () => {
  121. return dashboard.send( {id: message.id, data} );
  122. } );
  123. break;
  124. case 'getMember':
  125. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  126. let guild = this.guilds.cache.get('${message.data.guild}');
  127. guild.members.fetch('${message.data.member}').then( member => {
  128. var response = {
  129. patreon: guild.id in global.patreons,
  130. userPermissions: member.permissions.bitfield,
  131. botPermissions: guild.me.permissions.bitfield
  132. };
  133. if ( '${( message.data.channel || '' )}' ) {
  134. let channel = guild.channels.cache.get('${message.data.channel}');
  135. if ( channel?.isText() ) {
  136. response.userPermissions = channel.permissionsFor(member).bitfield;
  137. response.botPermissions = channel.permissionsFor(guild.me).bitfield;
  138. }
  139. else response.message = 'noChannel';
  140. }
  141. if ( '${( message.data.newchannel || '' )}' ) {
  142. let newchannel = guild.channels.cache.get('${message.data.newchannel}');
  143. if ( newchannel?.isText() ) {
  144. response.userPermissionsNew = newchannel.permissionsFor(member).bitfield;
  145. response.botPermissionsNew = newchannel.permissionsFor(guild.me).bitfield;
  146. }
  147. else response.message = 'noChannel';
  148. }
  149. return response;
  150. }, error => {
  151. return 'noMember';
  152. } );
  153. }`).then( results => {
  154. data.response = results.find( result => result );
  155. }, error => {
  156. data.error = error.toString();
  157. } ).finally( () => {
  158. return dashboard.send( {id: message.id, data} );
  159. } );
  160. break;
  161. case 'notifyGuild':
  162. return manager.broadcastEval(`if ( '${( message.data.prefix || '' )}' ) {
  163. global.patreons['${message.data.guild}'] = '${message.data.prefix}';
  164. }
  165. if ( '${( message.data.voice || '' )}' && '${message.data.guild}' in global.voice ) {
  166. global.voice['${message.data.guild}'] = '${message.data.voice}';
  167. }
  168. if ( this.guilds.cache.has('${message.data.guild}') ) {
  169. let channel = this.guilds.cache.get('${message.data.guild}').publicUpdatesChannel;
  170. if ( channel ) channel.send( \`${message.data.text.replace( /`/g, '\\`' )}\`, {
  171. embed: ${JSON.stringify(message.data.embed)},
  172. files: ${JSON.stringify(message.data.file)},
  173. allowedMentions: {parse: []}, split: true
  174. } ).catch( error => {} );
  175. }`).catch( error => {
  176. data.error = error.toString();
  177. } ).finally( () => {
  178. return dashboard.send( {id: message.id, data} );
  179. } );
  180. break;
  181. case 'createWebhook':
  182. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  183. let channel = this.guilds.cache.get('${message.data.guild}').channels.cache.get('${message.data.channel}');
  184. if ( channel ) channel.createWebhook( \`${message.data.name.replace( /`/g, '\\`' )}\`, {
  185. avatar: this.user.displayAvatarURL({format:'png',size:4096}),
  186. reason: \`${message.data.reason.replace( /`/g, '\\`' )}\`
  187. } ).then( webhook => {
  188. console.log( '- Dashboard: Webhook successfully created: ${message.data.guild}#${message.data.channel}' );
  189. webhook.send( \`${message.data.text.replace( /`/g, '\\`' )}\` ).catch(log_error);
  190. return webhook.id + '/' + webhook.token;
  191. }, error => {
  192. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  193. } );
  194. }`).then( results => {
  195. data.response = results.find( result => result );
  196. }, error => {
  197. data.error = error.toString();
  198. } ).finally( () => {
  199. return dashboard.send( {id: message.id, data} );
  200. } );
  201. break;
  202. case 'moveWebhook':
  203. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  204. this.fetchWebhook(...'${message.data.webhook}'.split('/')).then( webhook => {
  205. return webhook.edit( {
  206. channel: '${message.data.channel}'
  207. }, \`${message.data.reason.replace( /`/g, '\\`' )}\` ).then( newwebhook => {
  208. console.log( '- Dashboard: Webhook successfully moved: ${message.data.guild}#${message.data.channel}' );
  209. webhook.send( \`${message.data.text.replace( /`/g, '\\`' )}\` ).catch(log_error);
  210. return true;
  211. }, error => {
  212. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  213. } );
  214. }, error => {
  215. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  216. } );
  217. }`).then( results => {
  218. data.response = results.find( result => result );
  219. }, error => {
  220. data.error = error.toString();
  221. } ).finally( () => {
  222. return dashboard.send( {id: message.id, data} );
  223. } );
  224. break;
  225. default:
  226. console.log( '- [Dashboard]: Unknown message received!', message.data );
  227. data.error = 'Unknown message type: ' + message.data.type;
  228. return dashboard.send( {id: message.id, data} );
  229. }
  230. }
  231. console.log( '- [Dashboard]: Message received!', message );
  232. } );
  233. dashboard.on( 'error', error => {
  234. console.log( '- [Dashboard]: Error received!', error );
  235. } );
  236. dashboard.on( 'exit', (code) => {
  237. if ( code ) console.log( '- [Dashboard]: Process exited!', code );
  238. } );
  239. }
  240. /**
  241. * Post bot statistics to bot lists.
  242. * @param {Object} botList - The list of bot lists to post to.
  243. * @param {Number} shardCount - The total number of shards.
  244. */
  245. function postStats(botList = JSON.parse(process.env.botlist), shardCount = manager.totalShards) {
  246. manager.fetchClientValues('guilds.cache.size').then( results => {
  247. var guildCount = results.reduce( (acc, val) => acc + val, 0 );
  248. console.log( '- Current server count: ' + guildCount + '\n' + results.map( (count, i) => {
  249. return '-- Shard[' + i + ']: ' + count;
  250. } ).join('\n') );
  251. got.post( 'https://botblock.org/api/count', {
  252. json: Object.assign( {
  253. bot_id: process.env.bot,
  254. server_count: guildCount,
  255. shard_count: shardCount,
  256. shards: results
  257. }, botList )
  258. } ).then( response => {
  259. var body = response.body;
  260. if ( response.statusCode !== 200 || !body || body.error ) {
  261. console.log( '- ' + response.statusCode + ': Error while posting statistics to BotBlock.org: ' + ( body && body.message ) );
  262. return;
  263. }
  264. for ( let [key, value] of Object.entries(body.failure) ) {
  265. console.log( '- ' + value[0] + ': Error while posting statistics to ' + key + ': ' + value[1] );
  266. }
  267. }, error => {
  268. console.log( '- Error while posting statistics to BotBlock.org: ' + error );
  269. } );
  270. }, error => console.log( '- Error while getting the guild count: ' + error ) );
  271. }
  272. /**
  273. * End the process gracefully.
  274. * @param {NodeJS.Signals} signal - The signal received.
  275. */
  276. function graceful(signal) {
  277. console.log( '- ' + signal + ': Disabling respawn...' );
  278. manager.respawn = false;
  279. }
  280. process.once( 'SIGINT', graceful );
  281. process.once( 'SIGTERM', graceful );
  282. process.on( 'exit', code => {
  283. if ( diedShards >= manager.totalShards ) process.exit(1);
  284. } );
  285. if ( isDebug && process.argv[3]?.startsWith( '--timeout:' ) ) {
  286. let timeout = process.argv[3].split(':')[1];
  287. console.log( `\n- Close process in ${timeout} seconds!\n` );
  288. setTimeout( () => {
  289. console.log( `\n- Running for ${timeout} seconds, closing process!\n` );
  290. manager.shards.forEach( shard => shard.kill() );
  291. if ( typeof server !== 'undefined' ) server.kill();
  292. }, timeout * 1000 ).unref();
  293. }
  294. }, () => {
  295. process.exit(1);
  296. } )