bot.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import './util/globals.js';
  2. import { readdir } from 'fs';
  3. import Discord from 'discord.js';
  4. import db from './util/database.js';
  5. import Lang from './util/i18n.js';
  6. import Wiki from './util/wiki.js';
  7. import newMessage from './util/newMessage.js';
  8. import { breakOnTimeoutPause, allowDelete } from './util/functions.js';
  9. const client = new Discord.Client( {
  10. makeCache: Discord.Options.cacheWithLimits( {
  11. MessageManager: 100,
  12. PresenceManager: 0
  13. } ),
  14. sweepers: {
  15. messages: {
  16. interval: 300,
  17. lifetime: 300
  18. }
  19. },
  20. allowedMentions: {
  21. parse: [],
  22. repliedUser: true
  23. },
  24. failIfNotExists: false,
  25. presence: ( process.env.READONLY ? {
  26. status: 'dnd',
  27. activities: [{
  28. type: 'PLAYING',
  29. name: 'READONLY: ' + process.env.prefix + 'test' + ( process.env.SHARD_COUNT > 1 ? ' • Shard: ' + process.env.SHARDS : '' ),
  30. }],
  31. shardId: process.env.SHARDS
  32. } : {
  33. status: 'online',
  34. activities: [{
  35. type: 'PLAYING',
  36. name: process.env.prefix + 'help'
  37. }],
  38. shardId: process.env.SHARDS
  39. } ),
  40. intents: [
  41. Discord.Intents.FLAGS.GUILDS,
  42. Discord.Intents.FLAGS.GUILD_MESSAGES,
  43. Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
  44. Discord.Intents.FLAGS.GUILD_VOICE_STATES,
  45. Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
  46. Discord.Intents.FLAGS.DIRECT_MESSAGES,
  47. Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS
  48. ],
  49. partials: [
  50. 'CHANNEL'
  51. ]
  52. } );
  53. var isStop = false;
  54. client.on( 'ready', () => {
  55. console.log( '\n- ' + process.env.SHARDS + ': Successfully logged in as ' + client.user.username + '!\n' );
  56. [...voiceGuildsLang.keys()].forEach( guild => {
  57. if ( !client.guilds.cache.has(guild) ) voiceGuildsLang.delete(guild);
  58. } );
  59. client.application.commands.fetch();
  60. } );
  61. String.prototype.isMention = function(guild) {
  62. var text = this.trim();
  63. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  64. };
  65. Discord.Message.prototype.isAdmin = function() {
  66. return this.inGuild() && this.member && ( this.member.permissions.has(Discord.Permissions.FLAGS.MANAGE_GUILD) || ( this.isOwner() && this.evalUsed ) );
  67. };
  68. Discord.Message.prototype.isOwner = function() {
  69. return process.env.owner.split('|').includes( this.author.id );
  70. };
  71. Discord.Message.prototype.showEmbed = function() {
  72. return !this.inGuild() || this.channel.permissionsFor(client.user).has(Discord.Permissions.FLAGS.EMBED_LINKS);
  73. };
  74. Discord.Message.prototype.uploadFiles = function() {
  75. return !this.inGuild() || this.channel.permissionsFor(client.user).has(Discord.Permissions.FLAGS.ATTACH_FILES);
  76. };
  77. String.prototype.replaceSave = function(pattern, replacement) {
  78. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  79. };
  80. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  81. if ( breakOnTimeoutPause(this, ignorePause) ) return Promise.resolve();
  82. var emoji = '<:error:440871715938238494>';
  83. switch ( name ) {
  84. case 'nowiki':
  85. emoji = '<:unknown_wiki:505884572001763348>';
  86. break;
  87. case 'error':
  88. emoji = '<:error:440871715938238494>';
  89. break;
  90. default:
  91. emoji = name;
  92. }
  93. return this.react(emoji).catch(log_error);
  94. };
  95. Discord.MessageReaction.prototype.removeEmoji = function() {
  96. return this.users.remove().catch(log_error);
  97. };
  98. Discord.Message.prototype.sendChannel = function(message, ignorePause = false) {
  99. if ( breakOnTimeoutPause(this, ignorePause) ) return Promise.resolve();
  100. if ( message?.embeds?.length && !message.embeds[0] ) message.embeds = [];
  101. return this.channel.send( message ).then( msg => {
  102. allowDelete(msg, this.author.id);
  103. return msg;
  104. }, error => {
  105. log_error(error);
  106. this.reactEmoji('error');
  107. } );
  108. };
  109. Discord.Message.prototype.sendChannelError = function(message) {
  110. if ( breakOnTimeoutPause(this) ) return Promise.resolve();
  111. if ( message?.embeds?.length && !message.embeds[0] ) message.embeds = [];
  112. return this.channel.send( message ).then( msg => {
  113. msg.reactEmoji('error');
  114. allowDelete(msg, this.author.id);
  115. return msg;
  116. }, error => {
  117. log_error(error);
  118. this.reactEmoji('error');
  119. } );
  120. };
  121. Discord.Message.prototype.replyMsg = function(message, ignorePause = false, letDelete = true) {
  122. if ( breakOnTimeoutPause(this, ignorePause) ) return Promise.resolve();
  123. if ( message?.embeds?.length && !message.embeds[0] ) message.embeds = [];
  124. return this.reply( message ).then( msg => {
  125. if ( letDelete ) allowDelete(msg, this.author.id);
  126. return msg;
  127. }, error => {
  128. log_error(error);
  129. this.reactEmoji('error');
  130. } );
  131. };
  132. String.prototype.hasPrefix = function(prefix, flags = '') {
  133. var suffix = '';
  134. if ( prefix.endsWith( ' ' ) ) {
  135. prefix = prefix.trim();
  136. suffix = '(?: |$)';
  137. }
  138. var regex = new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + suffix, flags );
  139. return regex.test(this.replace( /\u200b/g, '' ).toLowerCase());
  140. };
  141. var slash = {};
  142. var buttons = {};
  143. var buttonsMap = {
  144. verify_again: 'verify'
  145. };
  146. readdir( './interactions', (error, files) => {
  147. if ( error ) return error;
  148. files.filter( file => file.endsWith('.js') ).forEach( file => {
  149. import('./interactions/' + file).then( ({default: command}) => {
  150. if ( command.hasOwnProperty('run') ) slash[command.name] = command.run;
  151. if ( command.hasOwnProperty('button') ) buttons[command.name] = command.button;
  152. } );
  153. } );
  154. } );
  155. /*
  156. !test eval msg.client.api.applications(msg.client.user.id).commands.post( {
  157. data: require('../interactions/commands.json')[0]
  158. } )
  159. */
  160. client.on( 'interactionCreate', interaction => {
  161. if ( interaction.inGuild() && typeof interaction.member.permissions === 'string' ) {
  162. interaction.member.permissions = new Discord.Permissions(interaction.member.permissions);
  163. }
  164. if ( interaction.channel?.partial ) return interaction.channel.fetch().then( () => {
  165. if ( interaction.isCommand() ) return slash_command(interaction);
  166. if ( interaction.isButton() ) return message_button(interaction);
  167. }, log_error );
  168. if ( interaction.isCommand() ) return slash_command(interaction);
  169. if ( interaction.isButton() ) return message_button(interaction);
  170. } );
  171. /**
  172. * Handle slash commands.
  173. * @param {Discord.CommandInteraction} interaction - The interaction.
  174. */
  175. function slash_command(interaction) {
  176. if ( breakOnTimeoutPause(interaction) ) return;
  177. if ( interaction.commandName === 'inline' ) console.log( ( interaction.guildId || '@' + interaction.user.id ) + ': Slash: /' + interaction.commandName );
  178. else console.log( ( interaction.guildId || '@' + interaction.user.id ) + ': Slash: /' + interaction.commandName + ' ' + interaction.options.data.map( option => {
  179. return option.name + ':' + option.value;
  180. } ).join(' ') );
  181. if ( !slash.hasOwnProperty(interaction.commandName) ) return;
  182. if ( !interaction.inGuild() ) {
  183. return slash[interaction.commandName](interaction, new Lang(), new Wiki());
  184. }
  185. let sqlargs = [interaction.guildId];
  186. if ( interaction.channel?.isThread() ) sqlargs.push(interaction.channel.parentId, '#' + interaction.channel.parent?.parentId);
  187. else sqlargs.push(interaction.channelId, '#' + interaction.channel?.parentId);
  188. db.query( 'SELECT wiki, lang FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', sqlargs ).then( ({rows:[row]}) => {
  189. return slash[interaction.commandName](interaction, new Lang(( row?.lang || interaction.guildLocale )), new Wiki(row?.wiki));
  190. }, dberror => {
  191. console.log( '- Slash: Error while getting the wiki: ' + dberror );
  192. return interaction.reply( {content: new Lang(( interaction.locale || interaction.guildLocale ), 'general').get('database') + '\n' + process.env.invite, ephemeral: true} ).catch(log_error);
  193. } );
  194. }
  195. /**
  196. * Handle message buttons.
  197. * @param {Discord.ButtonInteraction} interaction - The interaction.
  198. */
  199. function message_button(interaction) {
  200. if ( breakOnTimeoutPause(interaction) ) return;
  201. var cmd = ( buttonsMap.hasOwnProperty(interaction.customId) ? buttonsMap[interaction.customId] : interaction.customId );
  202. if ( !buttons.hasOwnProperty(cmd) ) return;
  203. if ( !interaction.inGuild() ) {
  204. return buttons[cmd](interaction, new Lang(), new Wiki());
  205. }
  206. let sqlargs = [interaction.guildId];
  207. if ( interaction.channel?.isThread() ) sqlargs.push(interaction.channel.parentId, '#' + interaction.channel.parent?.parentId);
  208. else sqlargs.push(interaction.channelId, '#' + interaction.channel?.parentId);
  209. db.query( 'SELECT wiki, lang FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', sqlargs ).then( ({rows:[row]}) => {
  210. return buttons[cmd](interaction, new Lang(( row?.lang || interaction.guildLocale )), new Wiki(row?.wiki));
  211. }, dberror => {
  212. console.log( '- Button: Error while getting the wiki: ' + dberror );
  213. return interaction.reply( {content: new Lang(( interaction.locale || interaction.guildLocale ), 'general').get('database') + '\n' + process.env.invite, ephemeral: true} ).catch(log_error);
  214. } );
  215. }
  216. client.on( 'messageCreate', msg => {
  217. if ( msg.channel.partial ) return msg.channel.fetch().then( () => {
  218. return messageCreate(msg);
  219. }, log_error );
  220. return messageCreate(msg);
  221. } );
  222. /**
  223. * Handle new messages.
  224. * @param {Discord.Message} msg - The message.
  225. */
  226. function messageCreate(msg) {
  227. if ( isStop || !msg.channel.isText() || msg.system || msg.webhookId || msg.author.bot || msg.author.id === msg.client.user.id ) return;
  228. if ( msg.member?.isCommunicationDisabled() || msg.guild?.me.isCommunicationDisabled() ) return;
  229. if ( !msg.content.hasPrefix(( patreonGuildsPrefix.get(msg.guildId) ?? process.env.prefix ), 'm') ) {
  230. if ( msg.content === process.env.prefix + 'help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  231. if ( msg.channel.permissionsFor(msg.client.user).has(( msg.channel.isThread() ? Discord.Permissions.FLAGS.SEND_MESSAGES_IN_THREADS : Discord.Permissions.FLAGS.SEND_MESSAGES )) ) {
  232. console.log( msg.guildId + ': ' + msg.content );
  233. let sqlargs = [msg.guildId];
  234. if ( msg.channel?.isThread() ) sqlargs.push(msg.channel.parentId, '#' + msg.channel.parent?.parentId);
  235. else sqlargs.push(msg.channelId, '#' + msg.channel.parentId);
  236. db.query( 'SELECT lang FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', sqlargs ).then( ({rows:[row]}) => {
  237. msg.replyMsg( new Lang(( row?.lang || msg.guild.preferredLocale ), 'general').get('prefix', patreonGuildsPrefix.get(msg.guildId)), true );
  238. }, dberror => {
  239. console.log( '- Error while getting the lang: ' + dberror );
  240. msg.replyMsg( new Lang(msg.guild.preferredLocale, 'general').get('prefix', patreonGuildsPrefix.get(msg.guildId)), true );
  241. } );
  242. }
  243. return;
  244. }
  245. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  246. }
  247. if ( msg.inGuild() ) {
  248. let sqlargs = [msg.guildId];
  249. if ( msg.channel.isThread() ) sqlargs.push(msg.channel.parentId, '#' + msg.channel.parent?.parentId);
  250. else sqlargs.push(msg.channelId, '#' + msg.channel.parentId);
  251. var permissions = msg.channel.permissionsFor(msg.client.user);
  252. var missing = permissions.missing([
  253. ( msg.channel.isThread() ? Discord.Permissions.FLAGS.SEND_MESSAGES_IN_THREADS : Discord.Permissions.FLAGS.SEND_MESSAGES ),
  254. Discord.Permissions.FLAGS.ADD_REACTIONS,
  255. Discord.Permissions.FLAGS.USE_EXTERNAL_EMOJIS,
  256. Discord.Permissions.FLAGS.READ_MESSAGE_HISTORY
  257. ]);
  258. if ( missing.length ) {
  259. if ( ( msg.isAdmin() || msg.isOwner() ) && msg.content.hasPrefix(( patreonGuildsPrefix.get(msg.guildId) ?? process.env.prefix ), 'm') ) {
  260. console.log( msg.guildId + ': Missing permissions - ' + missing.join(', ') );
  261. if ( !missing.includes( 'SEND_MESSAGES' ) && !missing.includes( 'SEND_MESSAGES_IN_THREADS' ) ) {
  262. db.query( 'SELECT lang FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', sqlargs ).then( ({rows:[row]}) => {
  263. return row?.lang;
  264. }, dberror => {
  265. console.log( '- Error while getting the lang: ' + dberror );
  266. } ).then( lang => {
  267. msg.sendChannel( {
  268. content: new Lang(( lang || msg.guild.preferredLocale ), 'general').get('missingperm') + ' `' + missing.join('`, `') + '`',
  269. reply: ( missing.includes( 'READ_MESSAGE_HISTORY' ) ? undefined : {messageReference: msg.id} )
  270. }, true );
  271. } );
  272. }
  273. }
  274. return;
  275. }
  276. db.query( 'SELECT wiki, lang, role, inline FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', sqlargs ).then( ({rows:[row]}) => {
  277. if ( row ) {
  278. if ( msg.guild.roles.cache.has(row.role) && msg.guild.roles.cache.get(row.role).comparePositionTo(msg.member.roles.highest) > 0 && !msg.isAdmin() ) {
  279. msg.onlyVerifyCommand = true;
  280. }
  281. newMessage(msg, new Lang(row.lang), row.wiki, patreonGuildsPrefix.get(msg.guildId), row.inline);
  282. }
  283. else {
  284. msg.defaultSettings = true;
  285. newMessage(msg, new Lang(msg.guild.preferredLocale));
  286. }
  287. }, dberror => {
  288. console.log( '- Error while getting the wiki: ' + dberror );
  289. msg.sendChannel( new Lang(msg.guild.preferredLocale, 'general').get('database') + '\n' + process.env.invite, true );
  290. } );
  291. }
  292. else newMessage(msg, new Lang());
  293. };
  294. client.on( 'voiceStateUpdate', (olds, news) => {
  295. if ( isStop || !( voiceGuildsLang.has(olds.guild.id) ) || !olds.guild.me.permissions.has('MANAGE_ROLES') || olds.channelId === news.channelId ) return;
  296. var lang = new Lang(voiceGuildsLang.get(olds.guild.id), 'voice');
  297. if ( olds.member && olds.channel ) {
  298. var oldrole = olds.member.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + olds.channel.name );
  299. if ( oldrole && oldrole.comparePositionTo(olds.guild.me.roles.highest) < 0 ) {
  300. console.log( olds.guild.id + ': ' + olds.member.id + ' left the voice channel "' + olds.channelId + '".' );
  301. olds.member.roles.remove( oldrole, lang.get('left', olds.member.displayName, olds.channel.name) ).catch(log_error);
  302. }
  303. }
  304. if ( news.member && news.channel ) {
  305. var newrole = news.guild.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + news.channel.name );
  306. if ( newrole && newrole.comparePositionTo(news.guild.me.roles.highest) < 0 ) {
  307. console.log( news.guild.id + ': ' + news.member.id + ' joined the voice channel "' + news.channelId + '".' );
  308. news.member.roles.add( newrole, lang.get('join', news.member.displayName, news.channel.name) ).catch(log_error);
  309. }
  310. }
  311. } );
  312. const leftGuilds = new Map();
  313. client.on( 'guildCreate', guild => {
  314. console.log( '- ' + guild.id + ': I\'ve been added to a server.' );
  315. if ( leftGuilds.has(guild.id) ) {
  316. clearTimeout(leftGuilds.get(guild.id));
  317. leftGuilds.delete(guild.id);
  318. }
  319. } );
  320. client.on( 'guildDelete', guild => {
  321. if ( !guild.available ) {
  322. console.log( '- ' + guild.id + ': This server isn\'t responding.' );
  323. return;
  324. }
  325. console.log( '- ' + guild.id + ': I\'ve been removed from a server.' );
  326. leftGuilds.set(guild.id, setTimeout(removeSettings, 300_000, guild.id).unref());
  327. } );
  328. function removeSettings(guild) {
  329. leftGuilds.delete(guild);
  330. if ( client.guilds.cache.has(guild) ) return;
  331. db.query( 'DELETE FROM discord WHERE main = $1', [guild] ).then( ({rowCount}) => {
  332. if ( patreonGuildsPrefix.has(guild) ) client.shard.broadcastEval( (discordClient, evalData) => {
  333. patreonGuildsPrefix.delete(evalData);
  334. }, {context: guild} );
  335. if ( voiceGuildsLang.has(guild) ) voiceGuildsLang.delete(guild);
  336. if ( rowCount ) console.log( '- ' + guild + ': Settings successfully removed.' );
  337. }, dberror => {
  338. console.log( '- ' + guild + ': Error while removing the settings: ' + dberror );
  339. } );
  340. }
  341. client.on( 'error', error => log_error(error, true) );
  342. client.on( 'warn', warning => log_warning(warning, false) );
  343. client.login(process.env.token).catch( error => {
  344. log_error(error, true, 'LOGIN-');
  345. return client.login(process.env.token).catch( error => {
  346. log_error(error, true, 'LOGIN-');
  347. return client.login(process.env.token).catch( error => {
  348. log_error(error, true, 'LOGIN-');
  349. process.exit(1);
  350. } );
  351. } );
  352. } );
  353. if ( isDebug ) client.on( 'debug', debug => {
  354. if ( isDebug ) console.log( '- ' + process.env.SHARDS + ': Debug: ' + debug );
  355. } );
  356. /**
  357. * End the process gracefully.
  358. * @param {NodeJS.Signals} signal - The signal received.
  359. */
  360. function graceful(signal) {
  361. isStop = true;
  362. console.log( '- ' + process.env.SHARDS + ': ' + signal + ': Preparing to close...' );
  363. setTimeout( () => {
  364. console.log( '- ' + process.env.SHARDS + ': ' + signal + ': Destroying client...' );
  365. client.destroy();
  366. db.end().then( () => {
  367. console.log( '- ' + process.env.SHARDS + ': ' + signal + ': Closed the database connection.' );
  368. process.exit(0);
  369. }, dberror => {
  370. console.log( '- ' + process.env.SHARDS + ': ' + signal + ': Error while closing the database connection: ' + dberror );
  371. } );
  372. }, 1_000 ).unref();
  373. }
  374. process.once( 'SIGINT', graceful );
  375. process.once( 'SIGTERM', graceful );