main.js 14 KB

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