main.js 14 KB

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