main.js 12 KB

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