main.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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, ShardClientUtil: {shardIDForGuildID}} = 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() || channel.type === 'category' );
  87. } ).sort( (a, b) => {
  88. let aVal = a.rawPosition + 1;
  89. if ( a.type === 'category' ) aVal *= 1000;
  90. else if ( !a.parent ) aVal -= 1000;
  91. else aVal += ( a.parent.rawPosition + 1 ) * 1000;
  92. let bVal = b.rawPosition + 1;
  93. if ( b.type === 'category' ) bVal *= 1000;
  94. else if ( !b.parent ) bVal -= 1000;
  95. else bVal += ( b.parent.rawPosition + 1 ) * 1000;
  96. return aVal - bVal;
  97. } ).map( channel => {
  98. return {
  99. id: channel.id,
  100. name: channel.name,
  101. isCategory: ( channel.type === 'category' ),
  102. userPermissions: member.permissionsIn(channel).bitfield,
  103. botPermissions: guild.me.permissionsIn(channel).bitfield
  104. };
  105. } ),
  106. roles: guild.roles.cache.filter( role => {
  107. return ( role.id !== guild.id );
  108. } ).sort( (a, b) => {
  109. return b.rawPosition - a.rawPosition;
  110. } ).map( role => {
  111. return {
  112. id: role.id,
  113. name: role.name,
  114. lower: ( guild.me.roles.highest.comparePositionTo(role) > 0 && !role.managed )
  115. };
  116. } )
  117. };
  118. }, error => {
  119. return 'noMember';
  120. } )
  121. }
  122. } )
  123. )`).then( results => {
  124. data.response = message.data.guilds.map( (guild, i) => {
  125. return results.find( result => result[i] )?.[i];
  126. } );
  127. }, error => {
  128. data.error = error.toString();
  129. } ).finally( () => {
  130. return dashboard.send( {id: message.id, data} );
  131. } );
  132. break;
  133. case 'getMember':
  134. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  135. let guild = this.guilds.cache.get('${message.data.guild}');
  136. guild.members.fetch('${message.data.member}').then( member => {
  137. var response = {
  138. patreon: guild.id in global.patreons,
  139. userPermissions: member.permissions.bitfield,
  140. botPermissions: guild.me.permissions.bitfield
  141. };
  142. if ( '${( message.data.channel || '' )}' ) {
  143. let channel = guild.channels.cache.get('${message.data.channel}');
  144. if ( channel?.isText() ) {
  145. response.userPermissions = channel.permissionsFor(member).bitfield;
  146. response.botPermissions = channel.permissionsFor(guild.me).bitfield;
  147. }
  148. else response.message = 'noChannel';
  149. }
  150. if ( '${( message.data.newchannel || '' )}' ) {
  151. let newchannel = guild.channels.cache.get('${message.data.newchannel}');
  152. if ( newchannel?.isText() ) {
  153. response.userPermissionsNew = newchannel.permissionsFor(member).bitfield;
  154. response.botPermissionsNew = newchannel.permissionsFor(guild.me).bitfield;
  155. }
  156. else response.message = 'noChannel';
  157. }
  158. return response;
  159. }, error => {
  160. return 'noMember';
  161. } );
  162. }`, shardIDForGuildID(message.data.guild, manager.totalShards)).then( result => {
  163. data.response = result;
  164. }, error => {
  165. data.error = error.toString();
  166. } ).finally( () => {
  167. return dashboard.send( {id: message.id, data} );
  168. } );
  169. break;
  170. case 'notifyGuild':
  171. return manager.broadcastEval(`if ( '${( message.data.prefix || '' )}' ) {
  172. global.patreons['${message.data.guild}'] = '${message.data.prefix}';
  173. }
  174. if ( '${( message.data.voice || '' )}' && '${message.data.guild}' in global.voice ) {
  175. global.voice['${message.data.guild}'] = '${message.data.voice}';
  176. }
  177. if ( this.guilds.cache.has('${message.data.guild}') ) {
  178. let channel = this.guilds.cache.get('${message.data.guild}').publicUpdatesChannel;
  179. if ( channel ) channel.send( \`${message.data.text.replace( /`/g, '\\`' )}\`, {
  180. embed: ${JSON.stringify(message.data.embed)},
  181. files: ${JSON.stringify(message.data.file)},
  182. allowedMentions: {parse: []}, split: true
  183. } ).catch( error => {} );
  184. }`).catch( error => {
  185. data.error = error.toString();
  186. } ).finally( () => {
  187. return dashboard.send( {id: message.id, data} );
  188. } );
  189. break;
  190. case 'createWebhook':
  191. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  192. let channel = this.guilds.cache.get('${message.data.guild}').channels.cache.get('${message.data.channel}');
  193. if ( channel ) channel.createWebhook( \`${message.data.name.replace( /`/g, '\\`' )}\`, {
  194. avatar: this.user.displayAvatarURL({format:'png',size:4096}),
  195. reason: \`${message.data.reason.replace( /`/g, '\\`' )}\`
  196. } ).then( webhook => {
  197. console.log( '- Dashboard: Webhook successfully created: ${message.data.guild}#${message.data.channel}' );
  198. webhook.send( \`${message.data.text.replace( /`/g, '\\`' )}\` ).catch(log_error);
  199. return webhook.id + '/' + webhook.token;
  200. }, error => {
  201. console.log( '- Dashboard: Error while creating the webhook: ' + error );
  202. } );
  203. }`, shardIDForGuildID(message.data.guild, manager.totalShards)).then( result => {
  204. data.response = result;
  205. }, error => {
  206. data.error = error.toString();
  207. } ).finally( () => {
  208. return dashboard.send( {id: message.id, data} );
  209. } );
  210. break;
  211. case 'moveWebhook':
  212. return manager.broadcastEval(`if ( this.guilds.cache.has('${message.data.guild}') ) {
  213. this.fetchWebhook(...'${message.data.webhook}'.split('/')).then( webhook => {
  214. return webhook.edit( {
  215. channel: '${message.data.channel}'
  216. }, \`${message.data.reason.replace( /`/g, '\\`' )}\` ).then( newwebhook => {
  217. console.log( '- Dashboard: Webhook successfully moved: ${message.data.guild}#${message.data.channel}' );
  218. webhook.send( \`${message.data.text.replace( /`/g, '\\`' )}\` ).catch(log_error);
  219. return true;
  220. }, error => {
  221. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  222. } );
  223. }, error => {
  224. console.log( '- Dashboard: Error while moving the webhook: ' + error );
  225. } );
  226. }`, shardIDForGuildID(message.data.guild, manager.totalShards)).then( result => {
  227. data.response = result;
  228. }, error => {
  229. data.error = error.toString();
  230. } ).finally( () => {
  231. return dashboard.send( {id: message.id, data} );
  232. } );
  233. break;
  234. default:
  235. console.log( '- [Dashboard]: Unknown message received!', message.data );
  236. data.error = 'Unknown message type: ' + message.data.type;
  237. return dashboard.send( {id: message.id, data} );
  238. }
  239. }
  240. console.log( '- [Dashboard]: Message received!', message );
  241. } );
  242. dashboard.on( 'error', error => {
  243. console.log( '- [Dashboard]: Error received!', error );
  244. } );
  245. dashboard.on( 'exit', (code) => {
  246. if ( code ) console.log( '- [Dashboard]: Process exited!', code );
  247. } );
  248. }
  249. /**
  250. * Post bot statistics to bot lists.
  251. * @param {Object} botList - The list of bot lists to post to.
  252. * @param {Number} shardCount - The total number of shards.
  253. */
  254. function postStats(botList = JSON.parse(process.env.botlist), shardCount = manager.totalShards) {
  255. manager.fetchClientValues('guilds.cache.size').then( results => {
  256. var guildCount = results.reduce( (acc, val) => acc + val, 0 );
  257. console.log( '- Current server count: ' + guildCount + '\n' + results.map( (count, i) => {
  258. return '-- Shard[' + i + ']: ' + count;
  259. } ).join('\n') );
  260. got.post( 'https://botblock.org/api/count', {
  261. json: Object.assign( {
  262. bot_id: process.env.bot,
  263. server_count: guildCount,
  264. shard_count: shardCount,
  265. shards: results
  266. }, botList )
  267. } ).then( response => {
  268. var body = response.body;
  269. if ( response.statusCode !== 200 || !body || body.error ) {
  270. console.log( '- ' + response.statusCode + ': Error while posting statistics to BotBlock.org: ' + ( body && body.message ) );
  271. return;
  272. }
  273. for ( let [key, value] of Object.entries(body.failure) ) {
  274. console.log( '- ' + value[0] + ': Error while posting statistics to ' + key + ': ' + value[1] );
  275. }
  276. }, error => {
  277. console.log( '- Error while posting statistics to BotBlock.org: ' + error );
  278. } );
  279. }, error => console.log( '- Error while getting the guild count: ' + error ) );
  280. }
  281. /**
  282. * End the process gracefully.
  283. * @param {NodeJS.Signals} signal - The signal received.
  284. */
  285. function graceful(signal) {
  286. console.log( '- ' + signal + ': Disabling respawn...' );
  287. manager.respawn = false;
  288. }
  289. process.once( 'SIGINT', graceful );
  290. process.once( 'SIGTERM', graceful );
  291. process.on( 'exit', code => {
  292. if ( diedShards >= manager.totalShards ) process.exit(1);
  293. } );
  294. if ( isDebug && process.argv[3]?.startsWith( '--timeout:' ) ) {
  295. let timeout = process.argv[3].split(':')[1];
  296. console.log( `\n- Close process in ${timeout} seconds!\n` );
  297. setTimeout( () => {
  298. console.log( `\n- Running for ${timeout} seconds, closing process!\n` );
  299. manager.shards.forEach( shard => shard.kill() );
  300. if ( typeof server !== 'undefined' ) server.kill();
  301. }, timeout * 1000 ).unref();
  302. }
  303. }, () => {
  304. process.exit(1);
  305. } )