newMessage.js 12 KB

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