newMessage.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. const {domainToASCII} = require('url');
  2. const {Util} = require('discord.js');
  3. const logging = require('./logging.js');
  4. const {got, partialURIdecode} = require('./functions.js');
  5. const {limit: {command: commandLimit}, defaultSettings, wikiProjects} = require('./default.json');
  6. const Wiki = require('./wiki.js');
  7. const check_wiki = {
  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.guildId : '@' + 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.guildId] ? '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( {
  62. content: lang.get('general.limit', author.toString()),
  63. reply: {messageReference: msg.id},
  64. allowedMentions: {
  65. users: [author.id],
  66. repliedUser: true
  67. }
  68. } );
  69. return;
  70. }
  71. count++;
  72. line = line.substring(prefix.length);
  73. var invoke = line.split(' ')[0].toLowerCase();
  74. var args = line.split(' ').slice(1);
  75. var aliasInvoke = ( lang.aliases[invoke] || invoke );
  76. var ownercmd = ( msg.isOwner() && ownercmdmap.hasOwnProperty(aliasInvoke) );
  77. var pausecmd = ( msg.isAdmin() && pause[msg.guildId] && pausecmdmap.hasOwnProperty(aliasInvoke) );
  78. if ( msg.onlyVerifyCommand && !( aliasInvoke === 'verify' || pausecmd || ownercmd ) ) return;
  79. if ( channel.isGuild() && pause[msg.guildId] && !( pausecmd || ownercmd ) ) {
  80. return console.log( msg.guildId + ': Paused' );
  81. }
  82. console.log( ( channel.isGuild() ? msg.guildId : '@' + author.id ) + ': ' + prefix + line );
  83. if ( ownercmd ) return ownercmdmap[aliasInvoke](lang, msg, args, line, wiki);
  84. if ( pausecmd ) return pausecmdmap[aliasInvoke](lang, msg, args, line, wiki);
  85. if ( cmdmap.hasOwnProperty(aliasInvoke) ) return cmdmap[aliasInvoke](lang, msg, args, line, wiki);
  86. if ( invoke.startsWith( '!' ) && /^![a-z\d-]{1,50}$/.test(invoke) ) {
  87. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki('https://' + invoke.substring(1) + '.gamepedia.com/'), invoke + ' ');
  88. }
  89. if ( invoke.startsWith( '?' ) && /^\?(?:[a-z-]{2,12}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  90. let invokeWiki = wiki;
  91. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.fandom.com/' + invoke.substring(1).split('.')[0] + '/';
  92. else invokeWiki = 'https://' + invoke.substring(1) + '.fandom.com/';
  93. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki(invokeWiki), invoke + ' ');
  94. }
  95. if ( invoke.startsWith( '??' ) && /^\?\?(?:[a-z-]{2,12}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  96. let invokeWiki = wiki;
  97. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.wikia.org/' + invoke.substring(2).split('.')[0] + '/';
  98. else invokeWiki = 'https://' + invoke.substring(2) + '.wikia.org/';
  99. return cmdmap.LINK(lang, msg, args.join(' '), new Wiki(invokeWiki), invoke + ' ');
  100. }
  101. if ( invoke.startsWith( '!!' ) && /^!!(?:[a-z\d-]{1,50}\.)?[a-z\d-]{1,50}\.[a-z\d-]{1,10}(?:\/|$)/.test(domainToASCII(invoke)) ) {
  102. let project = wikiProjects.find( project => invoke.split('/')[0].endsWith( project.name ) );
  103. if ( project ) {
  104. let regex = invoke.match( new RegExp( project.regex ) );
  105. if ( regex && invoke === '!!' + regex[1] ) return cmdmap.LINK(lang, msg, args.join(' '), new Wiki('https://' + regex[1] + project.scriptPath), invoke + ' ');
  106. }
  107. }
  108. return cmdmap.LINK(lang, msg, line, wiki);
  109. } );
  110. if ( msg.onlyVerifyCommand ) return;
  111. if ( ( !channel.isGuild() || !pause[msg.guildId] ) && !noInline && ( cont.includes( '[[' ) || cont.includes( '{{' ) ) ) {
  112. var links = [];
  113. var embeds = [];
  114. var linkcount = 0;
  115. var linkmaxcount = maxcount + 5;
  116. var breakInline = false;
  117. cleanCont.replace( /\u200b/g, '' ).replace( /<a?(:\w+:)\d+>/g, '$1' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).replace( /(?<!\\)``.+?``/gs, '<code>' ).replace( /(?<!\\)`.+?`/gs, '<code>' ).split('\n').forEach( line => {
  118. if ( line.startsWith( '>>> ' ) ) breakInline = true;
  119. if ( line.startsWith( '> ' ) || breakInline ) return;
  120. if ( line.hasPrefix(prefix) || !( line.includes( '[[' ) || line.includes( '{{' ) ) ) return;
  121. line = line.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode );
  122. if ( line.includes( '[[' ) && line.includes( ']]' ) && linkcount <= linkmaxcount ) {
  123. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)\\[\\[([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\]\\]\\1', 'g' );
  124. let entry = null;
  125. while ( ( entry = regex.exec(line) ) !== null ) {
  126. if ( linkcount < linkmaxcount ) {
  127. linkcount++;
  128. console.log( ( channel.isGuild() ? msg.guildId : '@' + author.id ) + ': ' + entry[0] );
  129. let title = entry[2].split('#')[0];
  130. let section = entry[2].split('#').slice(1).join('#');
  131. links.push({title,section,spoiler:entry[1]});
  132. }
  133. else if ( linkcount === linkmaxcount ) {
  134. linkcount++;
  135. console.log( '- Message contains too many links!' );
  136. msg.reactEmoji('⚠️');
  137. break;
  138. }
  139. }
  140. }
  141. if ( line.includes( '{{' ) && line.includes( '}}' ) && count <= maxcount ) {
  142. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)(?<!\\{)\\{\\{([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\}\\}\\1', 'g' );
  143. let entry = null;
  144. while ( ( entry = regex.exec(line) ) !== null ) {
  145. if ( count < maxcount ) {
  146. count++;
  147. console.log( ( channel.isGuild() ? msg.guildId : '@' + author.id ) + ': ' + entry[0] );
  148. let title = entry[2].split('#')[0];
  149. let section = entry[2].split('#').slice(1).join('#');
  150. embeds.push({title,section,spoiler:entry[1]});
  151. }
  152. else if ( count === maxcount ) {
  153. count++;
  154. console.log( '- Message contains too many links!' );
  155. msg.reactEmoji('⚠️');
  156. break;
  157. }
  158. }
  159. }
  160. } );
  161. 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 => {
  162. var body = response.body;
  163. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query ) {
  164. if ( wiki.noWiki(response.url, response.statusCode) ) {
  165. console.log( '- This wiki doesn\'t exist!' );
  166. msg.reactEmoji('nowiki');
  167. return;
  168. }
  169. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  170. return;
  171. }
  172. wiki.updateWiki(body.query.general);
  173. if ( body.query.normalized ) {
  174. body.query.normalized.forEach( title => links.filter( link => link.title === title.from ).forEach( link => link.title = title.to ) );
  175. }
  176. if ( body.query.interwiki ) {
  177. body.query.interwiki.forEach( interwiki => links.filter( link => link.title === interwiki.title ).forEach( link => {
  178. logging(wiki, msg.guildId, 'inline', 'interwiki');
  179. link.url = ( link.section ? decodeURI(interwiki.url.split('#')[0]) + Wiki.toSection(link.section) : decodeURI(interwiki.url) );
  180. } ) );
  181. }
  182. if ( body.query.pages ) {
  183. var querypages = Object.values(body.query.pages);
  184. querypages.filter( page => page.invalid !== undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  185. links.splice(links.indexOf(link), 1);
  186. } ) );
  187. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  188. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  189. if ( wiki.isMiraheze() && page.ns === 0 && /^Mh:[a-z\d]+:/.test(page.title) ) {
  190. logging(wiki, msg.guildId, 'inline', 'interwiki');
  191. var iw_parts = page.title.split(':');
  192. var iw = new Wiki('https://' + iw_parts[1] + '.miraheze.org/w/');
  193. link.url = iw.toLink(iw_parts.slice(2).join(':'), '', link.section);
  194. return;
  195. }
  196. logging(wiki, msg.guildId, 'inline', 'redlink');
  197. link.url = wiki.toLink(link.title, 'action=edit&redlink=1');
  198. } ) );
  199. }
  200. if ( links.length ) Util.splitMessage( links.map( link => {
  201. if ( !link.url ) logging(wiki, msg.guildId, 'inline');
  202. return link.spoiler + '<' + ( link.url || wiki.toLink(link.title, '', link.section) ) + '>' + link.spoiler;
  203. } ).join('\n') ).forEach( textpart => msg.sendChannel( textpart ) );
  204. }, error => {
  205. if ( wiki.noWiki(error.message) ) {
  206. console.log( '- This wiki doesn\'t exist!' );
  207. msg.reactEmoji('nowiki');
  208. }
  209. else {
  210. console.log( '- Error while following the links: ' + error );
  211. }
  212. } );
  213. 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 => {
  214. var body = response.body;
  215. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query ) {
  216. if ( wiki.noWiki(response.url, response.statusCode) ) {
  217. console.log( '- This wiki doesn\'t exist!' );
  218. msg.reactEmoji('nowiki');
  219. return;
  220. }
  221. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  222. return;
  223. }
  224. wiki.updateWiki(body.query.general);
  225. if ( body.query.normalized ) {
  226. body.query.normalized.forEach( title => embeds.filter( embed => embed.title === title.from ).forEach( embed => embed.title = title.to ) );
  227. }
  228. if ( body.query.pages ) {
  229. var querypages = Object.values(body.query.pages);
  230. querypages.filter( page => page.invalid !== undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  231. embeds.splice(embeds.indexOf(embed), 1);
  232. } ) );
  233. var missing = [];
  234. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  235. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  236. if ( wiki.isMiraheze() && page.ns === 0 && /^Mh:[a-z\d]+:/.test(page.title) ) return;
  237. embeds.splice(embeds.indexOf(embed), 1);
  238. if ( page.ns === 0 && !embed.section ) {
  239. var template = querypages.find( template => template.ns === 10 && template.title.split(':').slice(1).join(':') === embed.title );
  240. if ( template && template.missing === undefined ) embed.template = wiki.toLink(template.title);
  241. }
  242. if ( embed.template || !body.query.variables || !body.query.variables.some( variable => variable.toUpperCase() === embed.title ) ) missing.push(embed);
  243. } ) );
  244. if ( missing.length ) Util.splitMessage( missing.map( embed => {
  245. if ( embed.template ) logging(wiki, msg.guildId, 'inline', 'template');
  246. else logging(wiki, msg.guildId, 'inline', 'redlink');
  247. return embed.spoiler + '<' + ( embed.template || wiki.toLink(embed.title, 'action=edit&redlink=1') ) + '>' + embed.spoiler;
  248. } ).join('\n') ).forEach( textpart => msg.sendChannel( textpart ) );
  249. }
  250. if ( embeds.length ) embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  251. logging(wiki, msg.guildId, 'inline', 'embed');
  252. check_wiki.general(lang, msg, embed.title, wiki, '', reaction, embed.spoiler, false, new URLSearchParams(), embed.section);
  253. } ) );
  254. }, error => {
  255. if ( wiki.noWiki(error.message) ) {
  256. console.log( '- This wiki doesn\'t exist!' );
  257. msg.reactEmoji('nowiki');
  258. }
  259. else {
  260. console.log( '- Error while following the links: ' + error );
  261. }
  262. } );
  263. }
  264. }
  265. module.exports = newMessage;