main.js 14 KB

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