newMessage.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. const {Util} = require('discord.js');
  2. const logging = require('./logging.js');
  3. const {partialURIdecode} = require('./functions.js');
  4. const {limit: {command: commandLimit}, defaultSettings, wikiProjects} = require('./default.json');
  5. const Wiki = require('./wiki.js');
  6. const check_wiki = {
  7. fandom: require('../cmds/wiki/fandom/general.js'),
  8. general: require('../cmds/wiki/general.js'),
  9. test: require('../cmds/test.js').run
  10. };
  11. const fs = require('fs');
  12. var cmdmap = {};
  13. var pausecmdmap = {};
  14. var ownercmdmap = {};
  15. fs.readdir( './cmds', (error, files) => {
  16. if ( error ) return error;
  17. files.filter( file => file.endsWith('.js') ).forEach( file => {
  18. var command = require('../cmds/' + file);
  19. if ( command.everyone ) cmdmap[command.name] = command.run;
  20. if ( command.pause ) pausecmdmap[command.name] = command.run;
  21. if ( command.owner ) ownercmdmap[command.name] = command.run;
  22. } );
  23. } );
  24. /**
  25. * Processes new messages.
  26. * @param {import('discord.js').Message} msg - The Discord message.
  27. * @param {import('./i18n.js')} lang - The user language.
  28. * @param {Wiki} [wiki] - The default wiki.
  29. * @param {String} [prefix] - The prefix for the message.
  30. * @param {Boolean} [noInline] - Parse inline commands?
  31. * @param {String} [content] - Overwrite for the message content.
  32. */
  33. function newMessage(msg, lang, wiki = defaultSettings.wiki, prefix = process.env.prefix, noInline = null, content = '') {
  34. wiki = new Wiki(wiki);
  35. msg.noInline = noInline;
  36. var cont = ( content || msg.content );
  37. var cleanCont = ( content && Util.cleanContent(content, msg) || msg.cleanContent );
  38. var author = msg.author;
  39. var channel = msg.channel;
  40. if ( msg.isOwner() && cont.hasPrefix(prefix) ) {
  41. let invoke = cont.substring(prefix.length).split(' ')[0].split('\n')[0].toLowerCase();
  42. let aliasInvoke = ( lang.aliases[invoke] || invoke );
  43. if ( ownercmdmap.hasOwnProperty(aliasInvoke) ) {
  44. cont = cont.substring(prefix.length);
  45. let args = cont.split(' ').slice(1);
  46. if ( cont.split(' ')[0].split('\n')[1] ) args.unshift( '', cont.split(' ')[0].split('\n')[1] );
  47. console.log( ( channel.isGuild() ? msg.guild.id : '@' + author.id ) + ': ' + prefix + cont );
  48. return ownercmdmap[aliasInvoke](lang, msg, args, cont, wiki);
  49. }
  50. }
  51. var count = 0;
  52. var maxcount = commandLimit[( patreons[msg.guild?.id] ? 'patreon' : 'default' )];
  53. var breakLines = false;
  54. cleanCont.replace( /\u200b/g, '' ).replace( /<a?(:\w+:)\d+>/g, '$1' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).split('\n').forEach( line => {
  55. if ( line.startsWith( '>>> ' ) ) breakLines = true;
  56. if ( !line.hasPrefix(prefix) || breakLines || count > maxcount ) return;
  57. if ( count === maxcount ) {
  58. count++;
  59. console.log( '- Message contains too many commands!' );
  60. msg.reactEmoji('⚠️');
  61. msg.sendChannelError( lang.get('general.limit', '<@' + author.id + '>'), {allowedMentions:{users:[author.id]}} );
  62. return;
  63. }
  64. count++;
  65. line = line.substring(prefix.length);
  66. var invoke = line.split(' ')[0].toLowerCase();
  67. var args = line.split(' ').slice(1);
  68. var aliasInvoke = ( lang.aliases[invoke] || invoke );
  69. var ownercmd = ( msg.isOwner() && ownercmdmap.hasOwnProperty(aliasInvoke) );
  70. var pausecmd = ( msg.isAdmin() && pause[msg.guild.id] && pausecmdmap.hasOwnProperty(aliasInvoke) );
  71. if ( msg.onlyVerifyCommand && !( aliasInvoke === 'verify' || pausecmd || ownercmd ) ) return;
  72. if ( channel.isGuild() && pause[msg.guild.id] && !( pausecmd || ownercmd ) ) {
  73. return console.log( msg.guild.id + ': Paused' );
  74. }
  75. console.log( ( channel.isGuild() ? msg.guild.id : '@' + author.id ) + ': ' + prefix + line );
  76. if ( ownercmd ) return ownercmdmap[aliasInvoke](lang, msg, args, line, wiki);
  77. if ( pausecmd ) return pausecmdmap[aliasInvoke](lang, msg, args, line, wiki);
  78. if ( cmdmap.hasOwnProperty(aliasInvoke) ) return cmdmap[aliasInvoke](lang, msg, args, line, wiki);
  79. if ( /^![a-z\d-]{1,50}$/.test(invoke) ) {
  80. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki('https://' + invoke.substring(1) + '.gamepedia.com/'), invoke + ' ');
  81. }
  82. if ( /^\?(?:[a-z-]{2,12}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  83. let invokeWiki = wiki;
  84. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.fandom.com/' + invoke.substring(1).split('.')[0] + '/';
  85. else invokeWiki = 'https://' + invoke.substring(1) + '.fandom.com/';
  86. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki(invokeWiki), invoke + ' ');
  87. }
  88. if ( /^\?\?(?:[a-z-]{2,12}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  89. let invokeWiki = wiki;
  90. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.wikia.org/' + invoke.substring(2).split('.')[0] + '/';
  91. else invokeWiki = 'https://' + invoke.substring(2) + '.wikia.org/';
  92. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki(invokeWiki), invoke + ' ');
  93. }
  94. if ( /^!!(?:[a-z\d-]{1,50}\.)?[a-z\d-]{1,50}\.[a-z\d-]{1,10}(?:\/|$)/.test(invoke) ) {
  95. let project = wikiProjects.find( project => invoke.split('/')[0].endsWith( project.name ) );
  96. if ( project ) {
  97. let regex = invoke.match( new RegExp( project.regex ) );
  98. if ( regex && invoke === '!!' + regex[1] ) return cmdmap.LINK(lang, msg, args.join(' '), new Wiki('https://' + regex[1] + project.scriptPath), invoke + ' ');
  99. }
  100. }
  101. return cmdmap.LINK(lang, msg, line, wiki);
  102. } );
  103. if ( msg.onlyVerifyCommand ) return;
  104. if ( ( !channel.isGuild() || !pause[msg.guild.id] ) && !noInline && ( cont.includes( '[[' ) || cont.includes( '{{' ) ) ) {
  105. var links = [];
  106. var embeds = [];
  107. var linkcount = 0;
  108. var linkmaxcount = maxcount + 5;
  109. var breakInline = false;
  110. cleanCont.replace( /\u200b/g, '' ).replace( /<a?(:\w+:)\d+>/g, '$1' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).replace( /(?<!\\)`.+?`/gs, '<code>' ).split('\n').forEach( line => {
  111. if ( line.startsWith( '>>> ' ) ) breakInline = true;
  112. if ( line.startsWith( '> ' ) || breakInline ) return;
  113. if ( line.hasPrefix(prefix) || !( line.includes( '[[' ) || line.includes( '{{' ) ) ) return;
  114. if ( line.includes( '[[' ) && line.includes( ']]' ) && linkcount <= linkmaxcount ) {
  115. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)\\[\\[([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\]\\]\\1', 'g' );
  116. let entry = null;
  117. while ( ( entry = regex.exec(line) ) !== null ) {
  118. if ( linkcount < linkmaxcount ) {
  119. linkcount++;
  120. console.log( ( channel.isGuild() ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  121. let title = entry[2].split('#')[0].replace( /(?:%[\dA-F]{2})+/g, partialURIdecode );
  122. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#').replace( /(?:%[\dA-F]{2})+/g, partialURIdecode ) : '' );
  123. links.push({title,section,spoiler:entry[1]});
  124. }
  125. else if ( linkcount === linkmaxcount ) {
  126. linkcount++;
  127. console.log( '- Message contains too many links!' );
  128. msg.reactEmoji('⚠️');
  129. break;
  130. }
  131. }
  132. }
  133. if ( line.includes( '{{' ) && line.includes( '}}' ) && count <= maxcount ) {
  134. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)(?<!\\{)\\{\\{([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\}\\}\\1', 'g' );
  135. let entry = null;
  136. while ( ( entry = regex.exec(line) ) !== null ) {
  137. if ( count < maxcount ) {
  138. count++;
  139. console.log( ( channel.isGuild() ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  140. let title = entry[2].split('#')[0].replace( /(?:%[\dA-F]{2})+/g, partialURIdecode );
  141. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#').replace( /(?:%[\dA-F]{2})+/g, partialURIdecode ) : '' );
  142. embeds.push({title,section,spoiler:entry[1]});
  143. }
  144. else if ( count === maxcount ) {
  145. count++;
  146. console.log( '- Message contains too many links!' );
  147. msg.reactEmoji('⚠️');
  148. break;
  149. }
  150. }
  151. }
  152. } );
  153. if ( links.length ) got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&iwurl=true&titles=' + encodeURIComponent( links.map( link => link.title ).join('|') ) + '&format=json' ).then( response => {
  154. var body = response.body;
  155. if ( response.statusCode !== 200 || !body || !body.query ) {
  156. if ( wiki.noWiki(response.url, response.statusCode) ) {
  157. console.log( '- This wiki doesn\'t exist!' );
  158. msg.reactEmoji('nowiki');
  159. return;
  160. }
  161. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  162. return;
  163. }
  164. wiki.updateWiki(body.query.general);
  165. if ( body.query.normalized ) {
  166. body.query.normalized.forEach( title => links.filter( link => link.title === title.from ).forEach( link => link.title = title.to ) );
  167. }
  168. if ( body.query.interwiki ) {
  169. body.query.interwiki.forEach( interwiki => links.filter( link => link.title === interwiki.title ).forEach( link => {
  170. logging(wiki, msg.guild?.id, 'inline', 'interwiki');
  171. link.url = ( link.section ? interwiki.url.split('#')[0] + Wiki.toSection(link.section) : interwiki.url );
  172. } ) );
  173. }
  174. if ( body.query.pages ) {
  175. var querypages = Object.values(body.query.pages);
  176. querypages.filter( page => page.invalid !== undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  177. links.splice(links.indexOf(link), 1);
  178. } ) );
  179. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  180. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  181. if ( wiki.isMiraheze() && page.ns === 0 && /^Mh:[a-z\d]+:/.test(page.title) ) {
  182. logging(wiki, msg.guild?.id, 'inline', 'interwiki');
  183. var iw_parts = page.title.split(':');
  184. var iw = new Wiki('https://' + iw_parts[1] + '.miraheze.org/w/');
  185. link.url = iw.toLink(iw_parts.slice(2).join(':'), '', link.section);
  186. return;
  187. }
  188. logging(wiki, msg.guild?.id, 'inline', 'redlink');
  189. link.url = wiki.toLink(link.title, 'action=edit&redlink=1');
  190. } ) );
  191. }
  192. if ( links.length ) msg.sendChannel( links.map( link => {
  193. if ( !link.url ) logging(wiki, msg.guild?.id, 'inline');
  194. return link.spoiler + '<' + ( link.url || wiki.toLink(link.title, '', link.section) ) + '>' + link.spoiler;
  195. } ).join('\n'), {split:true} );
  196. }, error => {
  197. if ( wiki.noWiki(error.message) ) {
  198. console.log( '- This wiki doesn\'t exist!' );
  199. msg.reactEmoji('nowiki');
  200. }
  201. else {
  202. console.log( '- Error while following the links: ' + error );
  203. }
  204. } );
  205. if ( embeds.length ) got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general' + ( wiki.isFandom() ? '' : '|variables' ) + '&titles=' + encodeURIComponent( embeds.map( embed => embed.title + '|Template:' + embed.title ).join('|') ) + '&format=json' ).then( response => {
  206. var body = response.body;
  207. if ( response.statusCode !== 200 || !body || !body.query ) {
  208. if ( wiki.noWiki(response.url, response.statusCode) ) {
  209. console.log( '- This wiki doesn\'t exist!' );
  210. msg.reactEmoji('nowiki');
  211. return;
  212. }
  213. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  214. return;
  215. }
  216. wiki.updateWiki(body.query.general);
  217. if ( body.query.normalized ) {
  218. body.query.normalized.forEach( title => embeds.filter( embed => embed.title === title.from ).forEach( embed => embed.title = title.to ) );
  219. }
  220. if ( body.query.pages ) {
  221. var querypages = Object.values(body.query.pages);
  222. querypages.filter( page => page.invalid !== undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  223. embeds.splice(embeds.indexOf(embed), 1);
  224. } ) );
  225. var missing = [];
  226. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  227. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  228. if ( wiki.isMiraheze() && page.ns === 0 && /^Mh:[a-z\d]+:/.test(page.title) ) return;
  229. embeds.splice(embeds.indexOf(embed), 1);
  230. if ( page.ns === 0 && !embed.section ) {
  231. var template = querypages.find( template => template.ns === 10 && template.title.split(':').slice(1).join(':') === embed.title );
  232. if ( template && template.missing === undefined ) embed.template = wiki.toLink(template.title);
  233. }
  234. if ( embed.template || !body.query.variables || !body.query.variables.some( variable => variable.toUpperCase() === embed.title ) ) missing.push(embed);
  235. } ) );
  236. if ( missing.length ) {
  237. msg.sendChannel( missing.map( embed => {
  238. if ( embed.template ) logging(wiki, msg.guild?.id, 'inline', 'template');
  239. else logging(wiki, msg.guild?.id, 'inline', 'redlink');
  240. return embed.spoiler + '<' + ( embed.template || wiki.toLink(embed.title, 'action=edit&redlink=1') ) + '>' + embed.spoiler;
  241. } ).join('\n'), {split:true} );
  242. }
  243. }
  244. if ( embeds.length ) embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  245. logging(wiki, msg.guild?.id, 'inline', 'embed');
  246. check_wiki.general(lang, msg, embed.title, wiki, '', reaction, embed.spoiler, new URLSearchParams(), embed.section);
  247. } ) );
  248. }, error => {
  249. if ( wiki.noWiki(error.message) ) {
  250. console.log( '- This wiki doesn\'t exist!' );
  251. msg.reactEmoji('nowiki');
  252. }
  253. else {
  254. console.log( '- Error while following the links: ' + error );
  255. }
  256. } );
  257. }
  258. }
  259. module.exports = newMessage;