newMessage.js 12 KB

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