main.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. allowedMentions: {parse: []}, split: true
  173. } ).catch( error => {} );
  174. }`).catch( error => {
  175. data.error = error.toString();
  176. } ).finally( () => {
  177. return dashboard.send( {id: message.id, data} );
  178. } );
  179. break;
  180. case 'createWebhook':
  181. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  182. let channel = this.guilds.cache.get('${message.data.guild}').channels.cache.get('${message.data.channel}');
  183. if ( channel ) channel.createWebhook( \`${message.data.name.replace( /`/g, '\\`' )}\`, {
  184. avatar: this.user.displayAvatarURL({format:'png',size:4096}),
  185. reason: \`${message.data.reason.replace( /`/g, '\\`' )}\`
  186. } ).then( webhook => {
  187. console.log( '- Dashboard: Webhook successfully created: ${message.data.guild}#${message.data.channel}' );
  188. webhook.send( \`${message.data.text.replace( /`/g, '\\`' )}\` ).catch(log_error);
  189. return webhook.id + '/' + webhook.token;
  190. }, error => {
  191. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  192. } );
  193. }`).then( results => {
  194. data.response = results.find( result => result );
  195. }, error => {
  196. data.error = error.toString();
  197. } ).finally( () => {
  198. return dashboard.send( {id: message.id, data} );
  199. } );
  200. break;
  201. case 'moveWebhook':
  202. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  203. this.fetchWebhook(...'${message.data.webhook}'.split('/')).then( webhook => {
  204. return webhook.edit( {
  205. channel: '${message.data.channel}'
  206. }, \`${message.data.reason.replace( /`/g, '\\`' )}\` ).then( newwebhook => {
  207. console.log( '- Dashboard: Webhook successfully moved: ${message.data.guild}#${message.data.channel}' );
  208. webhook.send( \`${message.data.text.replace( /`/g, '\\`' )}\` ).catch(log_error);
  209. return true;
  210. }, error => {
  211. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  212. } );
  213. }, error => {
  214. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  215. } );
  216. }`).then( results => {
  217. data.response = results.find( result => result );
  218. }, error => {
  219. data.error = error.toString();
  220. } ).finally( () => {
  221. return dashboard.send( {id: message.id, data} );
  222. } );
  223. break;
  224. default:
  225. console.log( '- [Dashboard]: Unknown message received!', message.data );
  226. data.error = 'Unknown message type: ' + message.data.type;
  227. return dashboard.send( {id: message.id, data} );
  228. }
  229. }
  230. console.log( '- [Dashboard]: Message received!', message );
  231. } );
  232. dashboard.on( 'error', error => {
  233. console.log( '- [Dashboard]: Error received!', error );
  234. } );
  235. dashboard.on( 'exit', (code) => {
  236. if ( code ) console.log( '- [Dashboard]: Process exited!', code );
  237. } );
  238. }
  239. /**
  240. * Post bot statistics to bot lists.
  241. * @param {Object} botList - The list of bot lists to post to.
  242. * @param {Number} shardCount - The total number of shards.
  243. */
  244. function postStats(botList = JSON.parse(process.env.botlist), shardCount = manager.totalShards) {
  245. manager.fetchClientValues('guilds.cache.size').then( results => {
  246. var guildCount = results.reduce( (acc, val) => acc + val, 0 );
  247. console.log( '- Current server count: ' + guildCount + '\n' + results.map( (count, i) => {
  248. return '-- Shard[' + i + ']: ' + count;
  249. } ).join('\n') );
  250. got.post( 'https://botblock.org/api/count', {
  251. json: Object.assign( {
  252. bot_id: process.env.bot,
  253. server_count: guildCount,
  254. shard_count: shardCount,
  255. shards: results
  256. }, botList )
  257. } ).then( response => {
  258. var body = response.body;
  259. if ( response.statusCode !== 200 || !body || body.error ) {
  260. console.log( '- ' + response.statusCode + ': Error while posting statistics to BotBlock.org: ' + ( body && body.message ) );
  261. return;
  262. }
  263. for ( let [key, value] of Object.entries(body.failure) ) {
  264. console.log( '- ' + value[0] + ': Error while posting statistics to ' + key + ': ' + value[1] );
  265. }
  266. }, error => {
  267. console.log( '- Error while posting statistics to BotBlock.org: ' + error );
  268. } );
  269. }, error => console.log( '- Error while getting the guild count: ' + error ) );
  270. }
  271. /**
  272. * End the process gracefully.
  273. * @param {NodeJS.Signals} signal - The signal received.
  274. */
  275. function graceful(signal) {
  276. console.log( '- ' + signal + ': Disabling respawn...' );
  277. manager.respawn = false;
  278. }
  279. process.once( 'SIGINT', graceful );
  280. process.once( 'SIGTERM', graceful );
  281. process.on( 'exit', code => {
  282. if ( diedShards >= manager.totalShards ) process.exit(1);
  283. } );
  284. if ( isDebug && process.argv[3]?.startsWith( '--timeout:' ) ) {
  285. let timeout = process.argv[3].split(':')[1];
  286. console.log( `\n- Close process in ${timeout} seconds!\n` );
  287. setTimeout( () => {
  288. console.log( `\n- Running for ${timeout} seconds, closing process!\n` );
  289. manager.shards.forEach( shard => shard.kill() );
  290. if ( typeof server !== 'undefined' ) server.kill();
  291. }, timeout * 1000 ).unref();
  292. }
  293. }, () => {
  294. process.exit(1);
  295. } )