discussion.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import htmlparser from 'htmlparser2';
  2. import { MessageEmbed, Util } from 'discord.js';
  3. import { got, htmlToDiscord, escapeFormatting } from '../../util/functions.js';
  4. import { createRequire } from 'module';
  5. const require = createRequire(import.meta.url);
  6. const {limit: {discussion: discussionLimit}} = require('../../util/default.json');
  7. /**
  8. * Processes discussion commands.
  9. * @param {import('../../util/i18n.js').default} lang - The user language.
  10. * @param {import('discord.js').Message} msg - The Discord message.
  11. * @param {import('../../util/wiki.js').default} wiki - The wiki for the page.
  12. * @param {String} title - The title of the discussion post.
  13. * @param {String} sitename - The sitename of the wiki.
  14. * @param {import('discord.js').MessageReaction} reaction - The reaction on the message.
  15. * @param {String} spoiler - If the response is in a spoiler.
  16. * @param {Boolean} noEmbed - If the response should be without an embed.
  17. */
  18. export default function fandom_discussion(lang, msg, wiki, title, sitename, reaction, spoiler, noEmbed) {
  19. var limit = discussionLimit[( patreonGuildsPrefix.has(msg.guildId) ? 'patreon' : 'default' )];
  20. if ( !title ) {
  21. var pagelink = wiki + 'f';
  22. if ( !msg.showEmbed() || noEmbed ) {
  23. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler );
  24. if ( reaction ) reaction.removeEmoji();
  25. return;
  26. }
  27. var embed = new MessageEmbed().setAuthor( {name: sitename} ).setTitle( lang.get('discussion.main') ).setURL( pagelink );
  28. got.get( wiki + 'f', {
  29. responseType: 'text'
  30. } ).then( descresponse => {
  31. var descbody = descresponse.body;
  32. if ( descresponse.statusCode !== 200 || !descbody ) {
  33. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  34. } else {
  35. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png');
  36. var parser = new htmlparser.Parser( {
  37. onopentag: (tagname, attribs) => {
  38. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  39. var description = escapeFormatting(attribs.content);
  40. if ( description.length > 1000 ) description = description.substring(0, 1000) + '\u2026';
  41. embed.setDescription( description );
  42. }
  43. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  44. thumbnail = attribs.content;
  45. }
  46. }
  47. } );
  48. parser.write( descbody );
  49. parser.end();
  50. embed.setThumbnail( thumbnail );
  51. }
  52. }, error => {
  53. console.log( '- Error while getting the description: ' + error );
  54. } ).finally( () => {
  55. msg.sendChannel( {content: spoiler + '<' + pagelink + '>' + spoiler, embeds: [embed]} );
  56. if ( reaction ) reaction.removeEmoji();
  57. } );
  58. }
  59. else if ( title.split(' ')[0].toLowerCase() === 'post' || title.split(' ')[0].toLowerCase() === lang.get('discussion.post') ) {
  60. title = title.split(' ').slice(1).join(' ');
  61. got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPosts&includeCounters=false&limit=' + limit + '&format=json&cache=' + Date.now(), {
  62. headers: {
  63. Accept: 'application/hal+json'
  64. }
  65. } ).then( response => {
  66. var body = response.body;
  67. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded['doc:posts'] ) {
  68. console.log( '- ' + response.statusCode + ': Error while getting the posts: ' + ( body && body.title ) );
  69. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  70. if ( reaction ) reaction.removeEmoji();
  71. }
  72. else if ( body._embedded['doc:posts'].length ) {
  73. var posts = body._embedded['doc:posts'];
  74. var embed = new MessageEmbed().setAuthor( {name: sitename} );
  75. if ( posts.some( post => post.id === title ) ) {
  76. discussion_send(lang, msg, wiki, posts.find( post => post.id === title ), embed, spoiler, noEmbed);
  77. if ( reaction ) reaction.removeEmoji();
  78. }
  79. else if ( /^\d+$/.test(title) ) {
  80. got.get( wiki + 'wikia.php?controller=DiscussionPost&method=getPost&postId=' + title + '&format=json&cache=' + Date.now(), {
  81. headers: {
  82. Accept: 'application/hal+json'
  83. }
  84. } ).then( presponse => {
  85. var pbody = presponse.body;
  86. if ( presponse.statusCode !== 200 || !pbody || pbody.id !== title ) {
  87. if ( pbody && pbody.title === 'The requested resource was not found.' ) {
  88. if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  89. discussion_send(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler, noEmbed);
  90. }
  91. else msg.reactEmoji('🤷');
  92. }
  93. else {
  94. console.log( '- ' + presponse.statusCode + ': Error while getting the post: ' + ( pbody && pbody.title ) );
  95. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  96. }
  97. if ( reaction ) reaction.removeEmoji();
  98. }
  99. else if ( pbody.title ) {
  100. discussion_send(lang, msg, wiki, pbody, embed, spoiler, noEmbed);
  101. if ( reaction ) reaction.removeEmoji();
  102. }
  103. else got.get( wiki + 'wikia.php?controller=DiscussionThread&method=getThread&threadId=' + pbody.threadId + '&format=json&cache=' + Date.now(), {
  104. headers: {
  105. Accept: 'application/hal+json'
  106. }
  107. } ).then( thresponse => {
  108. var thbody = thresponse.body;
  109. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== pbody.threadId ) {
  110. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  111. embed.setTitle( '~~' + pbody.threadId + '~~' );
  112. }
  113. else embed.setTitle( escapeFormatting(thbody.title) );
  114. }, error => {
  115. console.log( '- Error while getting the thread: ' + error );
  116. embed.setTitle( '~~' + pbody.threadId + '~~' );
  117. } ).finally( () => {
  118. discussion_send(lang, msg, wiki, pbody, embed, spoiler, noEmbed);
  119. if ( reaction ) reaction.removeEmoji();
  120. } );
  121. }, error => {
  122. console.log( '- Error while getting the post: ' + error );
  123. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  124. if ( reaction ) reaction.removeEmoji();
  125. } );
  126. }
  127. else if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  128. discussion_send(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler, noEmbed);
  129. if ( reaction ) reaction.removeEmoji();
  130. }
  131. else {
  132. msg.reactEmoji('🤷');
  133. if ( reaction ) reaction.removeEmoji();
  134. }
  135. }
  136. else {
  137. msg.reactEmoji('🤷');
  138. if ( reaction ) reaction.removeEmoji();
  139. }
  140. }, error => {
  141. console.log( '- Error while getting the posts: ' + error );
  142. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  143. if ( reaction ) reaction.removeEmoji();
  144. } );
  145. }
  146. else {
  147. got.get( wiki + 'wikia.php?controller=DiscussionThread&method=getThreads&sortKey=trending&limit=' + limit + '&format=json&cache=' + Date.now(), {
  148. headers: {
  149. Accept: 'application/hal+json'
  150. }
  151. } ).then( response => {
  152. var body = response.body;
  153. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded.threads ) {
  154. console.log( '- ' + response.statusCode + ': Error while getting the threads: ' + ( body && body.title ) );
  155. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  156. if ( reaction ) reaction.removeEmoji();
  157. }
  158. else if ( body._embedded.threads.length ) {
  159. var threads = body._embedded.threads;
  160. var embed = new MessageEmbed().setAuthor( {name: sitename} );
  161. if ( threads.some( thread => thread.id === title ) ) {
  162. discussion_send(lang, msg, wiki, threads.find( thread => thread.id === title ), embed, spoiler, noEmbed);
  163. if ( reaction ) reaction.removeEmoji();
  164. }
  165. else if ( threads.some( thread => thread.title === title ) ) {
  166. discussion_send(lang, msg, wiki, threads.find( thread => thread.title === title ), embed, spoiler, noEmbed);
  167. if ( reaction ) reaction.removeEmoji();
  168. }
  169. else if ( threads.some( thread => thread.title.toLowerCase() === title.toLowerCase() ) ) {
  170. discussion_send(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase() === title.toLowerCase() ), embed, spoiler, noEmbed);
  171. if ( reaction ) reaction.removeEmoji();
  172. }
  173. else if ( threads.some( thread => thread.title.includes( title ) ) ) {
  174. discussion_send(lang, msg, wiki, threads.find( thread => thread.title.includes( title ) ), embed, spoiler, noEmbed);
  175. if ( reaction ) reaction.removeEmoji();
  176. }
  177. else if ( threads.some( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ) ) {
  178. discussion_send(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler, noEmbed);
  179. if ( reaction ) reaction.removeEmoji();
  180. }
  181. else if ( /^\d+$/.test(title) ) {
  182. got.get( wiki + 'wikia.php?controller=DiscussionThread&method=getThread&threadId=' + title + '&format=json&cache=' + Date.now(), {
  183. headers: {
  184. Accept: 'application/hal+json'
  185. }
  186. } ).then( thresponse => {
  187. var thbody = thresponse.body;
  188. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== title ) {
  189. if ( thbody && thbody.status === 404 ) {
  190. if (threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  191. discussion_send(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler, noEmbed);
  192. }
  193. else msg.reactEmoji('🤷');
  194. }
  195. else {
  196. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  197. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  198. }
  199. }
  200. else discussion_send(lang, msg, wiki, thbody, embed, spoiler, noEmbed);
  201. }, error => {
  202. console.log( '- Error while getting the thread: ' + error );
  203. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  204. } ).finally( () => {
  205. if ( reaction ) reaction.removeEmoji();
  206. } );
  207. }
  208. else if ( threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  209. discussion_send(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler, noEmbed);
  210. if ( reaction ) reaction.removeEmoji();
  211. }
  212. else {
  213. msg.reactEmoji('🤷');
  214. if ( reaction ) reaction.removeEmoji();
  215. }
  216. }
  217. else {
  218. msg.reactEmoji('🤷');
  219. if ( reaction ) reaction.removeEmoji();
  220. }
  221. }, error => {
  222. console.log( '- Error while getting the threads: ' + error );
  223. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  224. if ( reaction ) reaction.removeEmoji();
  225. } );
  226. }
  227. }
  228. /**
  229. * Send discussion posts.
  230. * @param {import('../../util/i18n.js').default} lang - The user language.
  231. * @param {import('discord.js').Message} msg - The Discord message.
  232. * @param {import('../../util/wiki.js').default} wiki - The wiki for the page.
  233. * @param {Object} discussion - The discussion post.
  234. * @param {import('discord.js').MessageEmbed} embed - The embed for the page.
  235. * @param {String} spoiler - If the response is in a spoiler.
  236. * @param {Boolean} noEmbed - If the response should be without an embed.
  237. */
  238. function discussion_send(lang, msg, wiki, discussion, embed, spoiler, noEmbed) {
  239. if ( discussion.title ) {
  240. embed.setTitle( escapeFormatting(discussion.title) );
  241. var pagelink = wiki + 'f/p/' + ( discussion.threadId || discussion.id );
  242. }
  243. else {
  244. if ( discussion._embedded.thread ) embed.setTitle( escapeFormatting(discussion._embedded.thread[0].title) );
  245. var pagelink = wiki + 'f/p/' + discussion.threadId + '/r/' + discussion.id;
  246. }
  247. if ( !msg.showEmbed() || noEmbed ) msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler );
  248. embed.setURL( pagelink ).setFooter( {text: discussion.createdBy.name, iconURL: discussion.createdBy.avatarUrl} ).setTimestamp( discussion.creationDate.epochSecond * 1000 );
  249. var description = '';
  250. switch ( discussion.funnel ) {
  251. case 'IMAGE':
  252. embed.setImage( discussion._embedded.contentImages[0].url );
  253. break;
  254. case 'POLL':
  255. discussion.poll.answers.forEach( answer => embed.addField( escapeFormatting(answer.text), ( answer.image ? '[__' + lang.get('discussion.image') + '__](' + answer.image.url + ')\n' : '' ) + lang.get('discussion.votes', answer.votes.toLocaleString(lang.get('dateformat')), answer.votes, ( ( answer.votes / discussion.poll.totalVotes ) * 100 ).toFixed(1).toLocaleString(lang.get('dateformat'))), true ) );
  256. break;
  257. case 'QUIZ':
  258. description = escapeFormatting(discussion._embedded.quizzes[0].title);
  259. embed.setThumbnail( discussion._embedded.quizzes[0].image );
  260. break;
  261. default:
  262. if ( discussion.jsonModel ) {
  263. try {
  264. description = discussion_formatting(JSON.parse(discussion.jsonModel)).replace( /(?:\*\*\*\*|(?<!\\)\_\_)/g, '' ).replace( /{@wiki}/g, wiki );
  265. if ( discussion._embedded.contentImages.length ) {
  266. if ( description.trim().endsWith( '{@0}' ) ) {
  267. embed.setImage( discussion._embedded.contentImages[0].url );
  268. description = description.replace( '{@0}', '' ).trim();
  269. }
  270. else {
  271. description = description.replace( /\{\@(\d+)\}/g, (match, n) => {
  272. if ( n >= discussion._embedded.contentImages.length ) return '';
  273. else return '[__' + lang.get('discussion.image') + '__](' + discussion._embedded.contentImages[n].url + ')';
  274. } );
  275. embed.setThumbnail( discussion._embedded.contentImages[0].url );
  276. }
  277. }
  278. else embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  279. }
  280. catch ( jsonerror ) {
  281. console.log( '- Error while getting the formatting: ' + jsonerror );
  282. description = escapeFormatting(discussion.rawContent);
  283. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  284. }
  285. }
  286. else if ( discussion.renderedContent ) {
  287. description = htmlToDiscord(discussion.renderedContent, pagelink);
  288. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  289. }
  290. else {
  291. description = escapeFormatting(discussion.rawContent);
  292. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  293. }
  294. }
  295. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  296. embed.setDescription( description );
  297. if ( discussion.tags?.length ) {
  298. embed.addField( lang.get('discussion.tags'), Util.splitMessage( discussion.tags.map( tag => '[' + escapeFormatting(tag.articleTitle) + '](' + wiki.toLink(tag.articleTitle, '', '', true) + ')' ).join(', '), {char:', ',maxLength:1000} )[0], false );
  299. }
  300. msg.sendChannel( {content: spoiler + '<' + pagelink + '>' + spoiler, embeds: [embed]} );
  301. }
  302. /**
  303. * Format discussion content
  304. * @param {Object} jsonModel - The content of the discussion post.
  305. * @returns {String}
  306. */
  307. function discussion_formatting(jsonModel) {
  308. var description = '';
  309. switch ( jsonModel.type ) {
  310. case 'doc':
  311. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  312. break;
  313. case 'paragraph':
  314. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  315. description += '\n';
  316. break;
  317. case 'openGraph':
  318. if ( !jsonModel.attrs.wasAddedWithInlineLink ) description += jsonModel.attrs.url + '\n';
  319. break;
  320. case 'text':
  321. var prepend = '';
  322. var append = '';
  323. if ( jsonModel.marks ) {
  324. jsonModel.marks.forEach( mark => {
  325. switch ( mark.type ) {
  326. case 'mention':
  327. prepend += '[';
  328. append = ']({@wiki}f/u/' + mark.attrs.userId + ')' + append;
  329. break;
  330. case 'link':
  331. prepend += '[';
  332. append = '](' + mark.attrs.href + ')' + append;
  333. break;
  334. case 'strong':
  335. prepend += '**';
  336. append = '**' + append;
  337. break;
  338. case 'em':
  339. prepend += '_';
  340. append = '_' + append;
  341. break;
  342. }
  343. } );
  344. }
  345. description += prepend + escapeFormatting(jsonModel.text) + append;
  346. break;
  347. case 'image':
  348. if ( jsonModel.attrs.id !== null ) description += '{@' + jsonModel.attrs.id + '}\n';
  349. break;
  350. case 'code_block':
  351. description += '```\n';
  352. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  353. description += '\n```\n';
  354. break;
  355. case 'bulletList':
  356. jsonModel.content.forEach( listItem => {
  357. description += '\t• ';
  358. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  359. } );
  360. break;
  361. case 'orderedList':
  362. var n = 1;
  363. jsonModel.content.forEach( listItem => {
  364. description += '\t' + n + '. ';
  365. n++;
  366. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  367. } );
  368. break;
  369. }
  370. return description;
  371. }