inline.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. const logging = require('../util/logging.js');
  2. const Wiki = require('../util/wiki.js');
  3. const {limitLength, partialURIdecode, allowDelete} = require('../util/functions.js');
  4. /**
  5. * Post a message with inline wiki links.
  6. * @param {Object} interaction - The interaction.
  7. * @param {import('../util/i18n.js')} lang - The user language.
  8. * @param {import('../util/wiki.js')} wiki - The wiki for the interaction.
  9. * @param {import('discord.js').TextChannel} [channel] - The guild for the interaction.
  10. */
  11. function slash_inline(interaction, lang, wiki, channel) {
  12. var text = ( interaction.data.options?.[0]?.value || '' ).replace( /\]\(/g, ']\\(' ).trim();
  13. if ( !text ) {
  14. return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
  15. json: {
  16. //type: 4,
  17. type: 3,
  18. data: {
  19. content: lang.get('interaction.inline'),
  20. allowed_mentions: {
  21. parse: []
  22. },
  23. flags: 64
  24. }
  25. }
  26. } ).then( response => {
  27. if ( response.statusCode !== 204 ) {
  28. console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
  29. }
  30. }, log_error );
  31. }
  32. var allowed_mentions = {
  33. parse: ['users']
  34. };
  35. if ( interaction.guild_id ) {
  36. if ( ( (interaction.member.permissions & 1 << 3) === 1 << 3 ) // ADMINISTRATOR
  37. || ( (interaction.member.permissions & 1 << 17) === 1 << 17 ) ) { // MENTION_EVERYONE
  38. allowed_mentions.parse = ['users', 'roles', 'everyone'];
  39. }
  40. else if ( channel?.guild ) {
  41. allowed_mentions.roles = channel.guild.roles.cache.filter( role => role.mentionable ).map( role => role.id );
  42. if ( allowed_mentions.roles.length > 100 ) {
  43. allowed_mentions.roles = allowed_mentions.roles.slice(0, 100);
  44. }
  45. }
  46. }
  47. if ( text.length > 1800 ) text = text.substring(0, 1800) + '\u2026';
  48. return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
  49. json: {
  50. type: 4,
  51. data: {
  52. content: text,
  53. allowed_mentions,
  54. flags: 0
  55. }
  56. }
  57. } ).then( aresponse => {
  58. if ( aresponse.statusCode !== 204 ) {
  59. console.log( '- Slash: ' + aresponse.statusCode + ': Error while sending the response: ' + aresponse.body?.message );
  60. return;
  61. }
  62. if ( !text.includes( '{{' ) && !( text.includes( '[[' ) && text.includes( ']]' ) ) ) {
  63. return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
  64. json: {}
  65. } ).then( presponse => {
  66. if ( presponse.statusCode === 200 && presponse.body?.id ) {
  67. channel?.messages.fetch(presponse.body.id).then( msg => {
  68. allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
  69. }, () => {} );
  70. }
  71. }, () => {} );
  72. }
  73. var textReplacement = [];
  74. var replacedText = text.replace( /\u200b/g, '' ).replace( /(?<!\\)(?:<a?(:\w+:)\d+>|```.+?```|`.+?`)/gs, (replacement, arg) => {
  75. textReplacement.push(replacement);
  76. return '\u200b<replacement' + ( arg ? '\u200b' + textReplacement.length + '\u200b' + arg : '' ) + '>\u200b';
  77. } );
  78. var templates = [];
  79. var links = [];
  80. var breakInline = false;
  81. replacedText.replace( /\u200b<replacement\u200b\d+\u200b(.+?)>\u200b/g, '$1' ).replace( /(?:%[\dA-F]{2})+/g, partialURIdecode ).split('\n').forEach( line => {
  82. if ( line.startsWith( '>>> ' ) ) breakInline = true;
  83. if ( line.startsWith( '> ' ) || breakInline ) return;
  84. var inlineLink = null;
  85. var regex = /(?<!\\|\{)\{\{(?:\s*(?:subst|safesubst|raw|msg|msgnw):)?([^<>\[\]\|\{\}\x01-\x1F\x7F#]+)(?<!\\)(?:\||\}\})/g;
  86. while ( ( inlineLink = regex.exec(line) ) !== null ) {
  87. let title = inlineLink[1].trim();
  88. if ( !title.replace( /:/g, '' ).trim().length || title.startsWith( '/' ) ) continue;
  89. if ( title.startsWith( 'int:' ) ) templates.push({
  90. raw: title,
  91. title: title.replace( /^int:/, 'MediaWiki:' ),
  92. template: title.replace( /^int:/, 'MediaWiki:' )
  93. });
  94. else templates.push({raw: title, title, template: 'Template:' + title});
  95. }
  96. inlineLink = null;
  97. regex = /(?<!\\)\[\[([^<>\[\]\|\{\}\x01-\x1F\x7F]+)(?:\|(?:(?!\[\[|\]\\\]).)*?)?(?<!\\)\]\]/g;
  98. while ( ( inlineLink = regex.exec(line) ) !== null ) {
  99. inlineLink[1] = inlineLink[1].trim();
  100. let title = inlineLink[1].split('#')[0].trim();
  101. let section = inlineLink[1].split('#').slice(1).join('#');
  102. if ( !title.replace( /:/g, '' ).trim().length || title.startsWith( '/' ) ) continue;
  103. links.push({raw: title, title, section});
  104. }
  105. } );
  106. if ( !templates.length && !links.length ) {
  107. return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
  108. json: {}
  109. } ).then( presponse => {
  110. if ( presponse.statusCode === 200 && presponse.body?.id ) {
  111. channel?.messages.fetch(presponse.body.id).then( msg => {
  112. allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
  113. }, () => {} );
  114. }
  115. }, () => {} );
  116. }
  117. return got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&iwurl=true&titles=' + encodeURIComponent( [
  118. ...templates.map( link => link.title + '|' + link.template ),
  119. ...links.map( link => link.title )
  120. ].join('|') ) + '&format=json' ).then( response => {
  121. var body = response.body;
  122. if ( response.statusCode !== 200 || body?.batchcomplete === undefined || !body?.query ) {
  123. if ( wiki.noWiki(response.url, response.statusCode) ) {
  124. console.log( '- This wiki doesn\'t exist!' );
  125. }
  126. else {
  127. console.log( '- ' + response.statusCode + ': Error while following the links: ' + body?.error?.info );
  128. }
  129. return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
  130. json: {}
  131. } ).then( presponse => {
  132. if ( presponse.statusCode === 200 && presponse.body?.id ) {
  133. channel?.messages.fetch(presponse.body.id).then( msg => {
  134. allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
  135. }, () => {} );
  136. }
  137. }, () => {} );
  138. }
  139. logging(wiki, interaction.guild_id, 'slash', 'inline');
  140. wiki.updateWiki(body.query.general);
  141. if ( body.query.normalized ) {
  142. body.query.normalized.forEach( title => {
  143. templates.filter( link => link.title === title.from ).forEach( link => link.title = title.to );
  144. templates.filter( link => link.template === title.from ).forEach( link => link.template = title.to );
  145. links.filter( link => link.title === title.from ).forEach( link => link.title = title.to );
  146. } );
  147. }
  148. if ( body.query.interwiki ) {
  149. body.query.interwiki.forEach( interwiki => {
  150. templates.filter( link => link.title === interwiki.title ).forEach( link => {
  151. link.url = decodeURI(interwiki.url)
  152. } );
  153. links.filter( link => link.title === interwiki.title ).forEach( link => {
  154. link.url = ( link.section ? decodeURI(interwiki.url.split('#')[0]) + Wiki.toSection(link.section) : decodeURI(interwiki.url) );
  155. } );
  156. } );
  157. }
  158. if ( body.query.pages ) {
  159. Object.values(body.query.pages).forEach( page => {
  160. templates.filter( link => link.title === page.title ).forEach( link => {
  161. if ( page.invalid !== undefined || ( page.missing !== undefined && page.known === undefined ) ) {
  162. link.title = '';
  163. }
  164. else if ( page.ns === 0 && !link.raw.startsWith( ':' ) ) {
  165. link.title = '';
  166. }
  167. } );
  168. templates.filter( link => link.template === page.title ).forEach( link => {
  169. if ( page.invalid !== undefined || ( page.missing !== undefined && page.known === undefined ) ) {
  170. link.template = '';
  171. }
  172. } );
  173. links.filter( link => link.title === page.title ).forEach( link => {
  174. link.ns = page.ns;
  175. if ( page.invalid !== undefined ) return links.splice(links.indexOf(link), 1);
  176. if ( page.missing !== undefined && page.known === undefined ) {
  177. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) {
  178. return;
  179. }
  180. if ( wiki.isMiraheze() && page.ns === 0 && /^Mh:[a-z\d]+:/.test(page.title) ) {
  181. var iw_parts = page.title.split(':');
  182. var iw = new Wiki('https://' + iw_parts[1] + '.miraheze.org/w/');
  183. link.url = iw.toLink(iw_parts.slice(2).join(':'), '', link.section, true);
  184. return;
  185. }
  186. return links.splice(links.indexOf(link), 1);
  187. }
  188. } );
  189. } );
  190. }
  191. templates = templates.filter( link => link.title || link.template );
  192. if ( templates.length || links.length ) {
  193. breakInline = false;
  194. replacedText = replacedText.split('\n').map( line => {
  195. if ( line.startsWith( '>>> ' ) ) breakInline = true;
  196. if ( line.startsWith( '> ' ) || breakInline ) return line;
  197. let emojiReplacements = 1;
  198. let regex = /(?<!\\|\{)(\{\{(?:\s*(?:subst|safesubst|raw|msg|msgnw):)?\s*)((?:[^<>\[\]\|\{\}\x01-\x1F\x7F#]|\u200b<replacement\u200b\d+\u200b.+?>\u200b)+?)(\s*(?<!\\)\||\}\})/g;
  199. line = line.replace( regex, (fullLink, linkprefix, title, linktrail) => {
  200. title = title.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode );
  201. let rawTitle = title.replace( /\u200b<replacement\u200b\d+\u200b(.+?)>\u200b/g, '$1' ).trim();
  202. let link = templates.find( link => link.raw === rawTitle );
  203. if ( !link ) return fullLink;
  204. console.log( ( interaction.guild_id || '@' + interaction.user.id ) + ': Slash: ' + fullLink );
  205. title = title.replace( /\u200b<replacement\u200b(\d+)\u200b(.+?)>\u200b/g, (replacement, id, arg) => {
  206. links.splice(id - emojiReplacements, 1);
  207. emojiReplacements++;
  208. return arg;
  209. } );
  210. if ( title.startsWith( 'int:' ) ) {
  211. title = title.replace( /^int:\s*/, replacement => {
  212. linkprefix += replacement;
  213. return '';
  214. } );
  215. }
  216. return linkprefix + '[' + title + '](<' + ( link.url || wiki.toLink(link.title || link.template, '', '', true) ) + '>)' + linktrail;
  217. } );
  218. regex = new RegExp( '([' + body.query.general.linkprefixcharset.replace( /\\x([a-fA-f0-9]{4,6}|\{[a-fA-f0-9]{4,6}\})/g, '\\u$1' ) + ']+)?' + '(?<!\\\\)\\[\\[' + '((?:[^' + "<>\\[\\]\\|\{\}\\x01-\\x1F\\x7F" + ']|' + '\\u200b<replacement\\u200b\\d+\\u200b.+?>\\u200b' + ')+)' + '(?:\\|((?:(?!\\[\\[|\\]\\(|\\]\\\\\\]).)*?))?' + '(?<!\\\\)\\]\\]' + body.query.general.linktrail.replace( /\\x([a-fA-f0-9]{4,6}|\{[a-fA-f0-9]{4,6}\})/g, '\\u$1' ).replace( /^\/\^(\(\[.+?\]\+\))\(\.\*\)\$\/sDu?$/, '$1?' ), 'gu' );
  219. line = line.replace( regex, (fullLink, linkprefix = '', title, display, linktrail = '') => {
  220. title = title.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode );
  221. let rawTitle = title.replace( /\u200b<replacement\u200b\d+\u200b(.+?)>\u200b/g, '$1' ).split('#')[0].trim();
  222. let link = links.find( link => link.raw === rawTitle );
  223. if ( !link ) return fullLink;
  224. console.log( ( interaction.guild_id || '@' + interaction.user.id ) + ': Slash: ' + fullLink );
  225. title = title.replace( /\u200b<replacement\u200b(\d+)\u200b(.+?)>\u200b/g, (replacement, id, arg) => {
  226. links.splice(id - emojiReplacements, 1);
  227. emojiReplacements++;
  228. return arg;
  229. } );
  230. if ( display === undefined ) display = title.replace( /^\s*:?/, '' );
  231. if ( !display.trim() ) {
  232. display = title.replace( /^\s*:/, '' );
  233. if ( display.includes( ',' ) && !/ ([^\(\)]+)$/.test(display) ) {
  234. display = display.replace( /^([^,]+), .*$/, '$1' );
  235. }
  236. display = display.replace( / ([^\(\)]+)$/, '' );
  237. if ( link.url || link.ns !== 0 ) {
  238. display = display.split(':').slice(1).join(':');
  239. }
  240. }
  241. return '[' + ( linkprefix + display + linktrail ).replace( /\[\]\(\)/g, '\\$&' ) + '](<' + ( link.url || wiki.toLink(link.title, '', link.section, true) ) + '>)';
  242. } );
  243. return line;
  244. } ).join('\n');
  245. text = replacedText.replace( /\u200b<replacement(?:\u200b\d+\u200b.+?)?>\u200b/g, replacement => {
  246. return textReplacement.shift();
  247. } );
  248. if ( text.length > 1900 ) text = limitLength(text, 1900, 100);
  249. return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
  250. json: {
  251. content: text,
  252. allowed_mentions
  253. }
  254. } ).then( presponse => {
  255. if ( presponse.statusCode !== 200 ) {
  256. console.log( '- Slash: ' + presponse.statusCode + ': Error while sending the response: ' + presponse.body?.message );
  257. }
  258. channel?.messages.fetch(presponse.body.id).then( msg => {
  259. allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
  260. }, () => {} );
  261. }, log_error );
  262. }
  263. else return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
  264. json: {}
  265. } ).then( presponse => {
  266. if ( presponse.statusCode === 200 && presponse.body?.id ) {
  267. channel?.messages.fetch(presponse.body.id).then( msg => {
  268. allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
  269. }, () => {} );
  270. }
  271. }, () => {} );
  272. }, error => {
  273. if ( wiki.noWiki(error.message) ) {
  274. console.log( '- This wiki doesn\'t exist!' );
  275. }
  276. else {
  277. console.log( '- Error while following the links: ' + error );
  278. }
  279. return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
  280. json: {}
  281. } ).then( presponse => {
  282. if ( presponse.statusCode === 200 && presponse.body?.id ) {
  283. channel?.messages.fetch(presponse.body.id).then( msg => {
  284. allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
  285. }, () => {} );
  286. }
  287. }, () => {} );
  288. } );
  289. }, log_error );
  290. }
  291. module.exports = {
  292. name: 'inline',
  293. run: slash_inline
  294. };