bot.js 17 KB

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