main.js 14 KB

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