main.js 14 KB

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