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. general: require('../cmds/wiki/general.js'),
  8. test: require('../cmds/test.js').run
  9. };
  10. const fs = require('fs');
  11. var cmdmap = {};
  12. var pausecmdmap = {};
  13. var ownercmdmap = {};
  14. fs.readdir( './cmds', (error, files) => {
  15. if ( error ) return error;
  16. files.filter( file => file.endsWith('.js') ).forEach( file => {
  17. var command = require('../cmds/' + file);
  18. if ( command.everyone ) cmdmap[command.name] = command.run;
  19. if ( command.pause ) pausecmdmap[command.name] = command.run;
  20. if ( command.owner ) ownercmdmap[command.name] = command.run;
  21. } );
  22. } );
  23. /**
  24. * Processes new messages.
  25. * @param {import('discord.js').Message} msg - The Discord message.
  26. * @param {import('./i18n.js')} lang - The user language.
  27. * @param {Wiki} [wiki] - The default wiki.
  28. * @param {String} [prefix] - The prefix for the message.
  29. * @param {Boolean} [noInline] - Parse inline commands?
  30. * @param {String} [content] - Overwrite for the message content.
  31. */
  32. function newMessage(msg, lang, wiki = defaultSettings.wiki, prefix = process.env.prefix, noInline = null, content = '') {
  33. wiki = new Wiki(wiki);
  34. msg.noInline = noInline;
  35. var cont = ( content || msg.content );
  36. var cleanCont = ( content && Util.cleanContent(content, msg) || msg.cleanContent );
  37. var author = msg.author;
  38. var channel = msg.channel;
  39. if ( msg.isOwner() && cont.hasPrefix(prefix) ) {
  40. let invoke = cont.substring(prefix.length).split(' ')[0].split('\n')[0].toLowerCase();
  41. let aliasInvoke = ( lang.aliases[invoke] || invoke );
  42. if ( ownercmdmap.hasOwnProperty(aliasInvoke) ) {
  43. cont = cont.substring(prefix.length);
  44. let args = cont.split(' ').slice(1);
  45. if ( cont.split(' ')[0].split('\n')[1] ) args.unshift( '', cont.split(' ')[0].split('\n')[1] );
  46. console.log( ( channel.isGuild() ? msg.guild.id : '@' + author.id ) + ': ' + prefix + cont );
  47. return ownercmdmap[aliasInvoke](lang, msg, args, cont, wiki);
  48. }
  49. }
  50. var count = 0;
  51. var maxcount = commandLimit[( patreons[msg.guild?.id] ? 'patreon' : 'default' )];
  52. var breakLines = false;
  53. cleanCont.replace( /\u200b/g, '' ).replace( /<a?(:\w+:)\d+>/g, '$1' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).split('\n').forEach( line => {
  54. if ( line.startsWith( '>>> ' ) ) breakLines = true;
  55. if ( !line.hasPrefix(prefix) || breakLines || count > maxcount ) return;
  56. if ( count === maxcount ) {
  57. count++;
  58. console.log( '- Message contains too many commands!' );
  59. msg.reactEmoji('⚠️');
  60. msg.sendChannelError( lang.get('general.limit', '<@' + author.id + '>'), {allowedMentions:{users:[author.id]}} );
  61. return;
  62. }
  63. count++;
  64. line = line.substring(prefix.length);
  65. var invoke = line.split(' ')[0].toLowerCase();
  66. var args = line.split(' ').slice(1);
  67. var aliasInvoke = ( lang.aliases[invoke] || invoke );
  68. var ownercmd = ( msg.isOwner() && ownercmdmap.hasOwnProperty(aliasInvoke) );
  69. var pausecmd = ( msg.isAdmin() && pause[msg.guild.id] && pausecmdmap.hasOwnProperty(aliasInvoke) );
  70. if ( msg.onlyVerifyCommand && !( aliasInvoke === 'verify' || pausecmd || ownercmd ) ) return;
  71. if ( channel.isGuild() && pause[msg.guild.id] && !( pausecmd || ownercmd ) ) {
  72. return console.log( msg.guild.id + ': Paused' );
  73. }
  74. console.log( ( channel.isGuild() ? msg.guild.id : '@' + author.id ) + ': ' + prefix + line );
  75. if ( ownercmd ) return ownercmdmap[aliasInvoke](lang, msg, args, line, wiki);
  76. if ( pausecmd ) return pausecmdmap[aliasInvoke](lang, msg, args, line, wiki);
  77. if ( cmdmap.hasOwnProperty(aliasInvoke) ) return cmdmap[aliasInvoke](lang, msg, args, line, wiki);
  78. if ( /^![a-z\d-]{1,50}$/.test(invoke) ) {
  79. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki('https://' + invoke.substring(1) + '.gamepedia.com/'), invoke + ' ');
  80. }
  81. if ( /^\?(?:[a-z-]{2,12}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  82. let invokeWiki = wiki;
  83. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.fandom.com/' + invoke.substring(1).split('.')[0] + '/';
  84. else invokeWiki = 'https://' + invoke.substring(1) + '.fandom.com/';
  85. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki(invokeWiki), invoke + ' ');
  86. }
  87. if ( /^\?\?(?:[a-z-]{2,12}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  88. let invokeWiki = wiki;
  89. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.wikia.org/' + invoke.substring(2).split('.')[0] + '/';
  90. else invokeWiki = 'https://' + invoke.substring(2) + '.wikia.org/';
  91. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki(invokeWiki), invoke + ' ');
  92. }
  93. if ( /^!!(?:[a-z\d-]{1,50}\.)?[a-z\d-]{1,50}\.[a-z\d-]{1,10}(?:\/|$)/.test(invoke) ) {
  94. let project = wikiProjects.find( project => invoke.split('/')[0].endsWith( project.name ) );
  95. if ( project ) {
  96. let regex = invoke.match( new RegExp( project.regex ) );
  97. if ( regex && invoke === '!!' + regex[1] ) return cmdmap.LINK(lang, msg, args.join(' '), new Wiki('https://' + regex[1] + project.scriptPath), invoke + ' ');
  98. }
  99. }
  100. return cmdmap.LINK(lang, msg, line, wiki);
  101. } );
  102. if ( msg.onlyVerifyCommand ) return;
  103. if ( ( !channel.isGuild() || !pause[msg.guild.id] ) && !noInline && ( cont.includes( '[[' ) || cont.includes( '{{' ) ) ) {
  104. var links = [];
  105. var embeds = [];
  106. var linkcount = 0;
  107. var linkmaxcount = maxcount + 5;
  108. var breakInline = false;
  109. cleanCont.replace( /\u200b/g, '' ).replace( /<a?(:\w+:)\d+>/g, '$1' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).replace( /(?<!\\)`.+?`/gs, '<code>' ).split('\n').forEach( line => {
  110. if ( line.startsWith( '>>> ' ) ) breakInline = true;
  111. if ( line.startsWith( '> ' ) || breakInline ) return;
  112. if ( line.hasPrefix(prefix) || !( line.includes( '[[' ) || line.includes( '{{' ) ) ) return;
  113. line = line.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode );
  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];
  122. let section = entry[2].split('#').slice(1).join('#');
  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];
  141. let section = entry[2].split('#').slice(1).join('#');
  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?.batchcomplete === undefined || !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?.batchcomplete === undefined || !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;