main.js 12 KB

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