inline.js 14 KB

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