main.js 12 KB

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