newMessage.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. msg.cleanContent.replace( /\u200b/g, '' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).replace( /(?<!\\)`.+?`/gs, '<code>' ).split('\n').forEach( line => {
  101. if ( line.hasPrefix(prefix) || !( line.includes( '[[' ) || line.includes( '{{' ) ) ) return;
  102. if ( line.includes( '[[' ) && line.includes( ']]' ) && linkcount <= linkmaxcount ) {
  103. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)\\[\\[([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\]\\]\\1', 'g' );
  104. let entry = null;
  105. while ( ( entry = regex.exec(line) ) !== null ) {
  106. if ( linkcount < linkmaxcount ) {
  107. linkcount++;
  108. console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  109. let title = entry[2].split('#')[0];
  110. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  111. links.push({title,section,spoiler:entry[1]});
  112. }
  113. else if ( linkcount === linkmaxcount ) {
  114. linkcount++;
  115. console.log( '- Message contains too many links!' );
  116. msg.reactEmoji('⚠️');
  117. break;
  118. }
  119. }
  120. }
  121. if ( line.includes( '{{' ) && line.includes( '}}' ) && count <= maxcount ) {
  122. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)(?<!\\{)\\{\\{([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\}\\}\\1', 'g' );
  123. let entry = null;
  124. while ( ( entry = regex.exec(line) ) !== null ) {
  125. if ( count < maxcount ) {
  126. count++;
  127. console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  128. let title = entry[2].split('#')[0];
  129. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  130. embeds.push({title,section,spoiler:entry[1]});
  131. }
  132. else if ( count === maxcount ) {
  133. count++;
  134. console.log( '- Message contains too many links!' );
  135. msg.reactEmoji('⚠️');
  136. break;
  137. }
  138. }
  139. }
  140. } );
  141. 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', {
  142. responseType: 'json'
  143. } ).then( response => {
  144. var body = response.body;
  145. if ( response.statusCode !== 200 || !body || !body.query ) {
  146. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  147. console.log( '- This wiki doesn\'t exist!' );
  148. msg.reactEmoji('nowiki');
  149. return;
  150. }
  151. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  152. return;
  153. }
  154. if ( body.query.normalized ) {
  155. body.query.normalized.forEach( title => links.filter( link => link.title === title.from ).forEach( link => link.title = title.to ) );
  156. }
  157. if ( body.query.interwiki ) {
  158. body.query.interwiki.forEach( interwiki => links.filter( link => link.title === interwiki.title ).forEach( link => {
  159. link.url = interwiki.url + ( link.section ? '#' + link.section.toSection() : '' );
  160. } ) );
  161. }
  162. if ( body.query.pages ) {
  163. var querypages = Object.values(body.query.pages);
  164. querypages.filter( page => page.invalid !== undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  165. links.splice(links.indexOf(link), 1);
  166. } ) );
  167. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  168. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  169. link.url = wiki.toLink(link.title, 'action=edit&redlink=1', '', body.query.general);
  170. } ) );
  171. }
  172. 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} );
  173. }, error => {
  174. if ( wiki.noWiki(error.message) ) {
  175. console.log( '- This wiki doesn\'t exist!' );
  176. msg.reactEmoji('nowiki');
  177. }
  178. else {
  179. console.log( '- Error while following the links: ' + error );
  180. }
  181. } );
  182. 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', {
  183. responseType: 'json'
  184. } ).then( response => {
  185. var body = response.body;
  186. if ( response.statusCode !== 200 || !body || !body.query ) {
  187. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  188. console.log( '- This wiki doesn\'t exist!' );
  189. msg.reactEmoji('nowiki');
  190. return;
  191. }
  192. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  193. return;
  194. }
  195. if ( body.query.normalized ) {
  196. body.query.normalized.forEach( title => embeds.filter( embed => embed.title === title.from ).forEach( embed => embed.title = title.to ) );
  197. }
  198. if ( body.query.pages ) {
  199. var querypages = Object.values(body.query.pages);
  200. querypages.filter( page => page.invalid !== undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  201. embeds.splice(embeds.indexOf(embed), 1);
  202. } ) );
  203. var missing = [];
  204. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  205. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  206. embeds.splice(embeds.indexOf(embed), 1);
  207. if ( page.ns === 0 && !embed.section ) {
  208. var template = querypages.find( template => template.ns === 10 && template.title.split(':').slice(1).join(':') === embed.title );
  209. if ( template && template.missing === undefined ) embed.template = wiki.toLink(template.title, '', '', body.query.general);
  210. }
  211. if ( embed.template || !body.query.variables || !body.query.variables.some( variable => variable.toUpperCase() === embed.title ) ) missing.push(embed);
  212. } ) );
  213. if ( missing.length ) {
  214. 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} );
  215. }
  216. }
  217. if ( embeds.length ) {
  218. if ( wiki.isFandom() ) embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  219. check_wiki.fandom(lang, msg, embed.title, wiki, '', reaction, embed.spoiler, '', embed.section);
  220. } ) );
  221. else embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  222. check_wiki.gamepedia(lang, msg, embed.title, wiki, '', reaction, embed.spoiler, '', embed.section);
  223. } ) );
  224. }
  225. }, error => {
  226. if ( wiki.noWiki(error.message) ) {
  227. console.log( '- This wiki doesn\'t exist!' );
  228. msg.reactEmoji('nowiki');
  229. }
  230. else {
  231. console.log( '- Error while following the links: ' + error );
  232. }
  233. } );
  234. }
  235. }
  236. module.exports = newMessage;