main.js 13 KB

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