main.js 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407
  1. require('dotenv').config();
  2. const util = require('util');
  3. util.inspect.defaultOptions = {compact:false,breakLength:Infinity};
  4. const Discord = require('discord.js');
  5. const DBL = require('dblapi.js');
  6. var request = require('request');
  7. var htmlparser = require('htmlparser2');
  8. var client = new Discord.Client( {
  9. messageCacheLifetime: 600,
  10. messageSweepInterval: 6000,
  11. disableEveryone: true,
  12. disabledEvents: ["TYPING_START"]
  13. } );
  14. const dbl = new DBL(process.env.dbltoken);
  15. var i18n = require('./i18n/allLangs.json');
  16. Object.keys(i18n.allLangs[1]).forEach( lang => i18n[lang] = require('./i18n/' + lang + '.json') );
  17. var minecraft = require('./minecraft.json');
  18. var multiManager = require('./wiki_manager.json');
  19. var pause = {};
  20. var stop = false;
  21. var isDebug = ( process.argv[2] === 'debug' );
  22. const access = {'PRIVATE-TOKEN': process.env.access};
  23. const defaultPermissions = new Discord.Permissions(268954688).toArray();
  24. const timeoptions = {
  25. year: 'numeric',
  26. month: 'short',
  27. day: 'numeric',
  28. hour: '2-digit',
  29. minute: '2-digit',
  30. timeZone: 'UTC',
  31. timeZoneName: 'short'
  32. }
  33. var ready = {
  34. settings: true,
  35. allSites: true
  36. }
  37. const defaultSettings = {
  38. "default": {
  39. "lang": "en",
  40. "wiki": "https://help.gamepedia.com/"
  41. }
  42. }
  43. var settings = defaultSettings;
  44. function getSettings() {
  45. ready.settings = true;
  46. request( {
  47. uri: process.env.read + process.env.file + process.env.raw,
  48. headers: access,
  49. json: true
  50. }, function( error, response, body ) {
  51. if ( error || !response || response.statusCode !== 200 || !body || body.message || body.error ) {
  52. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the settings: ' + ( error || body && ( body.message || body.error ) ) );
  53. ready.settings = false;
  54. }
  55. else {
  56. console.log( '- Settings successfully loaded.' );
  57. if ( body.default ) settings = JSON.parse(JSON.stringify(body));
  58. else if ( settings === defaultSettings ) settings = JSON.parse(JSON.stringify(defaultSettings));
  59. }
  60. setStatus();
  61. } );
  62. }
  63. function setStatus(hardreset) {
  64. if ( settings === defaultSettings ) client.user.setStatus('invisible').catch(log_error);
  65. else if ( hardreset === true ) client.user.setStatus('invisible').then(setStatus, log_error);
  66. else {
  67. client.user.setStatus('online').catch(log_error);
  68. client.user.setActivity( process.env.prefix + ' help' ).catch(log_error);
  69. }
  70. }
  71. var allSites = [];
  72. function getAllSites(callback, ...args) {
  73. ready.allSites = true;
  74. request( {
  75. uri: 'https://help.gamepedia.com/api.php?action=allsites&formatversion=2&do=getSiteStats&filter=wikis|wiki_domain,wiki_display_name,wiki_image,wiki_description,wiki_managers,official_wiki,created&format=json',
  76. json: true
  77. }, function( error, response, body ) {
  78. if ( error || !response || response.statusCode !== 200 || !body || body.status !== 'okay' || !body.data || !body.data.wikis ) {
  79. console.log( '- ' + ( response && response.statusCode ) + ': Error while gettings all sites: ' + ( error || body && body.error && body.error.info ) );
  80. ready.allSites = false;
  81. }
  82. else {
  83. console.log( '- Sites successfully loaded.' );
  84. allSites = JSON.parse(JSON.stringify(body.data.wikis.filter( site => /^[a-z\d-]{1,50}\.gamepedia\.com$/.test(site.wiki_domain) )));
  85. allSites.filter( site => site.wiki_domain in multiManager ).forEach( function(site) {
  86. site.wiki_managers = multiManager[site.wiki_domain].concat(site.wiki_managers).filter( (value, index, self) => self.indexOf(value) === index );
  87. } );
  88. }
  89. if ( callback ) callback(...args);
  90. } );
  91. }
  92. client.on( 'ready', () => {
  93. console.log( '\n- Successfully logged in as ' + client.user.username + '!' );
  94. getSettings();
  95. getAllSites();
  96. if ( !isDebug ) client.setInterval( () => {
  97. console.log( '- Current server count: ' + client.guilds.size );
  98. dbl.postStats(client.guilds.size).catch( () => {} );
  99. request.post( {
  100. uri: 'https://discord.bots.gg/api/v1/bots/' + client.user.id + '/stats',
  101. headers: {Authorization: process.env.dbggtoken},
  102. body: {guildCount: client.guilds.size},
  103. json: true
  104. }, () => {} );
  105. }, 10800000 ).unref();
  106. } );
  107. var cmdmap = {
  108. help: cmd_help,
  109. test: cmd_test,
  110. pause: cmd_pause,
  111. invite: cmd_invite,
  112. say: cmd_multiline,
  113. delete: cmd_multiline,
  114. poll: cmd_multiline,
  115. voice: cmd_voice,
  116. settings: cmd_settings,
  117. info: cmd_info
  118. }
  119. var multilinecmdmap = {
  120. say: cmd_say,
  121. delete: cmd_delete,
  122. poll: cmd_umfrage
  123. }
  124. var ownercmdmap = {
  125. stop: cmd_stop,
  126. pause: cmd_pause,
  127. eval: cmd_eval,
  128. get: cmd_get
  129. }
  130. var pausecmdmap = {
  131. help: cmd_help,
  132. test: cmd_test,
  133. pause: cmd_pause,
  134. say: cmd_multiline,
  135. delete: cmd_multiline,
  136. settings: cmd_settings
  137. }
  138. var minecraftcmdmap = {
  139. command: cmd_befehl2,
  140. bug: cmd_bug
  141. }
  142. function cmd_settings(lang, msg, args, line) {
  143. if ( msg.isAdmin() ) {
  144. if ( msg.guild.id in settings ) {
  145. var text = lang.settings.current.replaceSave( '%1$s', '- `' + process.env.prefix + ' settings lang`' ).replaceSave( '%2$s', settings[msg.guild.id].wiki + ' - `' + process.env.prefix + ' settings wiki`' ) + ' - `' + process.env.prefix + ' settings channel`\n';
  146. if ( settings[msg.guild.id].channels ) {
  147. Object.keys(settings[msg.guild.id].channels).forEach( function(channel) {
  148. text += '<#' + channel + '>: <' + settings[msg.guild.id].channels[channel] + '>\n';
  149. } );
  150. } else text += lang.settings.nochannels;
  151. } else {
  152. var text = lang.settings.missing.replaceSave( '%1$s', '`' + process.env.prefix + ' settings lang`' ).replaceSave( '%2$s', '`' + process.env.prefix + ' settings wiki`' );
  153. }
  154. if ( args.length ) {
  155. if ( args[0] ) args[0] = args[0].toLowerCase();
  156. args[1] = args.slice(1).join(' ').toLowerCase().trim().replace( /^<(.*)>$/, '$1' );
  157. if ( args[1] && ( args[0] === 'wiki' || args[0] === 'channel' ) ) {
  158. var regex = args[1].match( /^(?:(?:https?:)?\/\/)?([a-z\d-]{1,50})\.gamepedia\.com(?:\/|$)/ );
  159. }
  160. var langs = '\n' + lang.settings.langhelp.replaceSave( '%s', process.env.prefix + ' settings lang' ) + ' `' + Object.values(i18n.allLangs[1]).join(', ') + '`';
  161. var wikis = '\n' + lang.settings.wikihelp.replaceSave( '%s', process.env.prefix + ' settings wiki' );
  162. var channels = '\n' + lang.settings.wikihelp.replaceSave( '%s', process.env.prefix + ' settings channel' );
  163. var nolangs = lang.settings.langinvalid + langs;
  164. var nowikis = lang.settings.wikiinvalid + wikis;
  165. var nochannels = lang.settings.wikiinvalid + channels;
  166. if ( msg.guild.id in settings ) {
  167. var current = args[0] + ( line === 'changed' ? line : '' );
  168. if ( args[0] === 'lang' ) {
  169. if ( args[1] ) {
  170. if ( args[1] in i18n.allLangs[0] ) edit_settings(lang, msg, 'lang', i18n.allLangs[0][args[1]]);
  171. else msg.replyMsg( nolangs, {}, true );
  172. } else msg.replyMsg( lang.settings[current] + langs, {}, true );
  173. } else if ( args[0] === 'wiki' ) {
  174. if ( args[1] ) {
  175. if ( regex !== null ) edit_settings(lang, msg, 'wiki', 'https://' + regex[1] + '.gamepedia.com/');
  176. else find_wikis(lang, msg, 'wiki', args[1].split(' '), nowikis);
  177. } else msg.replyMsg( lang.settings[current] + ' ' + settings[msg.guild.id].wiki + wikis, {}, true );
  178. } else if ( args[0] === 'channel' ) {
  179. if ( args[1] ) {
  180. if ( regex !== null ) edit_settings(lang, msg, 'channel', 'https://' + regex[1] + '.gamepedia.com/');
  181. else find_wikis(lang, msg, 'channel', args[1].split(' '), nochannels);
  182. } else if ( settings[msg.guild.id].channels && msg.channel.id in settings[msg.guild.id].channels ) {
  183. msg.replyMsg( lang.settings[current] + ' ' + settings[msg.guild.id].channels[msg.channel.id] + channels, {}, true );
  184. } else msg.replyMsg( lang.settings[current] + ' ' + settings[msg.guild.id].wiki + channels, {}, true );
  185. } else msg.replyMsg( text, {}, true );
  186. } else {
  187. if ( args[0] === 'lang' ) {
  188. if ( args[1] ) {
  189. if ( args[1] in i18n.allLangs[0] ) edit_settings(lang, msg, 'lang', i18n.allLangs[0][args[1]]);
  190. else msg.replyMsg( nolangs, {}, true );
  191. } else msg.replyMsg( lang.settings.lang + langs, {}, true );
  192. } else if ( args[0] === 'wiki' || args[0] === 'channel' ) {
  193. if ( args[1] ) {
  194. if ( regex !== null ) edit_settings(lang, msg, 'wiki', 'https://' + regex[1] + '.gamepedia.com/');
  195. else find_wikis(lang, msg, 'wiki', args[1].split(' '), nowikis);
  196. } else msg.replyMsg( lang.settings.wikimissing + wikis, {}, true );
  197. } else msg.replyMsg( text, {split:true}, true );
  198. }
  199. } else msg.replyMsg( text, {split:true}, true );
  200. } else {
  201. msg.reactEmoji('❌');
  202. }
  203. }
  204. function find_wikis(lang, msg, key, value, text) {
  205. if ( value.length === 2 && value[1] === '--force' ) {
  206. msg.reactEmoji('⏳', true).then( function( reaction ) {
  207. request( {
  208. uri: value[0] + 'api.php?action=query&format=json',
  209. json: true
  210. }, function( error, response, body ) {
  211. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !( body instanceof Object ) ) {
  212. console.log( '- ' + ( response && response.statusCode ) + ': Error while reaching the wiki: ' + ( error || body && body.error && body.error.info ) );
  213. msg.reactEmoji('nowiki', true);
  214. if ( reaction ) reaction.removeEmoji();
  215. }
  216. else edit_settings(lang, msg, key, value[0]);
  217. } );
  218. } );
  219. } else if ( allSites.some( site => site.wiki_domain === value.join('') + '.gamepedia.com' ) ) {
  220. edit_settings(lang, msg, key, 'https://' + value.join('') + '.gamepedia.com/');
  221. } else {
  222. var sites = allSites.filter( site => site.wiki_display_name.toLowerCase().includes( value.join(' ') ) );
  223. if ( 0 < sites.length && sites.length < 21 ) {
  224. text += '\n\n' + lang.settings.foundwikis + '\n' + sites.map( site => site.wiki_display_name + ': `' + site.wiki_domain + '`' ).join('\n');
  225. }
  226. msg.replyMsg( text, {split:true}, true );
  227. }
  228. }
  229. function edit_settings(lang, msg, key, value) {
  230. msg.reactEmoji('⏳', true).then( function( reaction ) {
  231. if ( settings === defaultSettings ) {
  232. console.log( '- Error while getting current settings.' );
  233. msg.replyMsg( lang.settings.save_failed, {}, true );
  234. if ( reaction ) reaction.removeEmoji();
  235. }
  236. else {
  237. var temp_settings = JSON.parse(JSON.stringify(settings));
  238. var save = false;
  239. if ( !( msg.guild.id in temp_settings ) ) {
  240. temp_settings[msg.guild.id] = Object.assign({}, settings.default);
  241. save = true;
  242. }
  243. if ( key === 'channel' ) {
  244. if ( !temp_settings[msg.guild.id].channels ) temp_settings[msg.guild.id].channels = {};
  245. if ( temp_settings[msg.guild.id].channels[msg.channel.id] !== value ) {
  246. temp_settings[msg.guild.id].channels[msg.channel.id] = value;
  247. save = true;
  248. }
  249. } else if ( temp_settings[msg.guild.id][key] !== value ) {
  250. temp_settings[msg.guild.id][key] = value;
  251. save = true;
  252. }
  253. Object.keys(temp_settings).forEach( function(guild) {
  254. if ( !client.guilds.has(guild) && guild !== 'default' ) {
  255. delete temp_settings[guild];
  256. save = true;
  257. } else {
  258. var channels = temp_settings[guild].channels;
  259. if ( channels ) {
  260. Object.keys(channels).forEach( function(channel) {
  261. if ( channels[channel] === temp_settings[guild].wiki || !client.guilds.get(guild).channels.has(channel) ) {
  262. delete channels[channel];
  263. save = true;
  264. }
  265. } );
  266. if ( !Object.keys(channels).length ) {
  267. delete temp_settings[guild].channels;
  268. save = true;
  269. }
  270. }
  271. }
  272. } );
  273. if ( save ) request.post( {
  274. uri: process.env.save,
  275. headers: access,
  276. body: {
  277. branch: 'master',
  278. commit_message: client.user.username + ': Settings updated.',
  279. actions: [
  280. {
  281. action: 'update',
  282. file_path: process.env.file,
  283. content: JSON.stringify( temp_settings, null, '\t' )
  284. }
  285. ]
  286. },
  287. json: true
  288. }, function( error, response, body ) {
  289. if ( error || !response || response.statusCode !== 201 || !body || body.error ) {
  290. console.log( '- ' + ( response && response.statusCode ) + ': Error while editing the settings: ' + ( error || body && ( body.message || body.error ) ) );
  291. msg.replyMsg( lang.settings.save_failed, {}, true );
  292. }
  293. else {
  294. settings = JSON.parse(JSON.stringify(temp_settings));
  295. if ( key === 'lang' ) lang = i18n[value];
  296. cmd_settings(lang, msg, [key], 'changed');
  297. console.log( '- Settings successfully updated.' );
  298. }
  299. if ( reaction ) reaction.removeEmoji();
  300. } );
  301. else {
  302. cmd_settings(lang, msg, [key], 'changed');
  303. if ( reaction ) reaction.removeEmoji();
  304. }
  305. }
  306. } );
  307. }
  308. function cmd_info(lang, msg, args, line) {
  309. if ( args.join('') ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  310. else {
  311. msg.sendChannel( lang.disclaimer.replaceSave( '%s', ( msg.channel.type === 'text' && msg.guild.members.get(process.env.owner) || '*MarkusRost*' ) ) + '\n<https://www.patreon.com/WikiBot>' );
  312. cmd_helpserver(lang, msg);
  313. cmd_invite(lang, msg, args, line);
  314. }
  315. }
  316. function cmd_helpserver(lang, msg) {
  317. msg.sendChannel( lang.helpserver + '\n' + process.env.invite );
  318. }
  319. function cmd_invite(lang, msg, args, line) {
  320. if ( args.join('') ) {
  321. cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  322. } else {
  323. client.generateInvite(defaultPermissions).then( invite => msg.sendChannel( lang.invite.bot + '\n<' + invite + '>' ), log_error );
  324. }
  325. }
  326. function cmd_help(lang, msg, args, line) {
  327. if ( msg.channel.type === 'text' && pause[msg.guild.id] && ( args.join('') || !msg.isAdmin() ) ) return;
  328. if ( msg.isAdmin() && !( msg.guild.id in settings ) && settings !== defaultSettings ) {
  329. cmd_settings(lang, msg, [], line);
  330. cmd_helpserver(lang, msg);
  331. }
  332. var cmds = lang.help.list;
  333. var isMinecraft = ( msg.channel.getWiki() === minecraft[lang.lang].link );
  334. var cmdintro = '🔹 `' + process.env.prefix + ' ';
  335. if ( args.join('') ) {
  336. if ( args.join(' ').isMention(msg.guild) ) cmd_helpserver(lang, msg);
  337. else if ( args[0].toLowerCase() === 'admin' ) {
  338. if ( msg.channel.type !== 'text' || msg.isAdmin() ) {
  339. var cmdlist = lang.help.admin + '\n' + cmds.filter( cmd => cmd.admin && !cmd.hide ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  340. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  341. msg.sendChannel( cmdlist, {split:true} );
  342. }
  343. else {
  344. msg.replyMsg( lang.help.noadmin );
  345. }
  346. }
  347. else if ( args[0].toLowerCase() === 'minecraft' ) {
  348. var cmdlist = '<' + minecraft[lang.lang].link + '>\n' + cmds.filter( cmd => cmd.minecraft && !cmd.hide ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  349. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  350. msg.sendChannel( cmdlist, {split:true} );
  351. }
  352. else {
  353. var cmdlist = cmds.filter( cmd => cmd.cmd.split(' ')[0] === args[0].toLowerCase() && !cmd.unsearchable && ( msg.channel.type !== 'text' || !cmd.admin || msg.isAdmin() ) && ( !cmd.minecraft || isMinecraft ) ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  354. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  355. if ( cmdlist === '' ) msg.reactEmoji('❓');
  356. else msg.sendChannel( cmdlist, {split:true} );
  357. }
  358. }
  359. else if ( msg.isAdmin() && pause[msg.guild.id] ) {
  360. var cmdlist = lang.help.pause + '\n' + cmds.filter( cmd => cmd.pause ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  361. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  362. msg.sendChannel( cmdlist, {split:true}, true );
  363. }
  364. else {
  365. var cmdlist = lang.help.all + '\n' + cmds.filter( cmd => !cmd.hide && !cmd.admin && ( !cmd.minecraft || isMinecraft ) ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n') + '\n\n🔸 ' + lang.help.footer;
  366. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  367. msg.sendChannel( cmdlist, {split:true} );
  368. }
  369. }
  370. function cmd_say(lang, msg, args, line) {
  371. args = args.toEmojis();
  372. var text = args.join(' ');
  373. if ( args[0] === 'alarm' ) text = '🚨 **' + args.slice(1).join(' ') + '** 🚨';
  374. var imgs = [];
  375. if ( msg.uploadFiles() ) imgs = msg.attachments.map( function(img) {
  376. return {attachment:img.url,name:img.filename};
  377. } );
  378. if ( msg.isOwner() ) {
  379. try {
  380. text = eval( '`' + text + '`' );
  381. } catch ( error ) {
  382. log_error(error);
  383. }
  384. }
  385. if ( text || imgs.length ) {
  386. msg.channel.send( text, {disableEveryone:!msg.member.hasPermission(['MENTION_EVERYONE']),files:imgs} ).then( () => msg.deleteMsg(), error => {
  387. log_error(error);
  388. msg.reactEmoji('error', true);
  389. } );
  390. } else {
  391. args[0] = line.split(' ')[1];
  392. cmd_help(lang, msg, args, line);
  393. }
  394. }
  395. function cmd_umfrage(lang, msg, args, line) {
  396. var imgs = [];
  397. if ( msg.uploadFiles() ) imgs = msg.attachments.map( function(img) {
  398. return {attachment:img.url,name:img.filename};
  399. } );
  400. if ( args.length || imgs.length ) {
  401. var text = args.join(' ').split('\n');
  402. args = text.shift().split(' ');
  403. if ( text.length ) args.push('\n' + text.join('\n'));
  404. var reactions = [];
  405. args = args.toEmojis();
  406. for ( var i = 0; ( i < args.length || imgs.length ); i++ ) {
  407. var reaction = args[i];
  408. var custom = /^<a?:/;
  409. var pattern = /^[\u0000-\u1FFF]{1,4}$/;
  410. if ( !custom.test(reaction) && ( reaction.length > 4 || pattern.test(reaction) ) ) {
  411. cmd_sendumfrage(lang, msg, args.slice(i).join(' ').replace( /^\n| (\n)/, '$1' ), reactions, imgs);
  412. break;
  413. } else if ( reaction !== '' ) {
  414. if ( custom.test(reaction) ) {
  415. reaction = reaction.substring(reaction.lastIndexOf(':') + 1, reaction.length - 1);
  416. }
  417. reactions[i] = reaction;
  418. if ( i === args.length - 1 ) {
  419. cmd_sendumfrage(lang, msg, args.slice(i + 1).join(' ').replace( /^\n| (\n)/, '$1' ), reactions, imgs);
  420. break;
  421. }
  422. }
  423. }
  424. } else {
  425. args[0] = line.split(' ')[1];
  426. cmd_help(lang, msg, args, line);
  427. }
  428. }
  429. function cmd_sendumfrage(lang, msg, text, reactions, imgs) {
  430. msg.channel.send( lang.poll.title + text, {disableEveryone:!msg.member.hasPermission(['MENTION_EVERYONE']),files:imgs} ).then( poll => {
  431. msg.deleteMsg();
  432. if ( reactions.length ) {
  433. reactions.forEach( function(entry) {
  434. poll.react(entry).catch( error => {
  435. log_error(error);
  436. poll.reactEmoji('error');
  437. } );
  438. } );
  439. } else {
  440. poll.reactEmoji('support');
  441. poll.reactEmoji('oppose');
  442. }
  443. }, error => {
  444. log_error(error);
  445. msg.reactEmoji('error');
  446. } );
  447. }
  448. function cmd_test(lang, msg, args, line) {
  449. if ( args.join('') ) {
  450. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  451. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  452. var text = lang.test.text[Math.floor(Math.random() * lang.test.random)] || lang.test.default;
  453. console.log( '- Test: Fully functioning!' );
  454. var now = Date.now();
  455. msg.replyMsg( text ).then( edit => {
  456. var then = Date.now();
  457. var embed = new Discord.RichEmbed().setTitle( lang.test.time ).addField( 'Discord', ( then - now ) + 'ms' );
  458. now = Date.now();
  459. request( {
  460. uri: msg.channel.getWiki() + 'api.php?action=query&format=json',
  461. json: true
  462. }, function( error, response, body ) {
  463. then = Date.now();
  464. if ( body && body.warnings ) log_warn(body.warnings);
  465. var ping = ( then - now ) + 'ms';
  466. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !( body instanceof Object ) ) {
  467. if ( response && ( response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' || response.statusCode === 410 ) ) {
  468. console.log( '- This wiki doesn\'t exist!' );
  469. ping += ' <:unknown_wiki:505887262077353984>';
  470. }
  471. else {
  472. console.log( '- ' + ( response && response.statusCode ) + ': Error while reaching the wiki: ' + ( error || body && body.error && body.error.info ) );
  473. ping += ' <:error:505887261200613376>';
  474. }
  475. }
  476. embed.addField( msg.channel.getWiki(), ping );
  477. if ( edit ) edit.edit( edit.content, embed ).catch(log_error);
  478. } );
  479. } );
  480. } else {
  481. console.log( '- Test: Paused!' );
  482. msg.replyMsg( lang.test.pause, {}, true );
  483. }
  484. }
  485. async function cmd_eval(lang, msg, args, line) {
  486. try {
  487. var text = util.inspect( await eval( args.join(' ') ) );
  488. } catch ( error ) {
  489. var text = error.toString();
  490. }
  491. if ( isDebug ) console.log( '--- EVAL START ---\n' + text + '\n--- EVAL END ---' );
  492. if ( text.length > 2000 ) msg.reactEmoji('✅', true);
  493. else msg.sendChannel( '```js\n' + text + '\n```', {split:{prepend:'```js\n',append:'\n```'}}, true );
  494. }
  495. async function cmd_stop(lang, msg, args, line) {
  496. if ( args.join(' ').split('\n')[0].isMention(msg.guild) ) {
  497. await msg.replyMsg( 'I\'ll destroy myself now!', {}, true );
  498. await client.destroy();
  499. console.log( '- I\'m now shutting down!' );
  500. setTimeout( async () => {
  501. console.log( '- I need to long to close, terminating!' );
  502. process.exit(1);
  503. }, 1000 ).unref();
  504. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  505. cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  506. }
  507. }
  508. function cmd_pause(lang, msg, args, line) {
  509. if ( msg.channel.type === 'text' && args.join(' ').split('\n')[0].isMention(msg.guild) && ( msg.isAdmin() || msg.isOwner() ) ) {
  510. if ( pause[msg.guild.id] ) {
  511. delete pause[msg.guild.id];
  512. console.log( '- Pause ended.' );
  513. msg.replyMsg( lang.pause.off, {}, true );
  514. } else {
  515. msg.replyMsg( lang.pause.on, {}, true );
  516. console.log( '- Pause started.' );
  517. pause[msg.guild.id] = true;
  518. }
  519. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  520. cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  521. }
  522. }
  523. function cmd_delete(lang, msg, args, line) {
  524. if ( msg.channel.memberPermissions(msg.member).has('MANAGE_MESSAGES') ) {
  525. if ( /^\d+$/.test(args[0]) && parseInt(args[0], 10) + 1 > 0 ) {
  526. if ( parseInt(args[0], 10) > 99 ) {
  527. msg.replyMsg( lang.delete.big.replace( '%s', '`99`' ), {}, true );
  528. }
  529. else {
  530. msg.channel.bulkDelete(parseInt(args[0], 10) + 1, true).then( messages => {
  531. msg.reply( lang.delete.success.replace( '%s', messages.size - 1 ) ).then( antwort => antwort.deleteMsg(5000), log_error );
  532. console.log( '- The last ' + ( messages.size - 1 ) + ' messages in #' + msg.channel.name + ' were deleted by @' + msg.member.displayName + '!' );
  533. }, log_error );
  534. }
  535. }
  536. else {
  537. msg.replyMsg( lang.delete.invalid, {}, true );
  538. }
  539. }
  540. else {
  541. msg.reactEmoji('❌');
  542. }
  543. }
  544. function cmd_link(lang, msg, title, wiki = msg.channel.getWiki(), cmd = ' ') {
  545. if ( cmd === ' ' && msg.isAdmin() && !( msg.guild.id in settings ) && settings !== defaultSettings ) {
  546. cmd_settings(lang, msg, [], '');
  547. }
  548. if ( /^\|\|(?:(?!\|\|).)+\|\|$/.test(title) ) {
  549. title = title.substring( 2, title.length - 2);
  550. var spoiler = '||';
  551. }
  552. msg.reactEmoji('⏳').then( reaction => check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler) );
  553. }
  554. function check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler = '', querystring = '', fragment = '', selfcall = 0) {
  555. if ( title.includes( '#' ) ) {
  556. fragment = title.split('#').slice(1).join('#');
  557. title = title.split('#')[0];
  558. }
  559. if ( /\?\w+=/.test(title) ) {
  560. var querystart = title.search(/\?\w+=/);
  561. querystring = title.substring(querystart + 1) + ( querystring ? '&' + querystring : '' );
  562. title = title.substring(0, querystart);
  563. }
  564. var linksuffix = ( querystring ? '?' + querystring.toTitle() : '' ) + ( fragment ? '#' + fragment.toSection() : '' );
  565. if ( title.length > 300 ) {
  566. title = title.substring(0, 300);
  567. msg.reactEmoji('⚠');
  568. }
  569. var invoke = title.split(' ')[0].toLowerCase();
  570. var aliasInvoke = ( lang.aliase[invoke] || invoke );
  571. var args = title.split(' ').slice(1);
  572. var mclang = minecraft[lang.lang];
  573. var mcaliasInvoke = ( mclang.aliase[invoke] || invoke );
  574. if ( !msg.notminecraft && wiki === mclang.link && ( mcaliasInvoke in minecraftcmdmap || invoke.startsWith( '/' ) ) ) {
  575. if ( mcaliasInvoke in minecraftcmdmap ) minecraftcmdmap[mcaliasInvoke](lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler);
  576. else cmd_befehl(lang, mclang, msg, invoke.substring(1), args, title, cmd, querystring, fragment, reaction, spoiler);
  577. }
  578. else if ( aliasInvoke === 'random' && !args.join('') && !linksuffix ) cmd_random(lang, msg, wiki, reaction, spoiler);
  579. else if ( aliasInvoke === 'overview' && !args.join('') && !linksuffix ) {
  580. if ( allSites.some( site => 'https://' + site.wiki_domain + '/' === wiki ) ) cmd_overview(lang, msg, wiki, reaction, spoiler);
  581. else getAllSites(cmd_overview, lang, msg, wiki, reaction, spoiler);
  582. }
  583. else if ( aliasInvoke === 'page' ) {
  584. msg.sendChannel( spoiler + '<' + wiki.toLink() + args.join('_').toTitle() + linksuffix + '>' + spoiler );
  585. if ( reaction ) reaction.removeEmoji();
  586. }
  587. else if ( aliasInvoke === 'search' ) {
  588. linksuffix = ( linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  589. msg.sendChannel( spoiler + '<' + wiki.toLink() + 'Special:Search?search=' + args.join(' ').toSearch() + linksuffix + '>' + spoiler );
  590. if ( reaction ) reaction.removeEmoji();
  591. }
  592. else if ( aliasInvoke === 'diff' && args.join('') && !linksuffix ) cmd_diff(lang, msg, args, wiki, reaction, spoiler);
  593. else {
  594. var noRedirect = ( /(?:^|&)redirect=no(?:&|$)/.test(querystring) || /(?:^|&)action=(?!view(?:&|$))/.test(querystring) );
  595. request( {
  596. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general|namespaces|specialpagealiases&iwurl=true' + ( noRedirect ? '' : '&redirects=true' ) + '&prop=pageimages|categoryinfo|pageprops|extracts&piprop=original|name&ppprop=description|displaytitle&exsentences=10&exintro=true&explaintext=true&titles=' + encodeURIComponent( title ) + '&format=json',
  597. json: true
  598. }, function( error, response, body ) {
  599. if ( body && body.warnings ) log_warn(body.warnings);
  600. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  601. if ( response && ( response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' || response.statusCode === 410 ) ) {
  602. console.log( '- This wiki doesn\'t exist!' );
  603. msg.reactEmoji('nowiki');
  604. }
  605. else {
  606. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  607. msg.sendChannelError( spoiler + '<' + wiki.toLink() + ( linksuffix || !title ? title.toTitle() + linksuffix : 'Special:Search?search=' + title.toSearch() ) + '>' + spoiler );
  608. }
  609. if ( reaction ) reaction.removeEmoji();
  610. }
  611. else {
  612. if ( body.query.pages ) {
  613. var querypages = Object.values(body.query.pages);
  614. var querypage = querypages[0];
  615. if ( body.query.redirects && body.query.redirects[0].from.split(':')[0] === body.query.namespaces['-1']['*'] && body.query.specialpagealiases.filter( sp => ['Mypage','Mytalk','MyLanguage'].includes( sp.realname ) ).map( sp => sp.aliases[0] ).includes( body.query.redirects[0].from.split(':').slice(1).join(':').split('/')[0].replace( / /g, '_' ) ) ) {
  616. querypage.title = body.query.redirects[0].from;
  617. delete body.query.redirects[0].tofragment;
  618. delete querypage.missing;
  619. querypage.ns = -1;
  620. querypage.special = '';
  621. }
  622. if ( querypages.length !== 1 ) querypage = {
  623. title: title,
  624. invalidreason: 'The requested page title contains invalid characters: "|".',
  625. invalid: ''
  626. }
  627. var contribs = body.query.namespaces['-1']['*'] + ':' + body.query.specialpagealiases.find( sp => sp.realname === 'Contributions' ).aliases[0] + '/';
  628. if ( ( querypage.ns === 2 || querypage.ns === 202 ) && ( !querypage.title.includes( '/' ) || /^[^:]+:(?:(?:\d{1,3}\.){3}\d{1,3}\/\d{2}|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}\/\d{2,3})$/.test(querypage.title) ) ) {
  629. var userparts = querypage.title.split(':');
  630. querypage.noRedirect = noRedirect;
  631. cmd_user(lang, msg, userparts[0].toTitle() + ':', userparts.slice(1).join(':'), wiki, linksuffix, querypage, contribs.toTitle(), reaction, spoiler);
  632. }
  633. else if ( querypage.ns === -1 && querypage.title.startsWith( contribs ) && querypage.title.length > contribs.length ) {
  634. var username = querypage.title.split('/').slice(1).join('/');
  635. request( {
  636. uri: wiki + 'api.php?action=query&titles=User:' + encodeURIComponent( username ) + '&format=json',
  637. json: true
  638. }, function( uerror, uresponse, ubody ) {
  639. if ( uerror || !uresponse || uresponse.statusCode !== 200 || !ubody || ubody.batchcomplete === undefined || !ubody.query ) {
  640. console.log( '- ' + ( uresponse && uresponse.statusCode ) + ': Error while getting the user: ' + ( uerror || ubody && ubody.error && ubody.error.info ) );
  641. msg.sendChannelError( spoiler + '<' + wiki.toLink() + ( contribs + username ).toTitle() + linksuffix + '>' + spoiler );
  642. if ( reaction ) reaction.removeEmoji();
  643. }
  644. else {
  645. querypage = Object.values(ubody.query.pages)[0];
  646. if ( querypage.ns === 2 ) {
  647. username = querypage.title.split(':').slice(1).join(':');
  648. querypage.title = contribs + username;
  649. delete querypage.missing;
  650. querypage.ns = -1;
  651. querypage.special = '';
  652. querypage.noRedirect = noRedirect;
  653. cmd_user(lang, msg, contribs.toTitle(), username, wiki, linksuffix, querypage, contribs.toTitle(), reaction, spoiler);
  654. }
  655. else {
  656. msg.reactEmoji('error');
  657. if ( reaction ) reaction.removeEmoji();
  658. }
  659. }
  660. } );
  661. }
  662. else if ( ( querypage.missing !== undefined && querypage.known === undefined && !( noRedirect || querypage.categoryinfo ) ) || querypage.invalid !== undefined ) {
  663. request( {
  664. uri: wiki + 'api.php?action=query&prop=pageimages|categoryinfo|pageprops|extracts&piprop=original|name&ppprop=description|displaytitle&exsentences=10&exintro=true&explaintext=true&generator=search&gsrnamespace=4|12|14|' + Object.values(body.query.namespaces).filter( ns => ns.content !== undefined ).map( ns => ns.id ).join('|') + '&gsrlimit=1&gsrsearch=' + encodeURIComponent( title ) + '&format=json',
  665. json: true
  666. }, function( srerror, srresponse, srbody ) {
  667. if ( srbody && srbody.warnings ) log_warn(srbody.warnings);
  668. if ( srerror || !srresponse || srresponse.statusCode !== 200 || !srbody || srbody.batchcomplete === undefined ) {
  669. console.log( '- ' + ( srresponse && srresponse.statusCode ) + ': Error while getting the search results: ' + ( srerror || srbody && srbody.error && srbody.error.info ) );
  670. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Search?search=' + title.toSearch() + '>' + spoiler );
  671. }
  672. else {
  673. if ( !srbody.query ) {
  674. msg.reactEmoji('🤷');
  675. }
  676. else {
  677. querypage = Object.values(srbody.query.pages)[0];
  678. var pagelink = wiki.toLink() + querypage.title.toTitle() + linksuffix;
  679. var text = '';
  680. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  681. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  682. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  683. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  684. embed.setTitle( displaytitle );
  685. }
  686. if ( querypage.pageprops && querypage.pageprops.description ) {
  687. var description = htmlToPlain( querypage.pageprops.description );
  688. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  689. embed.setDescription( description );
  690. }
  691. else if ( querypage.extract ) {
  692. var extract = querypage.extract.escapeFormatting();
  693. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  694. embed.setDescription( extract );
  695. }
  696. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  697. var pageimage = querypage.original.source;
  698. if ( querypage.ns === 6 ) {
  699. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.pageimage.toLowerCase()) ) embed.setImage( pageimage );
  700. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.pageimage}] );
  701. } else embed.setThumbnail( pageimage );
  702. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  703. if ( title.replace( /\-/g, ' ' ).toTitle().toLowerCase() === querypage.title.replace( /\-/g, ' ' ).toTitle().toLowerCase() ) {
  704. text = '';
  705. }
  706. else if ( !srbody.continue ) {
  707. text = '\n' + lang.search.infopage.replaceSave( '%s', '`' + process.env.prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' );
  708. }
  709. else {
  710. text = '\n' + lang.search.infosearch.replaceSave( '%1$s', '`' + process.env.prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' ).replaceSave( '%2$s', '`' + process.env.prefix + cmd + lang.search.search + ' ' + title + linksuffix + '`' );
  711. }
  712. if ( querypage.categoryinfo ) {
  713. var langCat = lang.search.category;
  714. var category = [langCat.content];
  715. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  716. if ( querypage.categoryinfo.pages > 0 ) {
  717. var pages = querypage.categoryinfo.pages;
  718. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  719. }
  720. if ( querypage.categoryinfo.files > 0 ) {
  721. var files = querypage.categoryinfo.files;
  722. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  723. }
  724. if ( querypage.categoryinfo.subcats > 0 ) {
  725. var subcats = querypage.categoryinfo.subcats;
  726. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  727. }
  728. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  729. else text += '\n\n' + category.join('\n');
  730. }
  731. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, embed );
  732. }
  733. }
  734. if ( reaction ) reaction.removeEmoji();
  735. } );
  736. }
  737. else if ( querypage.ns === -1 ) {
  738. var pagelink = wiki.toLink() + querypage.title.toTitle() + linksuffix;
  739. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink ).setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  740. var specialpage = body.query.specialpagealiases.find( sp => body.query.namespaces['-1']['*'] + ':' + sp.aliases[0].replace( /\_/g, ' ' ) === querypage.title.split('/')[0] ).realname.toLowerCase();
  741. special_page(lang, msg, querypage.title, specialpage, embed, wiki, reaction, spoiler);
  742. }
  743. else {
  744. var pagelink = wiki.toLink() + querypage.title.toTitle() + ( querystring ? '?' + querystring.toTitle() : '' ) + ( fragment ? '#' + fragment.toSection() : ( body.query.redirects && body.query.redirects[0].tofragment ? '#' + body.query.redirects[0].tofragment.toSection() : '' ) );
  745. var text = '';
  746. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  747. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  748. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  749. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  750. embed.setTitle( displaytitle );
  751. }
  752. if ( querypage.pageprops && querypage.pageprops.description ) {
  753. var description = htmlToPlain( querypage.pageprops.description );
  754. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  755. embed.setDescription( description );
  756. }
  757. else if ( querypage.extract ) {
  758. var extract = querypage.extract.escapeFormatting();
  759. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  760. embed.setDescription( extract );
  761. }
  762. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  763. var pageimage = querypage.original.source;
  764. if ( querypage.ns === 6 ) {
  765. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.pageimage.toLowerCase()) ) embed.setImage( pageimage );
  766. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.pageimage}] );
  767. } else embed.setThumbnail( pageimage );
  768. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  769. if ( querypage.categoryinfo ) {
  770. var langCat = lang.search.category;
  771. var category = [langCat.content];
  772. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  773. if ( querypage.categoryinfo.pages > 0 ) {
  774. var pages = querypage.categoryinfo.pages;
  775. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  776. }
  777. if ( querypage.categoryinfo.files > 0 ) {
  778. var files = querypage.categoryinfo.files;
  779. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  780. }
  781. if ( querypage.categoryinfo.subcats > 0 ) {
  782. var subcats = querypage.categoryinfo.subcats;
  783. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  784. }
  785. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  786. else text += '\n\n' + category.join('\n');
  787. }
  788. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, embed );
  789. if ( reaction ) reaction.removeEmoji();
  790. }
  791. }
  792. else if ( body.query.interwiki ) {
  793. var inter = body.query.interwiki[0];
  794. var intertitle = inter.title.substring(inter.iw.length + 1);
  795. var regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.gamepedia\.com(?:\/|$)/ );
  796. if ( regex !== null && selfcall < 5 ) {
  797. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  798. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  799. selfcall++;
  800. check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '.gamepedia.com/', ' !' + regex[1] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  801. } else {
  802. if ( reaction ) reaction.removeEmoji();
  803. console.log( '- Aborted, paused.' );
  804. }
  805. } else {
  806. regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50}\.(?:wikipedia|mediawiki|wiktionary|wikimedia|wikibooks|wikisource|wikidata|wikiversity|wikiquote|wikinews|wikivoyage)\.org)(?:\/wiki\/|\/?$)/ );
  807. if ( regex !== null && selfcall < 5 ) {
  808. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  809. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  810. selfcall++;
  811. check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/w/', cmd + inter.iw + ':', reaction, spoiler, querystring, fragment, selfcall);
  812. } else {
  813. if ( reaction ) reaction.removeEmoji();
  814. console.log( '- Aborted, paused.' );
  815. }
  816. } else {
  817. if ( fragment ) fragment = '#' + fragment.toSection();
  818. if ( inter.url.includes( '#' ) ) {
  819. if ( !fragment ) fragment = '#' + inter.url.split('#').slice(1).join('#');
  820. inter.url = inter.url.split('#')[0];
  821. }
  822. if ( querystring ) inter.url += ( inter.url.includes( '?' ) ? '&' : '?' ) + querystring.toTitle();
  823. msg.sendChannel( spoiler + ' ' + inter.url.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler ).then( message => {
  824. if ( message && selfcall === 5 ) message.reactEmoji('⚠');
  825. } );
  826. if ( reaction ) reaction.removeEmoji();
  827. }
  828. }
  829. }
  830. else if ( body.query.redirects ) {
  831. var pagelink = wiki.toLink() + body.query.redirects[0].to.toTitle() + ( querystring ? '?' + querystring.toTitle() : '' ) + ( fragment ? '#' + fragment.toSection() : ( body.query.redirects[0].tofragment ? '#' + body.query.redirects[0].tofragment.toSection() : '' ) );
  832. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.redirects[0].to.escapeFormatting() ).setURL( pagelink ).setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  833. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  834. if ( reaction ) reaction.removeEmoji();;
  835. }
  836. else {
  837. var pagelink = wiki.toLink() + body.query.general.mainpage.toTitle() + linksuffix;
  838. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.general.mainpage.escapeFormatting() ).setURL( pagelink ).setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  839. request( {
  840. uri: wiki + 'api.php?action=query' + ( noRedirect ? '' : '&redirects=true' ) + '&prop=pageprops|extracts&ppprop=description|displaytitle&exsentences=10&exintro=true&explaintext=true&titles=' + encodeURIComponent( body.query.general.mainpage ) + '&format=json',
  841. json: true
  842. }, function( mperror, mpresponse, mpbody ) {
  843. if ( mpbody && mpbody.warnings ) log_warn(body.warnings);
  844. if ( mperror || !mpresponse || mpresponse.statusCode !== 200 || !mpbody || mpbody.batchcomplete === undefined || !mpbody.query ) {
  845. console.log( '- ' + ( mpresponse && mpresponse.statusCode ) + ': Error while getting the main page: ' + ( mperror || mpbody && mpbody.error && mpbody.error.info ) );
  846. } else {
  847. querypage = Object.values(mpbody.query.pages)[0];
  848. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  849. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  850. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  851. embed.setTitle( displaytitle );
  852. }
  853. if ( querypage.pageprops && querypage.pageprops.description ) {
  854. var description = htmlToPlain( querypage.pageprops.description );
  855. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  856. embed.setDescription( description );
  857. }
  858. else if ( querypage.extract ) {
  859. var extract = querypage.extract.escapeFormatting();
  860. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  861. embed.setDescription( extract );
  862. }
  863. }
  864. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  865. if ( reaction ) reaction.removeEmoji();
  866. } );
  867. }
  868. }
  869. } );
  870. }
  871. }
  872. function special_page(lang, msg, title, specialpage, embed, wiki, reaction, spoiler) {
  873. var overwrites = {
  874. randompage: (lang, msg, args, embed, wiki, reaction, spoiler) => cmd_random(lang, msg, wiki, reaction, spoiler),
  875. diff: (lang, msg, args, embed, wiki, reaction, spoiler) => cmd_diff(lang, msg, args, wiki, reaction, spoiler, embed),
  876. statistics: (lang, msg, args, embed, wiki, reaction, spoiler) => cmd_overview(lang, msg, wiki, reaction, spoiler)
  877. }
  878. if ( specialpage in overwrites ) {
  879. var args = title.split('/').slice(1,3);
  880. overwrites[specialpage](lang, msg, args, embed, wiki, reaction, spoiler);
  881. return;
  882. }
  883. request( {
  884. uri: wiki + 'api.php?action=query&meta=allmessages&amenableparser=true&amtitle=' + encodeURIComponent( title ) + '&ammessages=' + encodeURIComponent( specialpage ) + '-summary&format=json',
  885. json: true
  886. }, function( error, response, body ) {
  887. if ( body && body.warnings ) log_warn(body.warnings);
  888. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined ) {
  889. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the special page: ' + ( error || body && body.error && body.error.info ) );
  890. }
  891. else {
  892. if ( body.query.allmessages[0]['*'] ) {
  893. var description = body.query.allmessages[0]['*'].toPlaintext();
  894. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  895. embed.setDescription( description );
  896. }
  897. }
  898. msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, embed );
  899. if ( reaction ) reaction.removeEmoji();
  900. } );
  901. }
  902. function cmd_user(lang, msg, namespace, username, wiki, linksuffix, querypage, contribs, reaction, spoiler) {
  903. if ( /^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  904. request( {
  905. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=blocks&bkprop=user|by|timestamp|expiry|reason&bkip=' + encodeURIComponent( username ) + '&format=json',
  906. json: true
  907. }, function( error, response, body ) {
  908. if ( body && body.warnings ) log_warn(body.warnings);
  909. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.blocks ) {
  910. if ( response && ( response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' || response.statusCode === 410 ) ) {
  911. console.log( '- This wiki doesn\'t exist!' );
  912. msg.reactEmoji('nowiki');
  913. }
  914. else if ( body && body.error && ( body.error.code === 'param_ip' || body.error.code === 'cidrtoobroad' ) ) {
  915. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('error');
  916. else {
  917. var pagelink = wiki.toLink() + querypage.title.toTitle() + linksuffix;
  918. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  919. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  920. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  921. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  922. embed.setTitle( displaytitle );
  923. }
  924. if ( querypage.pageprops && querypage.pageprops.description ) {
  925. var description = htmlToPlain( querypage.pageprops.description );
  926. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  927. embed.setDescription( description );
  928. }
  929. else if ( querypage.extract ) {
  930. var extract = querypage.extract.escapeFormatting();
  931. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  932. embed.setDescription( extract );
  933. }
  934. if ( querypage.pageimage && querypage.original ) {
  935. var pageimage = querypage.original.source;
  936. embed.setThumbnail( pageimage );
  937. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  938. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  939. }
  940. }
  941. else {
  942. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  943. msg.sendChannelError( spoiler + '<' + wiki.toLink() + ( querypage.noRedirect ? namespace : contribs ) + username.toTitle() + linksuffix + '>' + spoiler );
  944. }
  945. if ( reaction ) reaction.removeEmoji();
  946. }
  947. else {
  948. if ( !querypage.noRedirect || ( querypage.missing === undefined && querypage.ns !== -1 ) ) namespace = contribs;
  949. var blocks = body.query.blocks.map( function(block) {
  950. var isBlocked = false;
  951. var blockedtimestamp = new Date(block.timestamp).toLocaleString(lang.dateformat, timeoptions);
  952. var blockexpiry = block.expiry;
  953. if ( blockexpiry === 'infinity' ) {
  954. blockexpiry = lang.user.block.until_infinity;
  955. isBlocked = true;
  956. } else if ( blockexpiry ) {
  957. if ( Date.parse(blockexpiry) > Date.now() ) isBlocked = true;
  958. blockexpiry = new Date(blockexpiry).toLocaleString(lang.dateformat, timeoptions);
  959. }
  960. if ( isBlocked ) return [lang.user.block.header.replaceSave( '%s', block.user ).escapeFormatting(), lang.user.block[( block.reason ? 'text' : 'noreason' )].replaceSave( '%1$s', blockedtimestamp ).replaceSave( '%2$s', blockexpiry ).replaceSave( '%3$s', '[[User:' + block.by + '|' + block.by + ']]' ).replaceSave( '%4$s', block.reason )];
  961. } ).filter( block => block !== undefined );
  962. if ( username.includes( '/' ) ) {
  963. var rangeprefix = username;
  964. if ( username.includes( ':' ) ) {
  965. var range = parseInt(username.replace( /^.+\/(\d{2,3})$/, '$1' ), 10);
  966. if ( range === 128 ) username = username.replace( /^(.+)\/\d{2,3}$/, '$1' );
  967. else if ( range >= 112 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){7}).+$/, '$1' );
  968. else if ( range >= 96 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){6}).+$/, '$1' );
  969. else if ( range >= 80 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){5}).+$/, '$1' );
  970. else if ( range >= 64 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){4}).+$/, '$1' );
  971. else if ( range >= 48 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){3}).+$/, '$1' );
  972. else if ( range >= 32 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){2}).+$/, '$1' );
  973. else if ( range >= 19 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){1}).+$/, '$1' );
  974. }
  975. else {
  976. var range = parseInt(username.substring(username.length - 2), 10);
  977. if ( range === 32 ) username = username.replace( /^(.+)\/\d{2}$/, '$1' );
  978. else if ( range >= 24 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){3}).+$/, '$1' );
  979. else if ( range >= 16 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){2}).+$/, '$1' );
  980. }
  981. }
  982. request( {
  983. uri: wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=50' + ( username.includes( '/' ) ? '&ucuserprefix=' + encodeURIComponent( rangeprefix ) : '&ucuser=' + encodeURIComponent( username ) ) + '&format=json',
  984. json: true
  985. }, function( ucerror, ucresponse, ucbody ) {
  986. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  987. if ( ucbody && ucbody.warnings ) log_warn(ucbody.warnings);
  988. if ( ucerror || !ucresponse || ucresponse.statusCode !== 200 || !ucbody || ucbody.batchcomplete === undefined || !ucbody.query || !ucbody.query.usercontribs ) {
  989. if ( ucbody && ucbody.error && ucbody.error.code === 'baduser_ucuser' ) {
  990. msg.reactEmoji('error');
  991. }
  992. else {
  993. console.log( '- ' + ( ucresponse && ucresponse.statusCode ) + ': Error while getting the search results: ' + ( ucerror || ucbody && ucbody.error && ucbody.error.info ) );
  994. msg.sendChannelError( spoiler + '<' + wiki.toLink() + namespace + username.toTitle() + linksuffix + '>' + spoiler );
  995. }
  996. }
  997. else {
  998. var editcount = [lang.user.info.editcount, ( username.includes( '/' ) && ( ( username.includes( ':' ) && range % 16 ) || range % 8 ) ? '~' : '' ) + ucbody.query.usercontribs.length + ( ucbody.continue ? '+' : '' )];
  999. var pagelink = wiki.toLink() + namespace + username.toTitle() + linksuffix;
  1000. if ( msg.showEmbed() ) {
  1001. var text = '<' + pagelink + '>';
  1002. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( username ).setURL( pagelink ).addField( editcount[0], '[' + editcount[1] + '](' + wiki.toLink() + contribs + username.toTitle(true) + ')' );
  1003. if ( blocks.length ) blocks.forEach( block => embed.addField( block[0], block[1].toMarkdown(wiki) ) );
  1004. }
  1005. else {
  1006. var embed = {};
  1007. var text = '<' + pagelink + '>\n\n' + editcount.join(' ');
  1008. if ( blocks.length ) blocks.forEach( block => text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext() );
  1009. }
  1010. msg.sendChannel( spoiler + text + spoiler, embed );
  1011. }
  1012. if ( reaction ) reaction.removeEmoji();
  1013. } );
  1014. }
  1015. } );
  1016. } else {
  1017. request( {
  1018. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=users&usprop=blockinfo|groups|editcount|registration|gender&ususers=' + encodeURIComponent( username ) + '&format=json',
  1019. json: true
  1020. }, function( error, response, body ) {
  1021. if ( body && body.warnings ) log_warn(body.warnings);
  1022. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.users[0] ) {
  1023. if ( response && ( response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' || response.statusCode === 410 ) ) {
  1024. console.log( '- This wiki doesn\'t exist!' );
  1025. msg.reactEmoji('nowiki');
  1026. }
  1027. else {
  1028. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1029. msg.sendChannelError( spoiler + '<' + wiki.toLink() + namespace + username.toTitle() + linksuffix + '>' + spoiler );
  1030. }
  1031. }
  1032. else {
  1033. if ( body.query.users[0].missing !== undefined || body.query.users[0].invalid !== undefined ) {
  1034. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('🤷');
  1035. else {
  1036. var pagelink = wiki.toLink() + querypage.title.toTitle() + linksuffix;
  1037. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1038. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  1039. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  1040. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  1041. embed.setTitle( displaytitle );
  1042. }
  1043. if ( querypage.pageprops && querypage.pageprops.description ) {
  1044. var description = htmlToPlain( querypage.pageprops.description );
  1045. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1046. embed.setDescription( description );
  1047. }
  1048. else if ( querypage.extract ) {
  1049. var extract = querypage.extract.escapeFormatting();
  1050. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1051. embed.setDescription( extract );
  1052. }
  1053. if ( querypage.pageimage && querypage.original ) {
  1054. var pageimage = querypage.original.source;
  1055. embed.setThumbnail( pageimage );
  1056. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  1057. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  1058. }
  1059. if ( reaction ) reaction.removeEmoji();
  1060. }
  1061. else {
  1062. username = body.query.users[0].name;
  1063. var gender = [lang.user.info.gender];
  1064. switch (body.query.users[0].gender) {
  1065. case 'male':
  1066. gender.push(lang.user.gender.male);
  1067. break;
  1068. case 'female':
  1069. gender.push(lang.user.gender.female);
  1070. break;
  1071. default:
  1072. gender.push(lang.user.gender.unknown);
  1073. }
  1074. var registration = [lang.user.info.registration, new Date(body.query.users[0].registration).toLocaleString(lang.dateformat, timeoptions)];
  1075. var editcount = [lang.user.info.editcount, body.query.users[0].editcount];
  1076. var groups = body.query.users[0].groups;
  1077. var group = [lang.user.info.group];
  1078. for ( var i = 0; i < lang.user.groups.length; i++ ) {
  1079. if ( groups.includes( lang.user.groups[i][0] ) ) {
  1080. var thisSite = allSites.find( site => site.wiki_domain === body.query.general.servername );
  1081. if ( lang.user.groups[i][0] === 'hydra_staff' && thisSite && thisSite.wiki_managers.includes( username ) ) {
  1082. group.push(lang.user.manager);
  1083. }
  1084. else group.push(lang.user.groups[i][1]);
  1085. break;
  1086. }
  1087. }
  1088. var isBlocked = false;
  1089. var blockedtimestamp = new Date(body.query.users[0].blockedtimestamp).toLocaleString(lang.dateformat, timeoptions);
  1090. var blockexpiry = body.query.users[0].blockexpiry;
  1091. if ( blockexpiry === 'infinity' ) {
  1092. blockexpiry = lang.user.block.until_infinity;
  1093. isBlocked = true;
  1094. } else if ( blockexpiry ) {
  1095. var blockexpirydate = blockexpiry.replace( /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2,3})/, '$1-$2-$3T$4:$5:$6Z' );
  1096. blockexpiry = new Date(blockexpirydate).toLocaleString(lang.dateformat, timeoptions);
  1097. if ( Date.parse(blockexpirydate) > Date.now() ) isBlocked = true;
  1098. }
  1099. var blockedby = '[[User:' + body.query.users[0].blockedby + '|' + body.query.users[0].blockedby + ']]';
  1100. var blockreason = body.query.users[0].blockreason;
  1101. var block = [lang.user.block.header.replaceSave( '%s', username ).escapeFormatting(), lang.user.block[( blockreason ? 'text' : 'noreason' )].replaceSave( '%1$s', blockedtimestamp ).replaceSave( '%2$s', blockexpiry ).replaceSave( '%3$s', blockedby ).replaceSave( '%4$s', blockreason )];
  1102. var pagelink = wiki.toLink() + namespace + username.toTitle() + linksuffix;
  1103. if ( msg.showEmbed() ) {
  1104. var text = '<' + pagelink + '>';
  1105. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( username.escapeFormatting() ).setURL( pagelink ).addField( editcount[0], '[' + editcount[1] + '](' + wiki.toLink() + contribs + username.toTitle(true) + ')', true ).addField( group[0], group[1], true ).addField( gender[0], gender[1], true ).addField( registration[0], registration[1], true );
  1106. }
  1107. else {
  1108. var embed = {};
  1109. var text = '<' + pagelink + '>\n\n' + gender.join(' ') + '\n' + registration.join(' ') + '\n' + editcount.join(' ') + '\n' + group.join(' ');
  1110. }
  1111. if ( wiki.endsWith( '.gamepedia.com/' ) ) request( {
  1112. uri: wiki + 'api.php?action=profile&do=getPublicProfile&user_name=' + encodeURIComponent( username ) + '&format=json',
  1113. json: true
  1114. }, function( perror, presponse, pbody ) {
  1115. if ( perror || !presponse || presponse.statusCode !== 200 || !pbody || pbody.error || pbody.errormsg || !pbody.profile ) {
  1116. console.log( '- ' + ( presponse && presponse.statusCode ) + ': Error while getting the user profile: ' + ( perror || pbody && ( pbody.error && pbody.error.info || pbody.errormsg ) ) );
  1117. }
  1118. else if ( pbody.profile['link-discord'] ) {
  1119. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.find( member => {
  1120. return member.user.tag === pbody.profile['link-discord'].replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  1121. } );
  1122. var discordname = [lang.user.info.discord,pbody.profile['link-discord'].escapeFormatting()];
  1123. if ( discordmember ) {
  1124. if ( msg.showEmbed() ) discordname[1] = discordmember.toString();
  1125. else if ( discordmember.nickname ) discordname[1] += ' (' + discordmember.nickname.escapeFormatting() + ')';
  1126. }
  1127. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  1128. else text += '\n' + discordname.join(' ');
  1129. }
  1130. if ( isBlocked ) {
  1131. if ( msg.showEmbed() ) embed.addField( block[0], block[1].toMarkdown(wiki) );
  1132. else text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  1133. }
  1134. msg.sendChannel( spoiler + text + spoiler, embed );
  1135. if ( reaction ) reaction.removeEmoji();
  1136. } );
  1137. else {
  1138. if ( isBlocked ) {
  1139. if ( msg.showEmbed() ) embed.addField( block[0], block[1].toMarkdown(wiki) );
  1140. else text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  1141. }
  1142. msg.sendChannel( spoiler + text + spoiler, embed );
  1143. if ( reaction ) reaction.removeEmoji();
  1144. }
  1145. }
  1146. }
  1147. } );
  1148. }
  1149. }
  1150. function cmd_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  1151. if ( args[0] ) {
  1152. var error = false;
  1153. var title = '';
  1154. var revision = 0;
  1155. var diff = 0;
  1156. var relative = 'prev';
  1157. if ( /^\d+$/.test(args[0]) ) {
  1158. revision = parseInt(args[0], 10);
  1159. if ( args[1] ) {
  1160. if ( /^\d+$/.test(args[1]) ) {
  1161. diff = parseInt(args[1], 10);
  1162. }
  1163. else if ( args[1] === 'prev' || args[1] === 'next' || args[1] === 'cur' ) {
  1164. relative = args[1];
  1165. }
  1166. else error = true;
  1167. }
  1168. }
  1169. else if ( args[0] === 'prev' || args[0] === 'next' || args[0] === 'cur' ) {
  1170. relative = args[0];
  1171. if ( args[1] ) {
  1172. if ( /^\d+$/.test(args[1]) ) {
  1173. revision = parseInt(args[1], 10);
  1174. }
  1175. else error = true;
  1176. }
  1177. else error = true;
  1178. }
  1179. else title = args.join(' ');
  1180. if ( error ) {
  1181. msg.reactEmoji('error');
  1182. if ( reaction ) reaction.removeEmoji();
  1183. }
  1184. else if ( diff ) {
  1185. cmd_diffsend(lang, msg, [diff, revision], wiki, reaction, spoiler);
  1186. }
  1187. else {
  1188. request( {
  1189. uri: wiki + 'api.php?action=compare&prop=ids|diff' + ( title ? '&fromtitle=' + encodeURIComponent( title ) : '&fromrev=' + revision ) + '&torelative=' + relative + '&format=json',
  1190. json: true
  1191. }, function( error, response, body ) {
  1192. if ( body && body.warnings ) log_warn(body.warnings);
  1193. if ( error || !response || response.statusCode !== 200 || !body || !body.compare ) {
  1194. var noerror = false;
  1195. if ( body && body.error ) {
  1196. switch ( body.error.code ) {
  1197. case 'nosuchrevid':
  1198. noerror = true;
  1199. break;
  1200. case 'missingtitle':
  1201. noerror = true;
  1202. break;
  1203. case 'invalidtitle':
  1204. noerror = true;
  1205. break;
  1206. case 'missingcontent':
  1207. noerror = true;
  1208. break;
  1209. default:
  1210. noerror = false;
  1211. }
  1212. }
  1213. if ( response && ( response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' || response.statusCode === 410 ) ) {
  1214. console.log( '- This wiki doesn\'t exist!' );
  1215. msg.reactEmoji('nowiki');
  1216. }
  1217. else if ( noerror ) {
  1218. msg.replyMsg( lang.diff.badrev );
  1219. }
  1220. else {
  1221. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1222. msg.sendChannelError( spoiler + '<' + wiki.toLink() + title.toTitle() + '?diff=' + relative + ( title ? '' : '&oldid=' + revision ) + '>' + spoiler );
  1223. }
  1224. if ( reaction ) reaction.removeEmoji();
  1225. }
  1226. else {
  1227. if ( body.compare.fromarchive !== undefined || body.compare.toarchive !== undefined ) {
  1228. msg.reactEmoji('error');
  1229. if ( reaction ) reaction.removeEmoji();
  1230. } else {
  1231. var argids = [];
  1232. var ids = body.compare;
  1233. if ( ids.fromrevid && !ids.torevid ) argids = [ids.fromrevid];
  1234. else if ( !ids.fromrevid && ids.torevid ) argids = [ids.torevid];
  1235. else {
  1236. argids = [ids.torevid, ids.fromrevid];
  1237. var compare = ['', ''];
  1238. if ( ids.fromtexthidden === undefined && ids.totexthidden === undefined && ids['*'] !== undefined ) {
  1239. var more = '\n__' + lang.diff.info.more + '__';
  1240. var current_tag = '';
  1241. var small_prev_ins = '';
  1242. var small_prev_del = '';
  1243. var ins_length = more.length;
  1244. var del_length = more.length;
  1245. var added = false;
  1246. var parser = new htmlparser.Parser( {
  1247. onopentag: (tagname, attribs) => {
  1248. if ( tagname === 'ins' || tagname == 'del' ) {
  1249. current_tag = tagname;
  1250. }
  1251. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  1252. current_tag = tagname+'a';
  1253. }
  1254. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  1255. current_tag = tagname+"d";
  1256. }
  1257. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  1258. added = true;
  1259. }
  1260. },
  1261. ontext: (htmltext) => {
  1262. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  1263. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  1264. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  1265. else small_prev_ins += more;
  1266. }
  1267. if ( current_tag === 'del' && del_length <= 1000 ) {
  1268. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  1269. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  1270. else small_prev_del += more;
  1271. }
  1272. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  1273. ins_length += htmltext.escapeFormatting().length;
  1274. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  1275. else small_prev_ins += more;
  1276. }
  1277. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  1278. del_length += htmltext.escapeFormatting().length;
  1279. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  1280. else small_prev_del += more;
  1281. }
  1282. if ( added ) {
  1283. if ( htmltext === '+' && ins_length <= 1000 ) {
  1284. ins_length++;
  1285. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  1286. else small_prev_ins += more;
  1287. }
  1288. if ( htmltext === '−' && del_length <= 1000 ) {
  1289. del_length++;
  1290. if ( del_length <= 1000 ) small_prev_del += '\n';
  1291. else small_prev_del += more;
  1292. }
  1293. added = false;
  1294. }
  1295. },
  1296. onclosetag: (tagname) => {
  1297. if ( tagname === 'ins' ) {
  1298. current_tag = 'afterins';
  1299. } else if ( tagname === 'del' ) {
  1300. current_tag = 'afterdel';
  1301. } else {
  1302. current_tag = '';
  1303. }
  1304. }
  1305. }, {decodeEntities:true} );
  1306. parser.write( ids['*'] );
  1307. parser.end();
  1308. if ( small_prev_del.length ) {
  1309. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  1310. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  1311. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  1312. }
  1313. if ( small_prev_ins.length ) {
  1314. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  1315. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  1316. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  1317. }
  1318. }
  1319. else if ( ids.fromtexthidden !== undefined ) compare[0] = '__' + lang.diff.hidden + '__';
  1320. else if ( ids.totexthidden !== undefined ) compare[1] = '__' + lang.diff.hidden + '__';
  1321. }
  1322. cmd_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  1323. }
  1324. }
  1325. } );
  1326. }
  1327. }
  1328. else {
  1329. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, embed );
  1330. else msg.reactEmoji('error');
  1331. if ( reaction ) reaction.removeEmoji();
  1332. }
  1333. }
  1334. function cmd_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  1335. request( {
  1336. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=tags&tglimit=500&tgprop=displayname&prop=revisions&rvprop=ids|timestamp|flags|user|size|comment|tags' + ( args.length === 1 || args[0] === args[1] ? '|content' : '' ) + '&revids=' + args.join('|') + '&format=json',
  1337. json: true
  1338. }, function( error, response, body ) {
  1339. if ( body && body.warnings ) log_warn(body.warnings);
  1340. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  1341. if ( response && ( response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' || response.statusCode === 410 ) ) {
  1342. console.log( '- This wiki doesn\'t exist!' );
  1343. msg.reactEmoji('nowiki');
  1344. }
  1345. else {
  1346. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1347. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0] + '>' + spoiler );
  1348. }
  1349. if ( reaction ) reaction.removeEmoji();
  1350. }
  1351. else {
  1352. if ( body.query.badrevids ) {
  1353. msg.replyMsg( lang.diff.badrev );
  1354. if ( reaction ) reaction.removeEmoji();
  1355. }
  1356. else if ( body.query.pages && !body.query.pages['-1'] ) {
  1357. var pages = Object.values(body.query.pages);
  1358. if ( pages.length !== 1 ) {
  1359. msg.sendChannel( spoiler + '<' + wiki.toLink() + 'Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0] + '>' + spoiler );
  1360. if ( reaction ) reaction.removeEmoji();
  1361. }
  1362. else {
  1363. var title = pages[0].title;
  1364. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  1365. var diff = revisions[0].revid;
  1366. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  1367. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  1368. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  1369. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  1370. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  1371. var comment = [lang.diff.info.comment, ( revisions[0].commenthidden !== undefined ? lang.diff.hidden : ( revisions[0].comment ? revisions[0].comment.toFormatting(msg.showEmbed(), wiki, title) : lang.diff.nocomment ) )];
  1372. if ( revisions[0].tags.length ) var tags = [lang.diff.info.tags, body.query.tags.filter( tag => revisions[0].tags.includes( tag.name ) ).map( tag => tag.displayname ).join(', ')];
  1373. var pagelink = wiki.toLink() + title.toTitle() + '?diff=' + diff + '&oldid=' + oldid;
  1374. if ( msg.showEmbed() ) {
  1375. var text = '<' + pagelink + '>';
  1376. var editorlink = '[' + editor[1] + '](' + wiki.toLink() + 'User:' + editor[1].toTitle(true) + ')';
  1377. if ( revisions[0].anon !== undefined ) {
  1378. editorlink = '[' + editor[1] + '](' + wiki.toLink() + 'Special:Contributions/' + editor[1].toTitle(true) + ')';
  1379. }
  1380. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  1381. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( ( title + '?diff=' + diff + '&oldid=' + oldid ).escapeFormatting() ).setURL( pagelink ).addField( editor[0], editorlink, true ).addField( size[0], size[1], true ).addField( comment[0], comment[1] ).setFooter( timestamp[1] );
  1382. if ( tags ) {
  1383. var taglink = '';
  1384. var tagtext = '';
  1385. var tagparser = new htmlparser.Parser( {
  1386. onopentag: (tagname, attribs) => {
  1387. if ( tagname === 'a' ) taglink = attribs.href;
  1388. },
  1389. ontext: (htmltext) => {
  1390. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  1391. else tagtext += htmltext.escapeFormatting();
  1392. },
  1393. onclosetag: (tagname) => {
  1394. if ( tagname === 'a' ) taglink = '';
  1395. }
  1396. }, {decodeEntities:true} );
  1397. tagparser.write( tags[1] );
  1398. tagparser.end();
  1399. embed.addField( tags[0], tagtext );
  1400. }
  1401. var more = '\n__' + lang.diff.info.more + '__';
  1402. if ( !compare && oldid ) request( {
  1403. uri: wiki + 'api.php?action=compare&prop=diff&fromrev=' + oldid + '&torev=' + diff + '&format=json',
  1404. json: true
  1405. }, function( cperror, cpresponse, cpbody ) {
  1406. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  1407. if ( cperror || !cpresponse || cpresponse.statusCode !== 200 || !cpbody || !cpbody.compare || cpbody.compare['*'] === undefined ) {
  1408. var noerror = false;
  1409. if ( cpbody && cpbody.error ) {
  1410. switch ( cpbody.error.code ) {
  1411. case 'nosuchrevid':
  1412. noerror = true;
  1413. break;
  1414. case 'missingcontent':
  1415. noerror = true;
  1416. break;
  1417. default:
  1418. noerror = false;
  1419. }
  1420. }
  1421. if ( !noerror ) console.log( '- ' + ( cpresponse && cpresponse.statusCode ) + ': Error while getting the diff: ' + ( cperror || cpbody && cpbody.error && cpbody.error.info ) );
  1422. }
  1423. else if ( cpbody.compare.fromtexthidden === undefined && cpbody.compare.totexthidden === undefined && cpbody.compare.fromarchive === undefined && cpbody.compare.toarchive === undefined ) {
  1424. var current_tag = '';
  1425. var small_prev_ins = '';
  1426. var small_prev_del = '';
  1427. var ins_length = more.length;
  1428. var del_length = more.length;
  1429. var added = false;
  1430. var parser = new htmlparser.Parser( {
  1431. onopentag: (tagname, attribs) => {
  1432. if ( tagname === 'ins' || tagname == 'del' ) {
  1433. current_tag = tagname;
  1434. }
  1435. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  1436. current_tag = tagname+'a';
  1437. }
  1438. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  1439. current_tag = tagname+"d";
  1440. }
  1441. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  1442. added = true;
  1443. }
  1444. },
  1445. ontext: (htmltext) => {
  1446. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  1447. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  1448. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  1449. else small_prev_ins += more;
  1450. }
  1451. if ( current_tag === 'del' && del_length <= 1000 ) {
  1452. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  1453. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  1454. else small_prev_del += more;
  1455. }
  1456. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  1457. ins_length += htmltext.escapeFormatting().length;
  1458. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  1459. else small_prev_ins += more;
  1460. }
  1461. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  1462. del_length += htmltext.escapeFormatting().length;
  1463. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  1464. else small_prev_del += more;
  1465. }
  1466. if ( added ) {
  1467. if ( htmltext === '+' && ins_length <= 1000 ) {
  1468. ins_length++;
  1469. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  1470. else small_prev_ins += more;
  1471. }
  1472. if ( htmltext === '−' && del_length <= 1000 ) {
  1473. del_length++;
  1474. if ( del_length <= 1000 ) small_prev_del += '\n';
  1475. else small_prev_del += more;
  1476. }
  1477. added = false;
  1478. }
  1479. },
  1480. onclosetag: (tagname) => {
  1481. if ( tagname === 'ins' ) {
  1482. current_tag = 'afterins';
  1483. } else if ( tagname === 'del' ) {
  1484. current_tag = 'afterdel';
  1485. } else {
  1486. current_tag = '';
  1487. }
  1488. }
  1489. }, {decodeEntities:true} );
  1490. parser.write( cpbody.compare['*'] );
  1491. parser.end();
  1492. if ( small_prev_del.length ) {
  1493. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  1494. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  1495. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  1496. }
  1497. if ( small_prev_ins.length ) {
  1498. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  1499. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  1500. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  1501. }
  1502. }
  1503. else if ( cpbody.compare.fromtexthidden !== undefined ) {
  1504. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  1505. }
  1506. else if ( cpbody.compare.totexthidden !== undefined ) {
  1507. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  1508. }
  1509. msg.sendChannel( spoiler + text + spoiler, embed );
  1510. if ( reaction ) reaction.removeEmoji();
  1511. } );
  1512. else {
  1513. if ( compare ) {
  1514. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  1515. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  1516. }
  1517. else if ( revisions[0]['*'] ) {
  1518. var content = revisions[0]['*'].escapeFormatting();
  1519. if ( content.trim().length ) {
  1520. if ( content.length <= 1000 ) content = '**' + content + '**';
  1521. else {
  1522. content = content.substring(0, 1000 - more.length);
  1523. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  1524. }
  1525. embed.addField( lang.diff.info.added, content, true );
  1526. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  1527. }
  1528. msg.sendChannel( spoiler + text + spoiler, embed );
  1529. if ( reaction ) reaction.removeEmoji();
  1530. }
  1531. }
  1532. else {
  1533. var embed = {};
  1534. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  1535. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  1536. msg.sendChannel( spoiler + text + spoiler, embed );
  1537. if ( reaction ) reaction.removeEmoji();
  1538. }
  1539. }
  1540. }
  1541. else {
  1542. msg.reactEmoji('error');
  1543. if ( reaction ) reaction.removeEmoji();
  1544. }
  1545. }
  1546. } );
  1547. }
  1548. function cmd_random(lang, msg, wiki, reaction, spoiler) {
  1549. request( {
  1550. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general&prop=pageimages|pageprops|extracts&piprop=original|name&ppprop=description|displaytitle&exsentences=10&exintro=true&explaintext=true&generator=random&grnnamespace=0&format=json',
  1551. json: true
  1552. }, function( error, response, body ) {
  1553. if ( body && body.warnings ) log_warn(body.warnings);
  1554. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  1555. if ( response && ( response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' || response.statusCode === 410 ) ) {
  1556. console.log( '- This wiki doesn\'t exist!' );
  1557. msg.reactEmoji('nowiki');
  1558. }
  1559. else {
  1560. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1561. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Random>' + spoiler );
  1562. }
  1563. }
  1564. else {
  1565. querypage = Object.values(body.query.pages)[0];
  1566. var pagelink = wiki.toLink() + querypage.title.toTitle();
  1567. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1568. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  1569. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  1570. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  1571. embed.setTitle( displaytitle );
  1572. }
  1573. if ( querypage.pageprops && querypage.pageprops.description ) {
  1574. var description = htmlToPlain( querypage.pageprops.description );
  1575. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1576. embed.setDescription( description );
  1577. }
  1578. else if ( querypage.extract ) {
  1579. var extract = querypage.extract.escapeFormatting();
  1580. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1581. embed.setDescription( extract );
  1582. }
  1583. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  1584. embed.setThumbnail( querypage.original.source );
  1585. }
  1586. else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  1587. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, embed );
  1588. }
  1589. if ( reaction ) reaction.removeEmoji();
  1590. } );
  1591. }
  1592. function cmd_overview(lang, msg, wiki, reaction, spoiler) {
  1593. request( {
  1594. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general|statistics&titles=Special:Statistics&format=json',
  1595. json: true
  1596. }, function( error, response, body ) {
  1597. if ( body && body.warnings ) log_warn(body.warnings);
  1598. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  1599. if ( response && ( response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' || response.statusCode === 410 ) ) {
  1600. console.log( '- This wiki doesn\'t exist!' );
  1601. msg.reactEmoji('nowiki');
  1602. }
  1603. else {
  1604. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1605. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Statistics>' + spoiler );
  1606. }
  1607. }
  1608. else {
  1609. var site = false;
  1610. if ( allSites.some( site => site.wiki_domain === body.query.general.servername ) ) {
  1611. site = allSites.find( site => site.wiki_domain === body.query.general.servername );
  1612. var name = [lang.overview.name, site.wiki_display_name];
  1613. var created = [lang.overview.created, new Date(parseInt(site.created + '000', 10)).toLocaleString(lang.dateformat, timeoptions)];
  1614. var manager = [lang.overview.manager, site.wiki_managers];
  1615. var official = [lang.overview.official, ( site.official_wiki ? lang.overview.yes : lang.overview.no )];
  1616. var description = [lang.overview.description, site.wiki_description];
  1617. var image = [lang.overview.image, site.wiki_image];
  1618. if ( !description[1] ) description[1] = '-';
  1619. else if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  1620. description[1] = description[1].escapeFormatting();
  1621. if ( !image[1] ) image[1] = '-';
  1622. else if ( image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  1623. }
  1624. var articles = [lang.overview.articles, body.query.statistics.articles];
  1625. var pages = [lang.overview.pages, body.query.statistics.pages];
  1626. var edits = [lang.overview.edits, body.query.statistics.edits];
  1627. var users = [lang.overview.users, body.query.statistics.activeusers];
  1628. var title = body.query.pages['-1'].title;
  1629. var pagelink = wiki.toLink() + title.toTitle();
  1630. if ( msg.showEmbed() ) {
  1631. var text = '<' + pagelink + '>';
  1632. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( title.escapeFormatting() ).setURL( pagelink ).setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  1633. if ( site ) {
  1634. var managerlist = manager[1].map( manager => '[' + manager + '](' + wiki.toLink() + 'User:' + manager.toTitle(true) + ') ([' + lang.overview.talk + '](' + wiki.toLink() + 'User_talk:' + manager.toTitle(true) + '))' ).join('\n');
  1635. embed.addField( name[0], name[1], true ).addField( created[0], created[1], true ).addField( manager[0], ( managerlist || lang.overview.none ), true ).addField( official[0], official[1], true );
  1636. }
  1637. embed.addField( articles[0], articles[1], true ).addField( pages[0], pages[1], true ).addField( edits[0], edits[1], true ).addField( users[0], users[1], true ).setTimestamp( client.readyTimestamp ).setFooter( lang.overview.inaccurate );
  1638. if ( site ) {
  1639. embed.addField( description[0], description[1] ).addField( image[0], image[1] );
  1640. if ( image[1] !== '-' ) embed.setImage( image[1] );
  1641. }
  1642. }
  1643. else {
  1644. var embed = {};
  1645. var text = '<' + pagelink + '>\n\n';
  1646. if ( site ) text += name.join(' ') + '\n' + created.join(' ') + '\n' + manager[0] + ' ' + ( manager[1].join(', ') || lang.overview.none ) + '\n' + official.join(' ') + '\n';
  1647. text += articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  1648. if ( site ) {
  1649. text += '\n' + description.join(' ') + '\n' + image.join(' ');
  1650. if ( image[1] !== '-' && msg.uploadFiles() ) embed.files = [{attachment:image[1],name:( spoiler ? 'SPOILER ' : '' ) + name[1] + image[1].substring(image[1].lastIndexOf('.'))}];
  1651. }
  1652. text += '\n\n*' + lang.overview.inaccurate + '*';
  1653. }
  1654. msg.sendChannel( spoiler + text + spoiler, embed );
  1655. }
  1656. if ( reaction ) reaction.removeEmoji();
  1657. } );
  1658. }
  1659. function cmd_bug(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  1660. var invoke = args[0];
  1661. args = args.slice(1);
  1662. if ( invoke && /\d+$/.test(invoke) && !args.length ) {
  1663. var project = '';
  1664. if ( /^\d+$/.test(invoke) ) project = 'MC-';
  1665. request( {
  1666. uri: 'https://bugs.mojang.com/rest/api/2/issue/' + encodeURIComponent( project + invoke ) + '?fields=summary,issuelinks,fixVersions,resolution,status',
  1667. json: true
  1668. }, function( error, response, body ) {
  1669. var link = 'https://bugs.mojang.com/browse/';
  1670. if ( error || !response || response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  1671. if ( body && body.errorMessages ) {
  1672. if ( body.errorMessages.includes( 'Issue Does Not Exist' ) ) {
  1673. msg.reactEmoji('🤷');
  1674. }
  1675. else if ( body.errorMessages.includes( 'You do not have the permission to see the specified issue.' ) ) {
  1676. msg.sendChannel( spoiler + mclang.bug.private + '\n<' + link + project + invoke + '>' + spoiler );
  1677. }
  1678. else {
  1679. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + body.errorMessages.join(' - ') );
  1680. msg.reactEmoji('error');
  1681. }
  1682. }
  1683. else {
  1684. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + ( error || body && body.message ) );
  1685. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  1686. else msg.sendChannelError( spoiler + '<' + link + project + invoke + '>' + spoiler );
  1687. }
  1688. }
  1689. else {
  1690. if ( !body.fields ) {
  1691. msg.reactEmoji('error');
  1692. }
  1693. else {
  1694. var bugs = body.fields.issuelinks.filter( bug => bug.outwardIssue || ( bug.inwardIssue && bug.type.name != 'Duplicate' ) );
  1695. if ( bugs.length ) {
  1696. var embed = new Discord.RichEmbed();
  1697. var extrabugs = [];
  1698. bugs.forEach( bug => {
  1699. var ward = ( bug.outwardIssue ? 'outward' : 'inward' );
  1700. var issue = bug[ward + 'Issue'];
  1701. var name = bug.type[ward] + ' ' + issue.key;
  1702. var value = issue.fields.status.name + ': [' + issue.fields.summary.escapeFormatting() + '](' + link + issue.key + ')';
  1703. if ( embed.fields.length < 25 ) embed.addField( name, value );
  1704. else extrabugs.push({name,value,inline:false});
  1705. } );
  1706. if ( extrabugs.length ) embed.setFooter( mclang.bug.more.replaceSave( '%s', extrabugs.length ) );
  1707. }
  1708. var status = '**' + ( body.fields.resolution ? body.fields.resolution.name : body.fields.status.name ) + ':** ';
  1709. var fixed = '';
  1710. if ( body.fields.resolution && body.fields.fixVersions && body.fields.fixVersions.length ) {
  1711. fixed = '\n' + mclang.bug.fixed + ' ' + body.fields.fixVersions.map( v => v.name ).join(', ');
  1712. }
  1713. msg.sendChannel( spoiler + status + body.fields.summary.escapeFormatting() + '\n<' + link + body.key + '>' + fixed + spoiler, embed );
  1714. }
  1715. }
  1716. if ( reaction ) reaction.removeEmoji();
  1717. } );
  1718. }
  1719. else if ( invoke && invoke.toLowerCase() === 'version' && args.length && args.join(' ').length < 100 ) {
  1720. var jql = 'fixVersion="' + args.join(' ').replace( /("|\\)/g, '\\$1' ).toSearch() + '"+order+by+key';
  1721. request( {
  1722. uri: 'https://bugs.mojang.com/rest/api/2/search?fields=summary,resolution,status&jql=' + jql + '&maxResults=25',
  1723. json: true
  1724. }, function( error, response, body ) {
  1725. var link = 'https://bugs.mojang.com/issues/?jql=' + jql;
  1726. if ( error || !response || response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  1727. if ( body && body.errorMessages ) {
  1728. if ( body.errorMessages.includes( 'The value \'' + args.join(' ') + '\' does not exist for the field \'fixVersion\'.' ) ) {
  1729. msg.reactEmoji('🤷');
  1730. }
  1731. else {
  1732. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issues: ' + body.errorMessages.join(' - ') );
  1733. msg.reactEmoji('error');
  1734. }
  1735. }
  1736. else {
  1737. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issues: ' + ( error || body && body.message ) );
  1738. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  1739. else msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  1740. }
  1741. }
  1742. else {
  1743. if ( !body.issues ) {
  1744. msg.reactEmoji('error');
  1745. }
  1746. else {
  1747. if ( body.total > 0 ) {
  1748. var embed = new Discord.RichEmbed();
  1749. body.issues.forEach( bug => {
  1750. var status = ( bug.fields.resolution ? bug.fields.resolution.name : bug.fields.status.name );
  1751. var value = status + ': [' + bug.fields.summary.escapeFormatting() + '](https://bugs.mojang.com/browse/' + bug.key + ')';
  1752. embed.addField( bug.key, value );
  1753. } );
  1754. if ( body.total > 25 ) embed.setFooter( mclang.bug.more.replaceSave( '%s', body.total - 25 ) );
  1755. }
  1756. var total = '**' + args.join(' ') + ':** ' + mclang.bug.total.replaceSave( '%s', body.total );
  1757. msg.sendChannel( spoiler + total + '\n<' + link + '>' + spoiler, embed );
  1758. }
  1759. }
  1760. if ( reaction ) reaction.removeEmoji();
  1761. } );
  1762. }
  1763. else {
  1764. msg.notminecraft = true;
  1765. check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  1766. }
  1767. }
  1768. function cmd_befehl(lang, mclang, msg, befehl, args, title, cmd, querystring, fragment, reaction, spoiler) {
  1769. befehl = befehl.toLowerCase();
  1770. var aliasCmd = ( minecraft.cmd.aliase[befehl] || befehl );
  1771. if ( aliasCmd in minecraft.cmd.list ) {
  1772. var regex = new RegExp('/' + aliasCmd, 'g');
  1773. var cmdSyntax = minecraft.cmd.list[aliasCmd].join( '\n' ).replaceSave( regex, '/' + befehl );
  1774. msg.sendChannel( spoiler + '```md\n' + cmdSyntax + '```<' + mclang.link + mclang.cmd.page + aliasCmd + '>' + spoiler, {split:{maxLength:2000,prepend:spoiler + '```md\n',append:'```' + spoiler}} );
  1775. if ( reaction ) reaction.removeEmoji();
  1776. }
  1777. else {
  1778. msg.reactEmoji('❓');
  1779. msg.notminecraft = true;
  1780. check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  1781. }
  1782. }
  1783. function cmd_befehl2(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  1784. if ( args.join('') ) {
  1785. if ( args[0].startsWith( '/' ) ) cmd_befehl(lang, mclang, msg, args[0].substring(1), args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  1786. else cmd_befehl(lang, mclang, msg, args[0], args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  1787. }
  1788. else {
  1789. msg.notminecraft = true;
  1790. check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  1791. }
  1792. }
  1793. function cmd_multiline(lang, msg, args, line) {
  1794. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1795. if ( msg.isAdmin() ) msg.reactEmoji('error', true);
  1796. else msg.reactEmoji('❌');
  1797. }
  1798. }
  1799. function cmd_voice(lang, msg, args, line) {
  1800. if ( msg.isAdmin() && !args.join('') ) msg.replyMsg( lang.voice.text + '\n`' + lang.voice.channel + ' – <' + lang.voice.name + '>`' );
  1801. else cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  1802. }
  1803. function cmd_get(lang, msg, args, line) {
  1804. var id = args.join().replace( /^\\?<(?:@!?|#)(\d+)>$/, '$1' );
  1805. if ( /^\d+$/.test(id) ) {
  1806. if ( client.guilds.has(id) ) {
  1807. var guild = client.guilds.get(id);
  1808. var guildname = ['Guild:', guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( pause[guild.id] ? '\\*' : '' )];
  1809. var guildowner = ['Owner:', guild.owner.user.tag.escapeFormatting() + ' `' + guild.ownerID + '` ' + guild.owner.toString()];
  1810. var guildsize = ['Size:', guild.memberCount + ' members (' + guild.members.filter( member => member.user.bot ).size + ' bots)'];
  1811. var guildpermissions = ['Missing permissions:', ( guild.me.permissions.has(defaultPermissions) ? '*none*' : '`' + guild.me.permissions.missing(defaultPermissions).join('`, `') + '`' )];
  1812. var guildsettings = ['Settings:', ( guild.id in settings ? '```json\n' + JSON.stringify( settings[guild.id], null, '\t' ) + '\n```' : '*default*' )];
  1813. if ( msg.showEmbed() ) {
  1814. var text = '';
  1815. var embed = new Discord.RichEmbed().addField( guildname[0], guildname[1] ).addField( guildowner[0], guildowner[1] ).addField( guildsize[0], guildsize[1] ).addField( guildpermissions[0], guildpermissions[1] );
  1816. var split = Discord.Util.splitMessage( guildsettings[1], {maxLength:1000,prepend:'```json\n{',append:'\n```'} );
  1817. if ( split.length < guildsettings[1].length ) split.forEach( guildsettingspart => embed.addField( guildsettings[0], guildsettingspart ) );
  1818. else embed.addField( guildsettings[0], split );
  1819. }
  1820. else {
  1821. var embed = {};
  1822. var text = guildname.join(' ') + '\n' + guildowner.join(' ') + '\n' + guildsize.join(' ') + '\n' + guildpermissions.join(' ') + '\n' + guildsettings.join(' ');
  1823. }
  1824. msg.sendChannel( text, {embed,split:{prepend:'```json\n{',append:'\n```'}}, true );
  1825. } else if ( client.guilds.some( guild => guild.members.has(id) ) ) {
  1826. var username = [];
  1827. var guildlist = ['Guilds:'];
  1828. var guilds = client.guilds.filter( guild => guild.members.has(id) );
  1829. guildlist.push('\n' + guilds.map( function(guild) {
  1830. var member = guild.members.get(id);
  1831. if ( !username.length ) username.push('User:', member.user.tag.escapeFormatting() + ' `' + member.id + '` ' + member.toString());
  1832. return guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( member.permissions.has('MANAGE_GUILD') ? '\\*' : '' );
  1833. } ).join('\n'));
  1834. if ( guildlist[1].length > 1000 ) guildlist[1] = guilds.size;
  1835. if ( msg.showEmbed() ) {
  1836. var text = '';
  1837. var embed = new Discord.RichEmbed().addField( username[0], username[1] ).addField( guildlist[0], guildlist[1] );
  1838. }
  1839. else {
  1840. var embed = {};
  1841. var text = username.join(' ') + '\n' + guildlist.join(' ');
  1842. }
  1843. msg.sendChannel( text, embed, true );
  1844. } else if ( client.guilds.some( guild => guild.channels.filter( chat => chat.type === 'text' ).has(id) ) ) {
  1845. var channel = client.guilds.find( guild => guild.channels.filter( chat => chat.type === 'text' ).has(id) ).channels.get(id);
  1846. var channelguild = ['Guild:', channel.guild.name.escapeFormatting() + ' `' + channel.guild.id + '`' + ( pause[channel.guild.id] ? '\\*' : '' )];
  1847. var channelname = ['Channel:', '#' + channel.name.escapeFormatting() + ' `' + channel.id + '` ' + channel.toString()];
  1848. var channelpermissions = ['Missing permissions:', ( channel.memberPermissions(channel.guild.me).has(defaultPermissions) ? '*none*' : '`' + channel.memberPermissions(channel.guild.me).missing(defaultPermissions).join('`, `') + '`' )];
  1849. var channelwiki = ['Default Wiki:', channel.getWiki()];
  1850. if ( msg.showEmbed() ) {
  1851. var text = '';
  1852. var embed = new Discord.RichEmbed().addField( channelguild[0], channelguild[1] ).addField( channelname[0], channelname[1] ).addField( channelpermissions[0], channelpermissions[1] ).addField( channelwiki[0], channelwiki[1] );
  1853. }
  1854. else {
  1855. var embed = {};
  1856. var text = channelguild.join(' ') + '\n' + channelname.join(' ') + '\n' + channelpermissions.join(' ') + '\n' + channelwiki[0] + ' <' + channelwiki[1] + '>';
  1857. }
  1858. msg.sendChannel( text, embed, true );
  1859. } else msg.replyMsg( 'I couldn\'t find a result for `' + id + '`', {}, true );
  1860. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  1861. }
  1862. function htmlToPlain(html) {
  1863. var text = '';
  1864. var parser = new htmlparser.Parser( {
  1865. ontext: (htmltext) => {
  1866. text += htmltext.escapeFormatting();
  1867. }
  1868. }, {decodeEntities:true} );
  1869. parser.write( html );
  1870. parser.end();
  1871. return text;
  1872. };
  1873. function htmlToDiscord(html) {
  1874. var text = '';
  1875. var parser = new htmlparser.Parser( {
  1876. onopentag: (tagname, attribs) => {
  1877. switch (tagname) {
  1878. case 'b':
  1879. text += '**';
  1880. break;
  1881. case 'i':
  1882. text += '*';
  1883. break;
  1884. case 's':
  1885. text += '~~';
  1886. break;
  1887. case 'u':
  1888. text += '__';
  1889. break;
  1890. }
  1891. },
  1892. ontext: (htmltext) => {
  1893. text += htmltext.escapeFormatting();
  1894. },
  1895. onclosetag: (tagname) => {
  1896. switch (tagname) {
  1897. case 'b':
  1898. text += '**';
  1899. break;
  1900. case 'i':
  1901. text += '*';
  1902. break;
  1903. case 's':
  1904. text += '~~';
  1905. break;
  1906. case 'u':
  1907. text += '__';
  1908. break;
  1909. }
  1910. }
  1911. }, {decodeEntities:true} );
  1912. parser.write( html );
  1913. parser.end();
  1914. return text;
  1915. };
  1916. String.prototype.toLink = function() {
  1917. if ( this.endsWith( '.org/w/' ) ) return this.substring(0, this.length - 2) + 'wiki/';
  1918. else return this;
  1919. };
  1920. String.prototype.isMention = function(guild) {
  1921. var text = this.trim();
  1922. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  1923. };
  1924. Discord.Channel.prototype.getWiki = function() {
  1925. if ( this.type === 'text' && this.guild.id in settings ) {
  1926. if ( settings[this.guild.id].channels && this.id in settings[this.guild.id].channels ) return settings[this.guild.id].channels[this.id];
  1927. else return settings[this.guild.id].wiki;
  1928. }
  1929. else return settings.default.wiki;
  1930. };
  1931. Discord.Message.prototype.isAdmin = function() {
  1932. return this.channel.type === 'text' && this.member && this.member.permissions.has('MANAGE_GUILD');
  1933. };
  1934. Discord.Message.prototype.isOwner = function() {
  1935. return this.author.id === process.env.owner;
  1936. };
  1937. Discord.Message.prototype.showEmbed = function() {
  1938. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  1939. };
  1940. Discord.Message.prototype.uploadFiles = function() {
  1941. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  1942. };
  1943. Array.prototype.toEmojis = function() {
  1944. var text = this.join(' ');
  1945. var regex = /(<a?:)(\d+)(>)/g;
  1946. if ( regex.test(text) ) {
  1947. regex.lastIndex = 0;
  1948. var emojis = client.emojis;
  1949. while ( ( entry = regex.exec(text) ) !== null ) {
  1950. if ( emojis.has(entry[2]) ) {
  1951. text = text.replaceSave(entry[0], emojis.get(entry[2]).toString());
  1952. } else {
  1953. text = text.replaceSave(entry[0], entry[1] + 'unknown_emoji:' + entry[2] + entry[3]);
  1954. }
  1955. }
  1956. return text.split(' ');
  1957. }
  1958. else return this;
  1959. };
  1960. String.prototype.toTitle = function(isMarkdown = false) {
  1961. var title = this.replace( / /g, '_' ).replace( /\%/g, '%25' ).replace( /\?/g, '%3F' ).replace( /@(here|everyone)/g, '%40$1' );
  1962. if ( isMarkdown ) title = title.replace( /(\(|\))/g, '\\$1' );
  1963. return title;
  1964. };
  1965. String.prototype.toSearch = function() {
  1966. return encodeURIComponent( this ).replace( /%20/g, '+' );
  1967. };
  1968. String.prototype.toSection = function() {
  1969. return encodeURIComponent( this.replace( / /g, '_' ) ).replace( /\'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\%/g, '.' );
  1970. };
  1971. String.prototype.toFormatting = function(showEmbed = false, ...args) {
  1972. if ( showEmbed ) return this.toMarkdown(...args);
  1973. else return this.toPlaintext();
  1974. };
  1975. String.prototype.toMarkdown = function(wiki, title = '') {
  1976. var text = this;
  1977. while ( ( link = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g.exec(text) ) !== null ) {
  1978. if ( link[1] ) {
  1979. var page = ( /^(#|\/)/.test(link[1]) ? title.toTitle(true) + ( /^#/.test(link[1]) ? '#' + link[1].substring(1).toSection() : link[1].toTitle(true) ) : link[1].toTitle(true) );
  1980. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + wiki.toLink() + page + ')' );
  1981. } else {
  1982. var page = ( /^(#|\/)/.test(link[2]) ? title.toTitle(true) + ( /^#/.test(link[2]) ? '#' + link[2].substring(1).toSection() : link[2].toTitle(true) ) : link[2].toTitle(true) );
  1983. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + wiki.toLink() + page + ')' );
  1984. }
  1985. }
  1986. while ( title !== '' && ( link = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g.exec(text) ) !== null ) {
  1987. var page = title.toTitle(true) + '#' + link[1].toSection();
  1988. text = text.replaceSave( link[0], '[→](' + wiki.toLink() + page + ')' + link[1] + ( link[2] ? ': ' + link[2] : '' ) );
  1989. }
  1990. return text.escapeFormatting();
  1991. };
  1992. String.prototype.toPlaintext = function() {
  1993. return this.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' ).escapeFormatting();
  1994. };
  1995. String.prototype.escapeFormatting = function() {
  1996. return this.replace( /(`|_|\*|~|:|<|>|{|}|@|\||\\|\/\/)/g, '\\$1' );
  1997. };
  1998. String.prototype.replaceSave = function(pattern, replacement) {
  1999. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( '$', '$$$$' ) : replacement ) );
  2000. };
  2001. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  2002. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  2003. var emoji = '440871715938238494';
  2004. switch ( name ) {
  2005. case 'nowiki':
  2006. emoji = '505884572001763348';
  2007. break;
  2008. case 'error':
  2009. emoji = '440871715938238494';
  2010. break;
  2011. case 'support':
  2012. emoji = '448222377009086465';
  2013. break;
  2014. case 'oppose':
  2015. emoji = '448222455425794059';
  2016. break;
  2017. default:
  2018. emoji = name;
  2019. }
  2020. return this.react(emoji).catch(log_error);
  2021. } else {
  2022. console.log( '- Aborted, paused.' );
  2023. return Promise.resolve();
  2024. }
  2025. };
  2026. Discord.MessageReaction.prototype.removeEmoji = function() {
  2027. return this.remove().catch(log_error);
  2028. };
  2029. Discord.Message.prototype.sendChannel = function(content, options, ignorePause = false) {
  2030. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  2031. return this.channel.send(content, options).then( msg => {
  2032. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  2033. else msg.allowDelete(this.author.id);
  2034. return msg;
  2035. }, log_error );
  2036. } else {
  2037. console.log( '- Aborted, paused.' );
  2038. return Promise.resolve();
  2039. }
  2040. };
  2041. Discord.Message.prototype.sendChannelError = function(content, options) {
  2042. return this.channel.send(content, options).then( msg => {
  2043. if ( msg.length ) msg.forEach( message => {
  2044. message.reactEmoji('error');
  2045. message.allowDelete(this.author.id);
  2046. } );
  2047. else {
  2048. msg.reactEmoji('error');
  2049. msg.allowDelete(this.author.id);
  2050. }
  2051. return msg;
  2052. }, log_error );
  2053. };
  2054. Discord.Message.prototype.replyMsg = function(content, options, ignorePause = false) {
  2055. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  2056. return this.reply(content, options).then( msg => {
  2057. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  2058. else msg.allowDelete(this.author.id);
  2059. return msg;
  2060. }, log_error );
  2061. } else {
  2062. console.log( '- Aborted, paused.' );
  2063. return Promise.resolve();
  2064. }
  2065. };
  2066. Discord.Message.prototype.deleteMsg = function(timeout = 0) {
  2067. return this.delete(timeout).catch(log_error);
  2068. };
  2069. Discord.Message.prototype.allowDelete = function(author) {
  2070. return this.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑' && user.id === author, {max:1,time:60000} ).then( reaction => {
  2071. if ( reaction.size ) {
  2072. this.deleteMsg();
  2073. }
  2074. } );
  2075. };
  2076. String.prototype.hasPrefix = function(flags = '') {
  2077. return RegExp( '^' + process.env.prefix + '(?: |$)', flags ).test(this.replace( /\u200b/g, '' ).toLowerCase());
  2078. };
  2079. client.on( 'message', msg => {
  2080. if ( stop || msg.type !== 'DEFAULT' || !msg.content.hasPrefix('m') || msg.webhookID || msg.author.id === client.user.id ) return;
  2081. var cont = msg.content;
  2082. var author = msg.author;
  2083. var channel = msg.channel;
  2084. if ( channel.type === 'text' ) var permissions = channel.permissionsFor(client.user);
  2085. if ( !ready.settings && settings === defaultSettings ) getSettings();
  2086. if ( !ready.allSites && !allSites.length ) getAllSites();
  2087. if ( settings === defaultSettings ) {
  2088. msg.sendChannel( '⚠ **Limited Functionality** ⚠\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  2089. }
  2090. var lang = i18n[( channel.type === 'text' && settings[msg.guild.id] || settings.default ).lang];
  2091. if ( channel.type !== 'text' || permissions.has(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']) ) {
  2092. var invoke = ( cont.split(' ')[1] ? cont.split(' ')[1].split('\n')[0].toLowerCase() : '' );
  2093. var aliasInvoke = ( lang.aliase[invoke] || invoke );
  2094. var ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  2095. if ( cont.hasPrefix() && ( ( msg.isAdmin() && aliasInvoke in multilinecmdmap ) || ownercmd ) ) {
  2096. if ( ownercmd || permissions.has('MANAGE_MESSAGES') ) {
  2097. var args = cont.split(' ').slice(2);
  2098. if ( cont.split(' ')[1].split('\n')[1] ) args.unshift( '', cont.split(' ')[1].split('\n')[1] );
  2099. if ( !( ownercmd || aliasInvoke in pausecmdmap ) && pause[msg.guild.id] ) console.log( msg.guild.name + ': Paused' );
  2100. else console.log( ( msg.guild ? msg.guild.name : '@' + author.username ) + ': ' + cont );
  2101. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, cont);
  2102. else if ( !pause[msg.guild.id] || aliasInvoke in pausecmdmap ) multilinecmdmap[aliasInvoke](lang, msg, args, cont);
  2103. } else {
  2104. console.log( msg.guild.name + ': Missing permissions - MANAGE_MESSAGES' );
  2105. msg.replyMsg( lang.missingperm + ' `MANAGE_MESSAGES`' );
  2106. }
  2107. } else {
  2108. var count = 0;
  2109. msg.cleanContent.replace( /\u200b/g, '' ).split('\n').forEach( function(line) {
  2110. if ( line.hasPrefix() && count < 10 ) {
  2111. count++;
  2112. invoke = ( line.split(' ')[1] ? line.split(' ')[1].toLowerCase() : '' );
  2113. var args = line.split(' ').slice(2);
  2114. aliasInvoke = ( lang.aliase[invoke] || invoke );
  2115. ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  2116. if ( channel.type === 'text' && pause[msg.guild.id] && !( ( msg.isAdmin() && aliasInvoke in pausecmdmap ) || ownercmd ) ) console.log( msg.guild.name + ': Paused' );
  2117. else console.log( ( msg.guild ? msg.guild.name : '@' + author.username ) + ': ' + line );
  2118. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, line);
  2119. else if ( channel.type !== 'text' || !pause[msg.guild.id] || ( msg.isAdmin() && aliasInvoke in pausecmdmap ) ) {
  2120. if ( aliasInvoke in cmdmap ) cmdmap[aliasInvoke](lang, msg, args, line);
  2121. else if ( /^![a-z\d-]{1,50}$/.test(invoke) ) cmd_link(lang, msg, args.join(' '), 'https://' + invoke.substring(1) + '.gamepedia.com/', ' ' + invoke + ' ');
  2122. else cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  2123. }
  2124. } else if ( line.hasPrefix() && count === 10 ) {
  2125. count++;
  2126. console.log( '- Message contains too many commands!' );
  2127. msg.reactEmoji('⚠');
  2128. msg.sendChannelError( lang.limit.replaceSave( '%s', author ) );
  2129. }
  2130. } );
  2131. }
  2132. } else if ( msg.isAdmin() || msg.isOwner() ) {
  2133. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  2134. console.log( msg.guild.name + ': Missing permissions - ' + missing.join(', ') );
  2135. if ( !missing.includes( 'SEND_MESSAGES' ) ) msg.replyMsg( lang.missingperm + ' `' + missing.join('`, `') + '`' );
  2136. }
  2137. } );
  2138. client.on( 'voiceStateUpdate', (oldm, newm) => {
  2139. if ( stop ) return;
  2140. if ( !ready.settings && settings === defaultSettings ) getSettings();
  2141. if ( !ready.allSites && !allSites.length ) getAllSites();
  2142. if ( oldm.guild.me.permissions.has('MANAGE_ROLES') && oldm.voiceChannelID !== newm.voiceChannelID ) {
  2143. var lang = i18n[( settings[oldm.guild.id] || settings.default ).lang].voice;
  2144. if ( oldm.voiceChannel ) {
  2145. var oldrole = oldm.roles.find( role => role.name === lang.channel + ' – ' + oldm.voiceChannel.name );
  2146. if ( oldrole && oldrole.comparePositionTo(oldm.guild.me.highestRole) < 0 ) {
  2147. console.log( oldm.guild.name + ': ' + oldm.displayName + ' left the voice channel "' + oldm.voiceChannel.name + '".' );
  2148. oldm.removeRole( oldrole, lang.left.replaceSave( '%1$s', oldm.displayName ).replaceSave( '%2$s', oldm.voiceChannel.name ) ).catch(log_error);
  2149. }
  2150. }
  2151. if ( newm.voiceChannel ) {
  2152. var newrole = newm.guild.roles.find( role => role.name === lang.channel + ' – ' + newm.voiceChannel.name );
  2153. if ( newrole && newrole.comparePositionTo(newm.guild.me.highestRole) < 0 ) {
  2154. console.log( newm.guild.name + ': ' + newm.displayName + ' joined the voice channel "' + newm.voiceChannel.name + '".' );
  2155. newm.addRole( newrole, lang.join.replaceSave( '%1$s', newm.displayName ).replaceSave( '%2$s', newm.voiceChannel.name ) ).catch(log_error);
  2156. }
  2157. }
  2158. }
  2159. } );
  2160. client.on( 'guildCreate', guild => {
  2161. console.log( '- I\'ve been added to a server.' );
  2162. } );
  2163. client.on( 'guildDelete', guild => {
  2164. console.log( '- I\'ve been removed from a server.' );
  2165. if ( !guild.available ) {
  2166. console.log( '- ' + guild.name + ': This server isn\'t responding.' );
  2167. return;
  2168. }
  2169. if ( settings === defaultSettings ) {
  2170. console.log( '- Error while getting current settings.' );
  2171. }
  2172. else {
  2173. var temp_settings = JSON.parse(JSON.stringify(settings));
  2174. var save = false;
  2175. Object.keys(temp_settings).forEach( function(guild) {
  2176. if ( !client.guilds.has(guild) && guild !== 'default' ) {
  2177. delete temp_settings[guild];
  2178. save = true;
  2179. }
  2180. } );
  2181. if ( save ) request.post( {
  2182. uri: process.env.save,
  2183. headers: access,
  2184. body: {
  2185. branch: 'master',
  2186. commit_message: client.user.username + ': Settings removed',
  2187. actions: [
  2188. {
  2189. action: 'update',
  2190. file_path: process.env.file,
  2191. content: JSON.stringify( temp_settings, null, '\t' )
  2192. }
  2193. ]
  2194. },
  2195. json: true
  2196. }, function( error, response, body ) {
  2197. if ( error || !response || response.statusCode !== 201 || !body || body.error ) {
  2198. console.log( '- ' + ( response && response.statusCode ) + ': Error while removing the settings: ' + ( error || body && ( body.message || body.error ) ) );
  2199. }
  2200. else {
  2201. settings = JSON.parse(JSON.stringify(temp_settings));
  2202. console.log( '- Settings successfully removed.' );
  2203. }
  2204. } );
  2205. }
  2206. } );
  2207. client.login(process.env.token).catch( error => {
  2208. log_error(error, true, 'LOGIN-');
  2209. client.login(process.env.token).catch( error => {
  2210. log_error(error, true, 'LOGIN-');
  2211. client.login(process.env.token).catch( error => {
  2212. log_error(error, true, 'LOGIN-');
  2213. process.exit(1);
  2214. } );
  2215. } );
  2216. } );
  2217. client.on( 'error', error => log_error(error, true) );
  2218. client.on( 'warn', warning => log_warn(warning, false) );
  2219. if ( isDebug ) client.on( 'debug', debug => {
  2220. if ( isDebug ) console.log( '- Debug: ' + debug );
  2221. } );
  2222. function log_error(error, isBig = false, type = '') {
  2223. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  2224. if ( isDebug ) {
  2225. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  2226. } else {
  2227. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  2228. else console.log( '- ' + error.name + ': ' + error.message );
  2229. }
  2230. }
  2231. function log_warn(warning, api = true) {
  2232. if ( isDebug ) {
  2233. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  2234. } else {
  2235. if ( api ) console.warn( '- Warning: ' + Object.keys(warning).join(', ') );
  2236. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  2237. }
  2238. }
  2239. async function graceful(code = 0) {
  2240. stop = true;
  2241. console.log( '- SIGTERM: Preparing to close...' );
  2242. setTimeout( async () => {
  2243. console.log( '- SIGTERM: Destroying client...' );
  2244. await client.destroy();
  2245. setTimeout( async () => {
  2246. console.log( '- SIGTERM: Closing takes too long, terminating!' );
  2247. process.exit(code);
  2248. }, 1000 ).unref();
  2249. }, 2000 ).unref();
  2250. }
  2251. process.once( 'SIGINT', graceful );
  2252. process.once( 'SIGTERM', graceful );