main.js 269 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428
  1. require('dotenv').config();
  2. const util = require('util');
  3. util.inspect.defaultOptions = {compact:false,breakLength:Infinity};
  4. var isDebug = ( process.argv[2] === 'debug' );
  5. var ready = {
  6. patreons: false,
  7. voice: false,
  8. allSites: true
  9. }
  10. const Discord = require('discord.js');
  11. const got = require('got').extend( {
  12. throwHttpErrors: false,
  13. timeout: 5000,
  14. headers: {
  15. 'User-Agent': 'Wiki-Bot/' + ( isDebug ? 'testing' : process.env.npm_package_version ) + ' (Discord; ' + process.env.npm_package_name + ')'
  16. }
  17. } );
  18. const htmlparser = require('htmlparser2');
  19. const cheerio = require('cheerio');
  20. const sqlite3 = require('sqlite3').verbose();
  21. var db = new sqlite3.Database( './wikibot.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, dberror => {
  22. if ( dberror ) {
  23. console.log( '- Error while connecting to the database: ' + dberror );
  24. return dberror;
  25. }
  26. console.log( '- Connected to the database.' );
  27. } );
  28. var client = new Discord.Client( {
  29. messageCacheLifetime: 300,
  30. messageSweepInterval: 300,
  31. presence: {
  32. status: 'online',
  33. activity: {
  34. type: 'STREAMING',
  35. name: process.env.prefix + ' help',
  36. url: 'https://www.twitch.tv/wikibot'
  37. }
  38. },
  39. ws: {
  40. large_threshold: 1000,
  41. intents: [
  42. 'GUILDS',
  43. 'GUILD_MESSAGES',
  44. 'GUILD_MESSAGE_REACTIONS',
  45. 'GUILD_VOICE_STATES',
  46. 'GUILD_INTEGRATIONS',
  47. 'DIRECT_MESSAGES',
  48. 'DIRECT_MESSAGE_REACTIONS'
  49. ]
  50. }
  51. } );
  52. var i18n = require('./i18n/allLangs.json');
  53. Object.keys(i18n.allLangs[1]).forEach( lang => i18n[lang] = require('./i18n/' + lang + '.json') );
  54. const minecraft = require('./minecraft.json');
  55. var pause = {};
  56. var stop = false;
  57. const defaultPermissions = new Discord.Permissions(268815424).toArray();
  58. const timeoptions = {
  59. year: 'numeric',
  60. month: 'short',
  61. day: 'numeric',
  62. hour: '2-digit',
  63. minute: '2-digit',
  64. timeZone: 'UTC',
  65. timeZoneName: 'short'
  66. }
  67. const defaultSettings = {
  68. lang: "en",
  69. wiki: "https://community.fandom.com/"
  70. }
  71. var patreons = {};
  72. function getSettings(trysettings = 1) {
  73. db.each( 'SELECT guild, prefix FROM discord WHERE patreon IS NOT NULL', [], (dberror, row) => {
  74. if ( dberror ) {
  75. console.log( '- ' + trysettings + '. Error while getting the patreon: ' + dberror );
  76. if ( trysettings < 10 ) {
  77. trysettings++;
  78. getSettings(trysettings);
  79. }
  80. return dberror;
  81. }
  82. patreons[row.guild] = row.prefix;
  83. }, (dberror) => {
  84. if ( dberror ) {
  85. console.log( '- ' + trysettings + '. Error while getting the patreons: ' + dberror );
  86. if ( dberror.message === 'SQLITE_ERROR: no such table: discord' ) db.serialize( () => {
  87. db.run( 'CREATE TABLE IF NOT EXISTS patreons(patreon TEXT PRIMARY KEY UNIQUE NOT NULL, count INTEGER NOT NULL)', [], function (error) {
  88. if ( error ) {
  89. console.log( '- Error while creating the patreons table: ' + error );
  90. return error;
  91. }
  92. console.log( '- Created the patreons table.' );
  93. db.run( 'CREATE INDEX idx_patreons_patreon ON patreons(patreon)', [], function (idxerror) {
  94. if ( idxerror ) {
  95. console.log( '- Error while creating the patreons index: ' + idxerror );
  96. return error;
  97. }
  98. console.log( '- Created the patreons index.' );
  99. } );
  100. } );
  101. db.run( 'CREATE TABLE IF NOT EXISTS discord(guild TEXT NOT NULL, channel TEXT, lang TEXT NOT NULL DEFAULT [' + defaultSettings.lang + '], wiki TEXT NOT NULL DEFAULT [' + defaultSettings.wiki + '], prefix TEXT NOT NULL DEFAULT [' + process.env.prefix + '], patreon TEXT, voice INTEGER, inline INTEGER, UNIQUE(guild, channel), FOREIGN KEY(patreon) REFERENCES patreons(patreon) ON DELETE SET NULL)', [], function (error) {
  102. if ( error ) {
  103. console.log( '- Error while creating the discord table: ' + error );
  104. return error;
  105. }
  106. console.log( '- Created the discord table.' );
  107. db.run( 'CREATE TRIGGER unique_discord_guild BEFORE INSERT ON discord WHEN NEW.channel IS NULL BEGIN SELECT CASE WHEN (SELECT 1 FROM discord WHERE guild = NEW.guild AND channel IS NULL) IS NOT NULL THEN RAISE(ABORT, "UNIQUE constraint failed: discord.guild, discord.channel") END; END;', [], function (idxerror) {
  108. if ( idxerror ) {
  109. console.log( '- Error while creating the discord guild trigger: ' + idxerror );
  110. return error;
  111. }
  112. console.log( '- Created the discord guild trigger.' );
  113. } );
  114. db.run( 'CREATE INDEX idx_discord_patreon ON discord(patreon) WHERE patreon IS NOT NULL', [], function (idxerror) {
  115. if ( idxerror ) {
  116. console.log( '- Error while creating the discord patreon index: ' + idxerror );
  117. return error;
  118. }
  119. console.log( '- Created the discord patreon index.' );
  120. } );
  121. db.run( 'CREATE INDEX idx_discord_voice ON discord(voice) WHERE voice IS NOT NULL', [], function (idxerror) {
  122. if ( idxerror ) {
  123. console.log( '- Error while creating the discord voice index: ' + idxerror );
  124. return error;
  125. }
  126. console.log( '- Created the discord voice index.' );
  127. } );
  128. db.run( 'CREATE INDEX idx_discord_channel ON discord(guild, channel DESC)', [], function (idxerror) {
  129. if ( idxerror ) {
  130. console.log( '- Error while creating the discord channel index: ' + idxerror );
  131. return error;
  132. }
  133. console.log( '- Created the discord channel index.' );
  134. } );
  135. if ( trysettings < 10 ) {
  136. trysettings++;
  137. getSettings(trysettings);
  138. }
  139. } );
  140. /*
  141. db.run( 'CREATE TABLE IF NOT EXISTS verification(guild TEXT NOT NULL, channel TEXT, wiki TEXT NOT NULL, role TEXT NOT NULL, editcount INTEGER NOT NULL DEFAULT [0], usergroup TEXT NOT NULL DEFAULT [user])', [], function (error) {
  142. if ( error ) {
  143. console.log( '- Error while creating the verification table: ' + error );
  144. return error;
  145. }
  146. console.log( '- Created the verification table.' );
  147. db.run( 'CREATE INDEX idx_verification_channel ON verification(guild, channel DESC)', [], function (idxerror) {
  148. if ( idxerror ) {
  149. console.log( '- Error while creating the verification index: ' + idxerror );
  150. return error;
  151. }
  152. console.log( '- Created the verification index.' );
  153. } );
  154. } );
  155. */
  156. } );
  157. else {
  158. if ( trysettings < 10 ) {
  159. trysettings++;
  160. getSettings(trysettings);
  161. }
  162. }
  163. return dberror;
  164. }
  165. console.log( '- Patreons successfully loaded.' );
  166. ready.patreons = true;
  167. getVoice();
  168. } );
  169. }
  170. var voice = {};
  171. function getVoice(trysettings = 1) {
  172. db.each( 'SELECT guild, lang FROM discord WHERE voice IS NOT NULL', [], (dberror, row) => {
  173. if ( dberror ) {
  174. console.log( '- ' + trysettings + '. Error while getting the voice channel: ' + dberror );
  175. if ( trysettings < 10 ) {
  176. trysettings++;
  177. getVoice(trysettings);
  178. }
  179. return dberror;
  180. }
  181. voice[row.guild] = row.lang;
  182. }, (dberror) => {
  183. if ( dberror ) {
  184. console.log( '- ' + trysettings + '. Error while getting the voice channels: ' + dberror );
  185. if ( trysettings < 10 ) {
  186. trysettings++;
  187. getVoice(trysettings);
  188. }
  189. return dberror;
  190. }
  191. console.log( '- Voice channels successfully loaded.' );
  192. ready.voice = true;
  193. } );
  194. }
  195. var allSites = [];
  196. function getAllSites() {
  197. ready.allSites = true;
  198. got.get( '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,wiki_crossover,created&format=json', {
  199. responseType: 'json'
  200. } ).then( response => {
  201. var body = response.body;
  202. if ( response.statusCode !== 200 || !body || body.status !== 'okay' || !body.data || !body.data.wikis ) {
  203. console.log( '- ' + response.statusCode + ': Error while gettings all sites: ' + ( body && body.error && body.error.info ) );
  204. ready.allSites = false;
  205. }
  206. else {
  207. console.log( '- Sites successfully loaded.' );
  208. allSites = JSON.parse(JSON.stringify(body.data.wikis.filter( site => /^[a-z\d-]{1,50}\.gamepedia\.com$/.test(site.wiki_domain) )));
  209. allSites.filter( site => site.wiki_crossover ).forEach( site => site.wiki_crossover = site.wiki_crossover.replace( /^(?:https?:)?\/\/(([a-z\d-]{1,50})\.(?:fandom\.com|wikia\.org)(?:(?!\/wiki\/)\/([a-z-]{1,8}))?).*/, '$1' ) );
  210. }
  211. }, error => {
  212. console.log( '- Error while gettings all sites: ' + error );
  213. } );
  214. }
  215. client.on( 'ready', () => {
  216. console.log( '\n- Successfully logged in as ' + client.user.username + '!' );
  217. getSettings();
  218. getAllSites();
  219. if ( !isDebug ) client.setInterval( () => {
  220. console.log( '- Current server count: ' + client.guilds.cache.size );
  221. if ( process.env.dbltoken ) got.post( 'https://top.gg/api/bots/' + client.user.id + '/stats', {
  222. headers: {
  223. Authorization: process.env.dbltoken
  224. },
  225. json: {
  226. server_count: client.guilds.cache.size
  227. },
  228. responseType: 'json'
  229. } ).catch( error => {
  230. console.log( '- Error while posting statistics to https://top.gg/bot/' + client.user.id + ': ' + error );
  231. } );
  232. if ( process.env.dbggtoken ) got.post( 'https://discord.bots.gg/api/v1/bots/' + client.user.id + '/stats', {
  233. headers: {
  234. Authorization: process.env.dbggtoken
  235. },
  236. json: {
  237. guildCount: client.guilds.cache.size
  238. },
  239. responseType: 'json'
  240. } ).catch( error => {
  241. console.log( '- Error while posting statistics to https://discord.bots.gg/bots/' + client.user.id + ': ' + error );
  242. } );
  243. }, 10800000 ).unref();
  244. } );
  245. var cmdmap = {
  246. help: cmd_help,
  247. test: cmd_test,
  248. pause: cmd_pause,
  249. invite: cmd_invite,
  250. voice: cmd_voice,
  251. settings: cmd_settings,
  252. info: cmd_info,
  253. patreon: cmd_patreon
  254. }
  255. var ownercmdmap = {
  256. stop: cmd_stop,
  257. pause: cmd_pause,
  258. say: cmd_say,
  259. eval: cmd_eval,
  260. get: cmd_get,
  261. patreon: cmd_patreon
  262. }
  263. var pausecmdmap = {
  264. help: cmd_help,
  265. test: cmd_test,
  266. pause: cmd_pause,
  267. voice: cmd_voice,
  268. settings: cmd_settings,
  269. patreon: cmd_patreon
  270. }
  271. var minecraftcmdmap = {
  272. command: minecraft_command2,
  273. bug: minecraft_bug
  274. }
  275. function cmd_helpsetup(lang, msg) {
  276. msg.defaultSettings = false;
  277. msg.replyMsg( lang.settings.missing.replaceSave( '%1$s', '`' + process.env.prefix + ' settings lang`' ).replaceSave( '%2$s', '`' + process.env.prefix + ' settings wiki`' ) );
  278. }
  279. function cmd_settings(lang, msg, args, line, wiki) {
  280. if ( !msg.isAdmin() ) return msg.reactEmoji('❌');
  281. db.all( 'SELECT channel, lang, wiki, prefix, inline FROM discord WHERE guild = ? ORDER BY channel DESC', [msg.guild.id], (error, rows) => {
  282. if ( error ) {
  283. console.log( '- Error while getting the settings: ' + error );
  284. msg.reactEmoji('error', true);
  285. return error;
  286. }
  287. var guild = rows.find( row => !row.channel );
  288. if ( !guild ) guild = Object.assign({prefix: process.env.prefix}, defaultSettings);
  289. var prefix = guild.prefix;
  290. var text = lang.settings.missing.replaceSave( '%1$s', '`' + prefix + ' settings lang`' ).replaceSave( '%2$s', '`' + prefix + ' settings wiki`' );
  291. if ( rows.length ) {
  292. text = lang.settings.current + '\n' + lang.settings.currentlang + ' `' + i18n.allLangs[2][guild.lang] + '` - `' + prefix + ' settings lang`';
  293. if ( msg.guild.id in patreons ) text += '\n' + lang.settings.currentprefix + ' `' + prefix + '` - `' + prefix + ' settings prefix`';
  294. text += '\n' + lang.settings.currentinline + ' ' + ( guild.inline ? '~~' : '' ) + '`[[' + lang.search.page + ']]`' + ( guild.inline ? '~~' : '' ) + ' - `' + prefix + ' settings inline`';
  295. text += '\n' + lang.settings.currentwiki + ' ' + guild.wiki + ' - `' + prefix + ' settings wiki`';
  296. text += '\n' + lang.settings.currentchannel + ' `' + prefix + ' settings channel`\n';
  297. if ( rows.length === 1 ) text += lang.settings.nochannels;
  298. else text += rows.filter( row => row !== guild ).map( row => '<#' + row.channel + '>: ' + ( msg.guild.id in patreons ? '`' + i18n.allLangs[2][row.lang] + '` - ' : '' ) + '<' + row.wiki + '>' + ( msg.guild.id in patreons ? ' - ' + ( row.inline ? '~~' : '' ) + '`[[' + lang.search.page + ']]`' + ( row.inline ? '~~' : '' ) : '' ) ).join('\n');
  299. }
  300. if ( !args.length ) {
  301. return msg.replyMsg( text, {split:true}, true );
  302. }
  303. var prelang = '';
  304. args[0] = args[0].toLowerCase();
  305. if ( args[0] === 'channel' ) {
  306. prelang = 'channel ';
  307. if ( !rows.length ) return msg.replyMsg( text, {split:true}, true );
  308. var channel = rows.find( row => row.channel === msg.channel.id );
  309. if ( !channel ) channel = Object.assign({channel:msg.channel.id}, guild);
  310. text = lang.settings[prelang + 'current'];
  311. if ( msg.guild.id in patreons ) {
  312. text += '\n' + lang.settings.currentlang + ' `' + i18n.allLangs[2][channel.lang] + '` - `' + prefix + ' settings channel lang`';
  313. text += '\n' + lang.settings.currentinline + ' ' + ( channel.inline ? '~~' : '' ) + '`[[' + lang.search.page + ']]`' + ( channel.inline ? '~~' : '' ) + ' - `' + prefix + ' settings channel inline`';
  314. }
  315. text += '\n' + lang.settings.currentwiki + ' ' + channel.wiki + ' - `' + prefix + ' settings channel wiki`';
  316. if ( !args[1] ) return msg.replyMsg( text, {}, true );
  317. args[0] = args[1].toLowerCase();
  318. args[1] = args.slice(2).join(' ').toLowerCase().trim().replace( /^<(.*)>$/, '$1' );
  319. }
  320. else args[1] = args.slice(1).join(' ').toLowerCase().trim().replace( /^<(.*)>$/, '$1' );
  321. if ( args[0] === 'wiki' ) {
  322. prelang += 'wiki';
  323. var wikihelp = '\n' + lang.settings.wikihelp.replaceSave( '%s', prefix + ' settings ' + prelang );
  324. if ( !args[1] ) {
  325. if ( !rows.length ) return msg.replyMsg( lang.settings.wikimissing + wikihelp, {}, true );
  326. else return msg.replyMsg( lang.settings[prelang] + ' ' + ( channel || guild ).wiki + wikihelp, {}, true );
  327. }
  328. var regex = args[1].match( /^(?:https:\/\/)?([a-z\d-]{1,50}\.(?:gamepedia\.com|(?:fandom\.com|wikia\.org)(?:(?!\/wiki\/)\/[a-z-]{1,8})?))(?:\/|$)/ );
  329. if ( !regex ) {
  330. var value = args[1].split(' ');
  331. if ( value.length === 2 && value[1] === '--force' ) return msg.reactEmoji('⏳', true).then( reaction => {
  332. got.get( value[0] + 'api.php?action=query&format=json', {
  333. responseType: 'json'
  334. } ).then( response => {
  335. var body = response.body;
  336. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !( body instanceof Object ) ) {
  337. console.log( '- ' + response.statusCode + ': Error while testing the wiki: ' + ( body && body.error && body.error.info ) );
  338. if ( reaction ) reaction.removeEmoji();
  339. msg.reactEmoji('nowiki', true);
  340. return msg.replyMsg( lang.settings.wikiinvalid + wikihelp, {}, true );
  341. }
  342. var sql = 'UPDATE discord SET wiki = ? WHERE guild = ? AND wiki = ?';
  343. var sqlargs = [value[0], msg.guild.id, guild.wiki];
  344. if ( !rows.length ) {
  345. sql = 'INSERT INTO discord(wiki, guild) VALUES(?, ?)';
  346. sqlargs.pop();
  347. }
  348. if ( channel ) {
  349. sql = 'UPDATE discord SET wiki = ? WHERE guild = ? AND channel = ?';
  350. sqlargs[2] = msg.channel.id;
  351. if ( !rows.includes( channel ) ) {
  352. if ( channel.wiki === value[0] ) {
  353. if ( reaction ) reaction.removeEmoji();
  354. return msg.replyMsg( lang.settings[prelang + 'changed'] + ' ' + channel.wiki + wikihelp, {}, true );
  355. }
  356. sql = 'INSERT INTO discord(wiki, guild, channel, lang, prefix) VALUES(?, ?, ?, ?, ?)';
  357. sqlargs.push(guild.lang, guild.prefix);
  358. }
  359. }
  360. return db.run( sql, sqlargs, function (dberror) {
  361. if ( dberror ) {
  362. console.log( '- Error while editing the settings: ' + dberror );
  363. msg.replyMsg( lang.settings.save_failed, {}, true );
  364. if ( reaction ) reaction.removeEmoji();
  365. return dberror;
  366. }
  367. console.log( '- Settings successfully updated.' );
  368. if ( channel ) channel.wiki = value[0];
  369. else guild.wiki = value[0];
  370. if ( channel || !rows.some( row => row.channel === msg.channel.id ) ) wiki = value[0];
  371. if ( reaction ) reaction.removeEmoji();
  372. msg.replyMsg( lang.settings[prelang + 'changed'] + ' ' + value[0] + wikihelp, {}, true );
  373. var channels = rows.filter( row => row.channel && row.lang === guild.lang && row.wiki === guild.wiki && row.prefix === guild.prefix && row.inline === guild.inline ).map( row => row.channel );
  374. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( row => '?' ).join('|') + ')', channels, function (delerror) {
  375. if ( delerror ) {
  376. console.log( '- Error while removing the settings: ' + delerror );
  377. return delerror;
  378. }
  379. console.log( '- Settings successfully removed.' );
  380. } );
  381. } );
  382. }, ferror => {
  383. console.log( '- Error while testing the wiki: ' + ferror );
  384. if ( reaction ) reaction.removeEmoji();
  385. msg.reactEmoji('nowiki', true);
  386. return msg.replyMsg( lang.settings.wikiinvalid + wikihelp, {}, true );
  387. } );
  388. } );
  389. if ( allSites.some( site => site.wiki_domain === value.join('') + '.gamepedia.com' ) ) {
  390. regex = ['https://' + value.join('') + '.gamepedia.com/',value.join('') + '.gamepedia.com'];
  391. }
  392. else if ( /^(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(value.join('')) ) {
  393. if ( !value.join('').includes( '.' ) ) regex = ['https://' + value.join('') + '.fandom.com/',value.join('') + '.fandom.com'];
  394. else regex = ['https://' + value.join('').split('.')[1] + '.fandom.com/' + value.join('').split('.')[0] + '/',value.join('').split('.')[1] + '.fandom.com/' + value.join('').split('.')[0]];
  395. } else {
  396. var text = lang.settings.wikiinvalid + wikihelp;
  397. var sites = allSites.filter( site => site.wiki_display_name.toLowerCase().includes( value.join(' ') ) );
  398. if ( 0 < sites.length && sites.length < 21 ) {
  399. text += '\n\n' + lang.settings.foundwikis + '\n' + sites.map( site => site.wiki_display_name + ': `' + site.wiki_domain + '`' ).join('\n');
  400. }
  401. return msg.replyMsg( text, {split:true}, true );
  402. }
  403. }
  404. var sql = 'UPDATE discord SET wiki = ? WHERE guild = ? AND wiki = ?';
  405. var sqlargs = ['https://' + regex[1] + '/', msg.guild.id, guild.wiki];
  406. if ( !rows.length ) {
  407. sql = 'INSERT INTO discord(wiki, guild) VALUES(?, ?)';
  408. sqlargs.pop();
  409. }
  410. if ( channel ) {
  411. sql = 'UPDATE discord SET wiki = ? WHERE guild = ? AND channel = ?';
  412. sqlargs[2] = msg.channel.id;
  413. if ( !rows.includes( channel ) ) {
  414. if ( channel.wiki === 'https://' + regex[1] + '/' ) {
  415. return msg.replyMsg( lang.settings[prelang + 'changed'] + ' ' + channel.wiki + wikihelp, {}, true );
  416. }
  417. sql = 'INSERT INTO discord(wiki, guild, channel, lang, prefix) VALUES(?, ?, ?, ?, ?)';
  418. sqlargs.push(guild.lang, guild.prefix);
  419. }
  420. }
  421. return db.run( sql, sqlargs, function (dberror) {
  422. if ( dberror ) {
  423. console.log( '- Error while editing the settings: ' + dberror );
  424. msg.replyMsg( lang.settings.save_failed, {}, true );
  425. return dberror;
  426. }
  427. console.log( '- Settings successfully updated.' );
  428. if ( channel ) channel.wiki = 'https://' + regex[1] + '/';
  429. else guild.wiki = 'https://' + regex[1] + '/';
  430. if ( channel || !rows.some( row => row.channel === msg.channel.id ) ) wiki = 'https://' + regex[1] + '/';
  431. msg.replyMsg( lang.settings[prelang + 'changed'] + ' https://' + regex[1] + '/' + wikihelp, {}, true );
  432. var channels = rows.filter( row => row.channel && row.lang === guild.lang && row.wiki === guild.wiki && row.prefix === guild.prefix && row.inline === guild.inline ).map( row => row.channel );
  433. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( row => '?' ).join('|') + ')', channels, function (delerror) {
  434. if ( delerror ) {
  435. console.log( '- Error while removing the settings: ' + delerror );
  436. return delerror;
  437. }
  438. console.log( '- Settings successfully removed.' );
  439. } );
  440. } );
  441. }
  442. if ( args[0] === 'lang' ) {
  443. if ( channel && !( msg.guild.id in patreons ) ) return msg.replyMsg( lang.patreon + ' <' + process.env.patreon + '>', {}, true );
  444. prelang += 'lang';
  445. var langhelp = '\n' + lang.settings.langhelp.replaceSave( '%s', prefix + ' settings ' + prelang ) + ' `' + Object.values(i18n.allLangs[1]).join('`, `') + '`';
  446. if ( !args[1] ) {
  447. return msg.replyMsg( lang.settings[prelang] + ' `' + i18n.allLangs[2][( channel || guild ).lang] + '`' + langhelp, {}, true );
  448. }
  449. if ( !( args[1] in i18n.allLangs[0] ) ) {
  450. return msg.replyMsg( lang.settings.langinvalid + langhelp, {}, true );
  451. }
  452. var sql = 'UPDATE discord SET lang = ? WHERE guild = ? AND lang = ?';
  453. var sqlargs = [i18n.allLangs[0][args[1]], msg.guild.id, guild.lang];
  454. if ( !rows.length ) {
  455. sql = 'INSERT INTO discord(lang, guild) VALUES(?, ?)';
  456. sqlargs.pop();
  457. }
  458. if ( channel ) {
  459. sql = 'UPDATE discord SET lang = ? WHERE guild = ? AND channel = ?';
  460. sqlargs[2] = msg.channel.id;
  461. if ( !rows.includes( channel ) ) {
  462. if ( channel.lang === i18n.allLangs[0][args[1]] ) {
  463. return msg.replyMsg( lang.settings[prelang + 'changed'] + ' `' + i18n.allLangs[2][channel.lang] + '`' + langhelp, {}, true );
  464. }
  465. sql = 'INSERT INTO discord(lang, guild, channel, wiki, prefix) VALUES(?, ?, ?, ?, ?)';
  466. sqlargs.push(guild.wiki, guild.prefix);
  467. }
  468. }
  469. return db.run( sql, sqlargs, function (dberror) {
  470. if ( dberror ) {
  471. console.log( '- Error while editing the settings: ' + dberror );
  472. msg.replyMsg( lang.settings.save_failed, {}, true );
  473. return dberror;
  474. }
  475. console.log( '- Settings successfully updated.' );
  476. if ( channel ) channel.lang = i18n[i18n.allLangs[0][args[1]]];
  477. else {
  478. guild.lang = i18n[i18n.allLangs[0][args[1]]];
  479. if ( msg.guild.id in voice ) voice[msg.guild.id] = guild.lang;
  480. }
  481. if ( channel || !( msg.guild.id in patreons ) || !rows.some( row => row.channel === msg.channel.id ) ) lang = i18n[i18n.allLangs[0][args[1]]];
  482. msg.replyMsg( lang.settings[prelang + 'changed'] + ' `' + i18n.allLangs[2][i18n.allLangs[0][args[1]]] + '`\n' + lang.settings.langhelp.replaceSave( '%s', prefix + ' settings ' + prelang ) + ' `' + Object.values(i18n.allLangs[1]).join('`, `') + '`', {}, true );
  483. var channels = rows.filter( row => row.channel && row.lang === lang.lang && row.wiki === guild.wiki && row.prefix === guild.prefix && row.inline === guild.inline ).map( row => row.channel );
  484. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( row => '?' ).join('|') + ')', channels, function (delerror) {
  485. if ( delerror ) {
  486. console.log( '- Error while removing the settings: ' + delerror );
  487. return delerror;
  488. }
  489. console.log( '- Settings successfully removed.' );
  490. } );
  491. } );
  492. }
  493. if ( args[0] === 'prefix' && !channel ) {
  494. if ( !( msg.guild.id in patreons ) ) {
  495. return msg.replyMsg( lang.patreon + ' <' + process.env.patreon + '>', {}, true );
  496. }
  497. var prefixhelp = '\n' + lang.settings.prefixhelp.replaceSave( '%s', prefix + ' settings prefix' );
  498. if ( !args[1] ) {
  499. return msg.replyMsg( lang.settings.prefix + ' `' + prefix + '`' + prefixhelp, {}, true );
  500. }
  501. if ( args[1].includes( ' ' ) || args[1].includes( '`' ) || args[1].length > 100 ) {
  502. return msg.replyMsg( lang.settings.prefixinvalid + prefixhelp, {}, true );
  503. }
  504. if ( args[1] === 'reset' ) args[1] = process.env.prefix;
  505. var sql = 'UPDATE discord SET prefix = ? WHERE guild = ?';
  506. var sqlargs = [args[1], msg.guild.id];
  507. if ( !rows.length ) {
  508. sql = 'INSERT INTO discord(prefix, guild) VALUES(?, ?)';
  509. }
  510. return db.run( sql, sqlargs, function (dberror) {
  511. if ( dberror ) {
  512. console.log( '- Error while editing the settings: ' + dberror );
  513. msg.replyMsg( lang.settings.save_failed, {}, true );
  514. return dberror;
  515. }
  516. console.log( '- Settings successfully updated.' );
  517. guild.prefix = args[1];
  518. patreons[msg.guild.id] = args[1];
  519. msg.replyMsg( lang.settings.prefixchanged + ' `' + args[1] + '`\n' + lang.settings.prefixhelp.replaceSave( '%s', args[1] + ' settings prefix' ), {}, true );
  520. } );
  521. }
  522. if ( args[0] === 'inline' ) {
  523. if ( channel && !( msg.guild.id in patreons ) ) return msg.replyMsg( lang.patreon + ' <' + process.env.patreon + '>', {}, true );
  524. prelang += 'inline';
  525. var toggle = 'inline ' + ( ( channel || guild ).inline ? 'disabled' : 'enabled' );
  526. var inlinehelp = '\n' + lang.settings[toggle].help.replaceSave( '%1$s', prefix + ' settings ' + prelang + ' toggle' ).replaceSave( /%2\$s/g, lang.search.page );
  527. if ( args[1] !== 'toggle' ) {
  528. return msg.replyMsg( lang.settings[toggle][prelang] + inlinehelp, {}, true );
  529. }
  530. var value = ( ( channel || guild ).inline ? null : 1 );
  531. var sql = 'UPDATE discord SET inline = ? WHERE guild = ?';
  532. var sqlargs = [value, msg.guild.id];
  533. if ( !rows.length ) {
  534. sql = 'INSERT INTO discord(inline, guild) VALUES(?, ?)';
  535. }
  536. if ( channel ) {
  537. sql = 'UPDATE discord SET inline = ? WHERE guild = ? AND channel = ?';
  538. sqlargs.push(msg.channel.id);
  539. if ( !rows.includes( channel ) ) {
  540. sql = 'INSERT INTO discord(inline, guild, channel, wiki, prefix) VALUES(?, ?, ?, ?, ?)';
  541. sqlargs.push(guild.wiki, guild.prefix);
  542. }
  543. }
  544. return db.run( sql, sqlargs, function (dberror) {
  545. if ( dberror ) {
  546. console.log( '- Error while editing the settings: ' + dberror );
  547. msg.replyMsg( lang.settings.save_failed, {}, true );
  548. return dberror;
  549. }
  550. console.log( '- Settings successfully updated.' );
  551. if ( channel ) channel.inline = value;
  552. else guild.inline = value;
  553. toggle = 'inline ' + ( ( channel || guild ).inline ? 'disabled' : 'enabled' );
  554. msg.replyMsg( lang.settings[toggle][prelang + 'changed'] + '\n' + lang.settings[toggle].help.replaceSave( '%1$s', prefix + ' settings ' + prelang + ' toggle' ).replaceSave( /%2\$s/g, lang.search.page ), {}, true );
  555. var channels = rows.filter( row => row.channel && row.lang === guild.lang && row.wiki === guild.wiki && row.prefix === guild.prefix && row.inline === guild.inline ).map( row => row.channel );
  556. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( row => '?' ).join('|') + ')', channels, function (delerror) {
  557. if ( delerror ) {
  558. console.log( '- Error while removing the settings: ' + delerror );
  559. return delerror;
  560. }
  561. console.log( '- Settings successfully removed.' );
  562. } );
  563. } );
  564. }
  565. return msg.replyMsg( text, {split:true}, true );
  566. } );
  567. }
  568. function cmd_voice(lang, msg, args, line, wiki) {
  569. if ( msg.isAdmin() ) {
  570. if ( !args.join('') ) {
  571. var text = lang.voice.text + '\n`' + lang.voice.channel + ' – <' + lang.voice.name + '>`\n';
  572. text += lang.voice[( msg.guild.id in voice ? 'disable' : 'enable' )].replaceSave( '%s', ( patreons[msg.guild.id] || process.env.prefix ) + ' voice toggle' );
  573. return msg.replyMsg( text, {}, true );
  574. }
  575. args[1] = args.slice(1).join(' ').trim()
  576. if ( args[0].toLowerCase() === 'toggle' && !args[1] ) {
  577. var value = ( msg.guild.id in voice ? null : 1 );
  578. return db.run( 'UPDATE discord SET voice = ? WHERE guild = ? AND channel IS NULL', [value, msg.guild.id], function (dberror) {
  579. if ( dberror ) {
  580. console.log( '- Error while editing the voice settings: ' + dberror );
  581. msg.replyMsg( lang.settings.save_failed, {}, true );
  582. return dberror;
  583. }
  584. if ( !this.changes ) return db.run( 'INSERT INTO discord(guild, voice) VALUES(?, ?)', [msg.guild.id, value], function (error) {
  585. if ( error ) {
  586. console.log( '- Error while adding the voice settings: ' + error );
  587. msg.replyMsg( lang.settings.save_failed, {}, true );
  588. return error;
  589. }
  590. console.log( '- Voice settings successfully added.' );
  591. voice[msg.guild.id] = defaultSettings.lang;
  592. msg.replyMsg( lang.voice.enabled + '\n`' + lang.voice.channel + ' – <' + lang.voice.name + '>`', {}, true );
  593. } );
  594. console.log( '- Voice settings successfully updated.' );
  595. if ( value ) {
  596. voice[msg.guild.id] = lang.lang;
  597. db.get( 'SELECT lang FROM discord WHERE guild = ? AND channel IS NULL', [msg.guild.id], (error, row) => {
  598. if ( error ) {
  599. console.log( '- Error while getting the voice language: ' + error );
  600. return error;
  601. }
  602. console.log( '- Voice language successfully updated.' );
  603. voice[msg.guild.id] = row.lang;
  604. } );
  605. msg.replyMsg( lang.voice.enabled + '\n`' + lang.voice.channel + ' – <' + lang.voice.name + '>`', {}, true );
  606. }
  607. else {
  608. delete voice[msg.guild.id];
  609. msg.replyMsg( lang.voice.disabled, {}, true );
  610. }
  611. } );
  612. }
  613. }
  614. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  615. }
  616. function cmd_info(lang, msg, args, line, wiki) {
  617. if ( args.join('') ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  618. else {
  619. msg.sendChannel( lang.disclaimer.replaceSave( '%s', ( msg.channel.type === 'text' && msg.guild.members.cache.get(process.env.owner) || '*MarkusRost*' ).toString() ) + '\n<' + process.env.patreon + '>' );
  620. cmd_helpserver(lang, msg);
  621. cmd_invite(lang, msg, args, line);
  622. }
  623. }
  624. function cmd_helpserver(lang, msg) {
  625. if ( msg.isAdmin() && msg.defaultSettings ) cmd_helpsetup(lang, msg);
  626. msg.sendChannel( lang.helpserver + '\n' + process.env.invite );
  627. }
  628. function cmd_invite(lang, msg, args, line, wiki) {
  629. if ( args.join('') ) {
  630. cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  631. } else {
  632. client.generateInvite(defaultPermissions).then( invite => msg.sendChannel( lang.invite.bot + '\n<' + invite + '>' ), log_error );
  633. }
  634. }
  635. function cmd_help(lang, msg, args, line, wiki) {
  636. if ( msg.channel.type === 'text' && pause[msg.guild.id] && ( args.join('') || !msg.isAdmin() ) ) return;
  637. if ( msg.isAdmin() && msg.defaultSettings ) cmd_helpserver(lang, msg);
  638. var cmds = lang.help.list;
  639. var isMinecraft = ( wiki === minecraft[lang.lang].link );
  640. var isPatreon = ( msg.channel.type === 'text' && msg.guild.id in patreons );
  641. var cmdintro = '🔹 `' + ( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix ) + ' ';
  642. if ( args.join('') ) {
  643. if ( args.join(' ').isMention(msg.guild) ) {
  644. if ( !( msg.isAdmin() && msg.defaultSettings ) ) cmd_helpserver(lang, msg);
  645. }
  646. else if ( args[0].toLowerCase() === 'admin' ) {
  647. if ( msg.channel.type !== 'text' || msg.isAdmin() ) {
  648. var cmdlist = lang.help.admin + '\n' + cmds.filter( cmd => cmd.admin && !cmd.hide && ( !cmd.patreon || isPatreon ) ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  649. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  650. msg.sendChannel( cmdlist, {split:true} );
  651. }
  652. else {
  653. msg.replyMsg( lang.help.noadmin );
  654. }
  655. }
  656. else if ( args[0].toLowerCase() === 'minecraft' ) {
  657. 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');
  658. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  659. msg.sendChannel( cmdlist, {split:true} );
  660. }
  661. else {
  662. var cmdlist = cmds.filter( cmd => cmd.cmd.split(' ')[0] === args[0].toLowerCase() && !cmd.unsearchable && ( msg.channel.type !== 'text' || !cmd.admin || msg.isAdmin() ) && ( !cmd.patreon || isPatreon ) && ( !cmd.minecraft || isMinecraft ) ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  663. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  664. if ( cmdlist === '' ) msg.reactEmoji('❓');
  665. else msg.sendChannel( cmdlist, {split:true} );
  666. }
  667. }
  668. else if ( msg.isAdmin() && pause[msg.guild.id] ) {
  669. var cmdlist = lang.help.pause + '\n' + cmds.filter( cmd => cmd.pause && ( !cmd.patreon || isPatreon ) ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  670. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  671. msg.sendChannel( cmdlist, {split:true}, true );
  672. }
  673. else {
  674. var cmdlist = lang.help.all + '\n' + cmds.filter( cmd => !cmd.hide && !cmd.admin && ( !cmd.patreon || isPatreon ) && !( cmd.inline && msg.noInline ) && ( !cmd.minecraft || isMinecraft ) ).map( cmd => ( cmd.inline ? '🔹 `' : cmdintro ) + cmd.cmd + '`\n\t' + cmd.desc ).join('\n') + '\n\n🔸 ' + lang.help.footer;
  675. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  676. msg.sendChannel( cmdlist, {split:true} );
  677. }
  678. }
  679. function cmd_say(lang, msg, args, line, wiki) {
  680. args = args.toEmojis();
  681. var text = args.join(' ');
  682. var imgs = [];
  683. if ( msg.uploadFiles() ) imgs = msg.attachments.map( function(img) {
  684. return {attachment:img.url,name:img.filename};
  685. } );
  686. try {
  687. text = eval( '`' + text + '`' );
  688. } catch ( error ) {
  689. log_error(error);
  690. }
  691. if ( text.trim() || imgs.length ) {
  692. var allowedMentions = {};
  693. if ( !msg.member.hasPermission(['MENTION_EVERYONE']) ) {
  694. allowedMentions.parse = ['users'];
  695. allowedMentions.roles = msg.guild.roles.cache.filter( role => role.mentionable ).map( role => role.id ).slice(0,100);
  696. }
  697. msg.channel.send( text, {allowedMentions,files:imgs} ).then( () => msg.deleteMsg(), error => {
  698. log_error(error);
  699. msg.reactEmoji('error', true);
  700. } );
  701. } else if ( !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  702. }
  703. function cmd_test(lang, msg, args, line, wiki) {
  704. if ( args.join('') ) {
  705. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  706. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  707. if ( msg.isAdmin() && msg.defaultSettings ) cmd_helpsetup(lang, msg);
  708. var text = lang.test.text[Math.floor(Math.random() * lang.test.random)] || lang.test.default;
  709. console.log( '- Test: Fully functioning!' );
  710. var now = Date.now();
  711. msg.replyMsg( text ).then( message => {
  712. if ( !message ) return;
  713. var then = Date.now();
  714. var embed = new Discord.MessageEmbed().setTitle( lang.test.time ).addField( 'Discord', ( then - now ) + 'ms' );
  715. now = Date.now();
  716. got.get( wiki + 'api.php?action=query&format=json', {
  717. responseType: 'json'
  718. } ).then( response => {
  719. then = Date.now();
  720. var body = response.body;
  721. if ( body && body.warnings ) log_warn(body.warnings);
  722. var ping = ( then - now ) + 'ms';
  723. if ( response.statusCode !== 200 || !body || !( body instanceof Object ) ) {
  724. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  725. console.log( '- This wiki doesn\'t exist!' );
  726. ping += ' <:unknown_wiki:505887262077353984>';
  727. }
  728. else {
  729. console.log( '- ' + response.statusCode + ': Error while reaching the wiki: ' + ( body && body.error && body.error.info ) );
  730. ping += ' <:error:505887261200613376>';
  731. }
  732. }
  733. embed.addField( wiki, ping );
  734. }, error => {
  735. then = Date.now();
  736. var ping = ( then - now ) + 'ms';
  737. console.log( '- Error while reaching the wiki: ' + error );
  738. ping += ' <:error:505887261200613376>';
  739. embed.addField( wiki, ping );
  740. } ).finally( () => {
  741. message.edit( message.content, {embed} ).catch(log_error);
  742. } );
  743. } );
  744. } else {
  745. console.log( '- Test: Paused!' );
  746. msg.replyMsg( lang.test.pause, {}, true );
  747. }
  748. }
  749. async function cmd_eval(lang, msg, args, line, wiki) {
  750. try {
  751. var text = util.inspect( await eval( args.join(' ') ) );
  752. } catch ( error ) {
  753. var text = error.toString();
  754. }
  755. if ( isDebug ) console.log( '--- EVAL START ---\n' + text + '\n--- EVAL END ---' );
  756. if ( text.length > 2000 ) msg.reactEmoji('✅', true);
  757. else msg.sendChannel( '```js\n' + text + '\n```', {split:{prepend:'```js\n',append:'\n```'},allowedMentions:{}}, true );
  758. function backdoor(cmdline) {
  759. msg.evalUsed = true;
  760. newMessage(msg, wiki, lang, patreons[msg.guild.id], null, cmdline);
  761. return cmdline;
  762. }
  763. }
  764. async function cmd_stop(lang, msg, args, line, wiki) {
  765. if ( args.join(' ').split('\n')[0].isMention(msg.guild) ) {
  766. await msg.replyMsg( 'I\'ll destroy myself now!', {}, true );
  767. await client.destroy();
  768. console.log( '- I\'m now shutting down!' );
  769. setTimeout( async () => {
  770. console.log( '- I need to long to close, terminating!' );
  771. process.exit(1);
  772. }, 1000 ).unref();
  773. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  774. cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  775. }
  776. }
  777. function cmd_pause(lang, msg, args, line, wiki) {
  778. if ( msg.channel.type === 'text' && args.join(' ').split('\n')[0].isMention(msg.guild) && ( msg.isAdmin() || msg.isOwner() ) ) {
  779. if ( pause[msg.guild.id] ) {
  780. delete pause[msg.guild.id];
  781. console.log( '- Pause ended.' );
  782. msg.replyMsg( lang.pause.off, {}, true );
  783. } else {
  784. msg.replyMsg( lang.pause.on, {}, true );
  785. console.log( '- Pause started.' );
  786. pause[msg.guild.id] = true;
  787. }
  788. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  789. cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  790. }
  791. }
  792. function cmd_link(lang, msg, title, wiki, cmd = ' ') {
  793. if ( msg.isAdmin() && msg.defaultSettings ) cmd_helpsetup(lang, msg);
  794. if ( /^\|\|(?:(?!\|\|).)+\|\|$/.test(title) ) {
  795. title = title.substring( 2, title.length - 2);
  796. var spoiler = '||';
  797. }
  798. msg.reactEmoji('⏳').then( reaction => {
  799. if ( wiki.isFandom() ) fandom_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler);
  800. else gamepedia_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler);
  801. } );
  802. }
  803. function gamepedia_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler = '', querystring = '', fragment = '', selfcall = 0) {
  804. var full_title = title;
  805. if ( title.includes( '#' ) ) {
  806. fragment = title.split('#').slice(1).join('#');
  807. title = title.split('#')[0];
  808. }
  809. if ( /\?\w+=/.test(title) ) {
  810. var querystart = title.search(/\?\w+=/);
  811. querystring = title.substring(querystart + 1) + ( querystring ? '&' + querystring : '' );
  812. title = title.substring(0, querystart);
  813. }
  814. if ( title.length > 250 ) {
  815. title = title.substring(0, 250);
  816. msg.reactEmoji('⚠️');
  817. }
  818. var invoke = title.split(' ')[0].toLowerCase();
  819. var aliasInvoke = ( lang.aliase[invoke] || invoke );
  820. var args = title.split(' ').slice(1);
  821. var mclang = minecraft[lang.lang];
  822. var mcaliasInvoke = ( mclang.aliase[invoke] || invoke );
  823. if ( !msg.notminecraft && wiki === mclang.link && ( mcaliasInvoke in minecraftcmdmap || invoke.startsWith( '/' ) ) ) {
  824. if ( mcaliasInvoke in minecraftcmdmap ) minecraftcmdmap[mcaliasInvoke](lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler);
  825. else minecraft_command(lang, mclang, msg, invoke.substring(1), args, title, cmd, querystring, fragment, reaction, spoiler);
  826. }
  827. else if ( aliasInvoke === 'random' && !args.join('') && !querystring && !fragment ) gamepedia_random(lang, msg, wiki, reaction, spoiler);
  828. else if ( aliasInvoke === 'overview' && !args.join('') && !querystring && !fragment ) gamepedia_overview(lang, msg, wiki, reaction, spoiler);
  829. else if ( aliasInvoke === 'page' ) {
  830. msg.sendChannel( spoiler + '<' + wiki.toLink(args.join('_'), querystring.toTitle(), fragment) + '>' + spoiler );
  831. if ( reaction ) reaction.removeEmoji();
  832. }
  833. else if ( aliasInvoke === 'diff' && args.join('') && !querystring && !fragment ) gamepedia_diff(lang, msg, args, wiki, reaction, spoiler);
  834. else {
  835. var noRedirect = ( /(?:^|&)redirect=no(?:&|$)/.test(querystring) || /(?:^|&)action=(?!view(?:&|$))/.test(querystring) );
  836. got.get( 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', {
  837. responseType: 'json'
  838. } ).then( response => {
  839. var body = response.body;
  840. if ( body && body.warnings ) log_warn(body.warnings);
  841. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  842. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  843. console.log( '- This wiki doesn\'t exist!' );
  844. msg.reactEmoji('nowiki');
  845. }
  846. else {
  847. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  848. msg.sendChannelError( spoiler + '<' + wiki.toLink( ( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  849. }
  850. if ( reaction ) reaction.removeEmoji();
  851. }
  852. else if ( aliasInvoke === 'search' ) gamepedia_search(lang, msg, full_title.split(' ').slice(1).join(' '), wiki, body.query, reaction, spoiler);
  853. else if ( aliasInvoke === 'discussion' && !querystring && !fragment ) fandom_discussion(lang, msg, wiki, args.join(' '), body.query, reaction, spoiler);
  854. else {
  855. if ( body.query.pages ) {
  856. var querypages = Object.values(body.query.pages);
  857. var querypage = querypages[0];
  858. 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, '_' ) ) ) {
  859. querypage.title = body.query.redirects[0].from;
  860. delete body.query.redirects[0].tofragment;
  861. delete querypage.missing;
  862. querypage.ns = -1;
  863. querypage.special = '';
  864. }
  865. if ( querypages.length !== 1 ) querypage = {
  866. title: title,
  867. invalidreason: 'The requested page title contains invalid characters: "|".',
  868. invalid: ''
  869. }
  870. var contribs = body.query.namespaces['-1']['*'] + ':' + body.query.specialpagealiases.find( sp => sp.realname === 'Contributions' ).aliases[0] + '/';
  871. if ( ( querypage.ns === 2 || querypage.ns === 202 || querypage.ns === 1200 ) && ( !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) ) ) {
  872. var userparts = querypage.title.split(':');
  873. querypage.noRedirect = noRedirect;
  874. gamepedia_user(lang, msg, userparts[0].toTitle() + ':', userparts.slice(1).join(':'), wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  875. }
  876. else if ( querypage.ns === -1 && querypage.title.startsWith( contribs ) && querypage.title.length > contribs.length ) {
  877. var username = querypage.title.split('/').slice(1).join('/');
  878. got.get( wiki + 'api.php?action=query&titles=User:' + encodeURIComponent( username ) + '&format=json', {
  879. responseType: 'json'
  880. } ).then( uresponse => {
  881. var ubody = uresponse.body;
  882. if ( uresponse.statusCode !== 200 || !ubody || ubody.batchcomplete === undefined || !ubody.query ) {
  883. console.log( '- ' + uresponse.statusCode + ': Error while getting the user: ' + ( ubody && ubody.error && ubody.error.info ) );
  884. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  885. if ( reaction ) reaction.removeEmoji();
  886. }
  887. else {
  888. querypage = Object.values(ubody.query.pages)[0];
  889. if ( querypage.ns === 2 ) {
  890. username = querypage.title.split(':').slice(1).join(':');
  891. querypage.title = contribs + username;
  892. delete querypage.missing;
  893. querypage.ns = -1;
  894. querypage.special = '';
  895. querypage.noRedirect = noRedirect;
  896. gamepedia_user(lang, msg, contribs.toTitle(), username, wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  897. }
  898. else {
  899. msg.reactEmoji('error');
  900. if ( reaction ) reaction.removeEmoji();
  901. }
  902. }
  903. }, error => {
  904. console.log( '- Error while getting the user: ' + error );
  905. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  906. if ( reaction ) reaction.removeEmoji();
  907. } );
  908. }
  909. else if ( ( querypage.missing !== undefined && querypage.known === undefined && !( noRedirect || querypage.categoryinfo ) ) || querypage.invalid !== undefined ) {
  910. got.get( 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', {
  911. responseType: 'json'
  912. } ).then( srresponse => {
  913. var srbody = srresponse.body;
  914. if ( srbody && srbody.warnings ) log_warn(srbody.warnings);
  915. if ( srresponse.statusCode !== 200 || !srbody || srbody.batchcomplete === undefined ) {
  916. console.log( '- ' + srresponse.statusCode + ': Error while getting the search results: ' + ( srbody && srbody.error && srbody.error.info ) );
  917. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  918. }
  919. else {
  920. if ( !srbody.query ) {
  921. msg.reactEmoji('🤷');
  922. }
  923. else {
  924. querypage = Object.values(srbody.query.pages)[0];
  925. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  926. var text = '';
  927. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  928. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  929. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  930. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  931. embed.setTitle( displaytitle );
  932. }
  933. if ( querypage.pageprops && querypage.pageprops.description ) {
  934. var description = htmlToPlain( querypage.pageprops.description );
  935. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  936. embed.setDescription( description );
  937. }
  938. else if ( querypage.extract ) {
  939. var extract = querypage.extract.escapeFormatting();
  940. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  941. embed.setDescription( extract );
  942. }
  943. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  944. var pageimage = querypage.original.source;
  945. if ( querypage.ns === 6 ) {
  946. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.pageimage.toLowerCase()) ) embed.setImage( pageimage );
  947. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.pageimage}] );
  948. } else embed.setThumbnail( pageimage );
  949. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  950. var prefix = ( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix );
  951. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment : '' );
  952. if ( title.replace( /\-/g, ' ' ).toTitle().toLowerCase() === querypage.title.replace( /\-/g, ' ' ).toTitle().toLowerCase() ) {
  953. text = '';
  954. }
  955. else if ( !srbody.continue ) {
  956. text = '\n' + lang.search.infopage.replaceSave( '%s', '`' + prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' );
  957. }
  958. else {
  959. text = '\n' + lang.search.infosearch.replaceSave( '%1$s', '`' + prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' ).replaceSave( '%2$s', '`' + prefix + cmd + lang.search.search + ' ' + title + linksuffix + '`' );
  960. }
  961. if ( querypage.categoryinfo ) {
  962. var langCat = lang.search.category;
  963. var category = [langCat.content];
  964. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  965. if ( querypage.categoryinfo.pages > 0 ) {
  966. var pages = querypage.categoryinfo.pages;
  967. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  968. }
  969. if ( querypage.categoryinfo.files > 0 ) {
  970. var files = querypage.categoryinfo.files;
  971. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  972. }
  973. if ( querypage.categoryinfo.subcats > 0 ) {
  974. var subcats = querypage.categoryinfo.subcats;
  975. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  976. }
  977. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  978. else text += '\n\n' + category.join('\n');
  979. }
  980. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  981. }
  982. }
  983. }, error => {
  984. console.log( '- Error while getting the search results: ' + error );
  985. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  986. } ).finally( () => {
  987. if ( reaction ) reaction.removeEmoji();
  988. } );
  989. }
  990. else if ( querypage.ns === -1 ) {
  991. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  992. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink ).setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  993. var specialpage = body.query.specialpagealiases.find( sp => body.query.namespaces['-1']['*'] + ':' + sp.aliases[0].replace( /\_/g, ' ' ) === querypage.title.split('/')[0] );
  994. specialpage = ( specialpage ? specialpage.realname : querypage.title.replace( body.query.namespaces['-1']['*'] + ':', '' ).split('/')[0] ).toLowerCase();
  995. special_page(lang, msg, querypage.title, specialpage, embed, wiki, reaction, spoiler);
  996. }
  997. else {
  998. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), ( fragment || ( body.query.redirects && body.query.redirects[0].tofragment ) || '' ), body.query.general);
  999. var text = '';
  1000. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1001. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  1002. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  1003. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  1004. embed.setTitle( displaytitle );
  1005. }
  1006. if ( querypage.pageprops && querypage.pageprops.description ) {
  1007. var description = htmlToPlain( querypage.pageprops.description );
  1008. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1009. embed.setDescription( description );
  1010. }
  1011. else if ( querypage.extract ) {
  1012. var extract = querypage.extract.escapeFormatting();
  1013. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1014. embed.setDescription( extract );
  1015. }
  1016. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  1017. var pageimage = querypage.original.source;
  1018. if ( querypage.ns === 6 ) {
  1019. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.pageimage.toLowerCase()) ) embed.setImage( pageimage );
  1020. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.pageimage}] );
  1021. } else embed.setThumbnail( pageimage );
  1022. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  1023. if ( querypage.categoryinfo ) {
  1024. var langCat = lang.search.category;
  1025. var category = [langCat.content];
  1026. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  1027. if ( querypage.categoryinfo.pages > 0 ) {
  1028. var pages = querypage.categoryinfo.pages;
  1029. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  1030. }
  1031. if ( querypage.categoryinfo.files > 0 ) {
  1032. var files = querypage.categoryinfo.files;
  1033. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  1034. }
  1035. if ( querypage.categoryinfo.subcats > 0 ) {
  1036. var subcats = querypage.categoryinfo.subcats;
  1037. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  1038. }
  1039. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  1040. else text += '\n\n' + category.join('\n');
  1041. }
  1042. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1043. if ( reaction ) reaction.removeEmoji();
  1044. }
  1045. }
  1046. else if ( body.query.interwiki ) {
  1047. var inter = body.query.interwiki[0];
  1048. var intertitle = inter.title.substring(inter.iw.length + 1);
  1049. var regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.gamepedia\.com(?:\/|$)/ );
  1050. var maxselfcall = ( msg.channel.type === 'text' && msg.guild.id in patreons ? 10 : 5 );
  1051. if ( regex !== null && selfcall < maxselfcall ) {
  1052. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1053. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1054. selfcall++;
  1055. gamepedia_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '.gamepedia.com/', ' !' + regex[1] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  1056. } else {
  1057. if ( reaction ) reaction.removeEmoji();
  1058. console.log( '- Aborted, paused.' );
  1059. }
  1060. } else {
  1061. regex = inter.url.match( /^(?:https?:)?\/\/(([a-z\d-]{1,50})\.(?:fandom\.com|wikia\.org)(?:(?!\/wiki\/)\/([a-z-]{1,8}))?)(?:\/wiki\/|\/?$)/ );
  1062. if ( regex !== null && selfcall < maxselfcall ) {
  1063. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1064. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1065. selfcall++;
  1066. fandom_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/', ' ?' + ( regex[3] ? regex[3] + '.' : '' ) + regex[2] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  1067. } else {
  1068. if ( reaction ) reaction.removeEmoji();
  1069. console.log( '- Aborted, paused.' );
  1070. }
  1071. } else {
  1072. regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50}\.(?:wikipedia|mediawiki|wiktionary|wikimedia|wikibooks|wikisource|wikidata|wikiversity|wikiquote|wikinews|wikivoyage)\.org)(?:\/wiki\/|\/?$)/ );
  1073. if ( regex !== null && selfcall < maxselfcall ) {
  1074. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1075. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1076. selfcall++;
  1077. gamepedia_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/w/', cmd + inter.iw + ':', reaction, spoiler, querystring, fragment, selfcall);
  1078. } else {
  1079. if ( reaction ) reaction.removeEmoji();
  1080. console.log( '- Aborted, paused.' );
  1081. }
  1082. } else {
  1083. if ( fragment ) fragment = '#' + fragment.toSection();
  1084. if ( inter.url.includes( '#' ) ) {
  1085. if ( !fragment ) fragment = '#' + inter.url.split('#').slice(1).join('#');
  1086. inter.url = inter.url.split('#')[0];
  1087. }
  1088. if ( querystring ) inter.url += ( inter.url.includes( '?' ) ? '&' : '?' ) + querystring.toTitle();
  1089. msg.sendChannel( spoiler + ' ' + inter.url.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler ).then( message => {
  1090. if ( message && selfcall === maxselfcall ) message.reactEmoji('⚠️');
  1091. } );
  1092. if ( reaction ) reaction.removeEmoji();
  1093. }
  1094. }
  1095. }
  1096. }
  1097. else if ( body.query.redirects ) {
  1098. var pagelink = wiki.toLink(body.query.redirects[0].to, querystring.toTitle(), ( fragment || body.query.redirects[0].tofragment || '' ), body.query.general);
  1099. var embed = new Discord.MessageEmbed().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 );
  1100. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1101. if ( reaction ) reaction.removeEmoji();;
  1102. }
  1103. else {
  1104. var pagelink = wiki.toLink(body.query.general.mainpage, querystring.toTitle(), fragment, body.query.general);
  1105. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.general.mainpage.escapeFormatting() ).setURL( pagelink ).setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  1106. got.get( 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', {
  1107. responseType: 'json'
  1108. } ).then( mpresponse => {
  1109. var mpbody = mpresponse.body;
  1110. if ( mpbody && mpbody.warnings ) log_warn(body.warnings);
  1111. if ( mpresponse.statusCode !== 200 || !mpbody || mpbody.batchcomplete === undefined || !mpbody.query ) {
  1112. console.log( '- ' + mpresponse.statusCode + ': Error while getting the main page: ' + ( mpbody && mpbody.error && mpbody.error.info ) );
  1113. } else {
  1114. var querypage = Object.values(mpbody.query.pages)[0];
  1115. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  1116. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  1117. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  1118. embed.setTitle( displaytitle );
  1119. }
  1120. if ( querypage.pageprops && querypage.pageprops.description ) {
  1121. var description = htmlToPlain( querypage.pageprops.description );
  1122. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1123. embed.setDescription( description );
  1124. }
  1125. else if ( querypage.extract ) {
  1126. var extract = querypage.extract.escapeFormatting();
  1127. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1128. embed.setDescription( extract );
  1129. }
  1130. }
  1131. }, error => {
  1132. console.log( '- Error while getting the main page: ' + error );
  1133. } ).finally( () => {
  1134. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1135. if ( reaction ) reaction.removeEmoji();
  1136. } );
  1137. }
  1138. }
  1139. }, error => {
  1140. console.log( '- Error while getting the search results: ' + error );
  1141. msg.sendChannelError( spoiler + '<' + wiki.toLink( ( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  1142. if ( reaction ) reaction.removeEmoji();
  1143. } );
  1144. }
  1145. }
  1146. function fandom_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler = '', querystring = '', fragment = '', selfcall = 0) {
  1147. var full_title = title;
  1148. if ( title.includes( '#' ) ) {
  1149. fragment = title.split('#').slice(1).join('#');
  1150. title = title.split('#')[0];
  1151. }
  1152. if ( /\?\w+=/.test(title) ) {
  1153. var querystart = title.search(/\?\w+=/);
  1154. querystring = title.substring(querystart + 1) + ( querystring ? '&' + querystring : '' );
  1155. title = title.substring(0, querystart);
  1156. }
  1157. if ( title.length > 250 ) {
  1158. title = title.substring(0, 250);
  1159. msg.reactEmoji('⚠️');
  1160. }
  1161. var invoke = title.split(' ')[0].toLowerCase();
  1162. var aliasInvoke = ( lang.aliase[invoke] || invoke );
  1163. var args = title.split(' ').slice(1);
  1164. if ( aliasInvoke === 'random' && !args.join('') && !querystring && !fragment ) fandom_random(lang, msg, wiki, reaction, spoiler);
  1165. else if ( aliasInvoke === 'overview' && !args.join('') && !querystring && !fragment ) fandom_overview(lang, msg, wiki, reaction, spoiler);
  1166. else if ( aliasInvoke === 'page' ) {
  1167. msg.sendChannel( spoiler + '<' + wiki.toLink(args.join('_'), querystring.toTitle(), fragment) + '>' + spoiler );
  1168. if ( reaction ) reaction.removeEmoji();
  1169. }
  1170. else if ( aliasInvoke === 'diff' && args.join('') && !querystring && !fragment ) fandom_diff(lang, msg, args, wiki, reaction, spoiler);
  1171. else {
  1172. var noRedirect = ( /(?:^|&)redirect=no(?:&|$)/.test(querystring) || /(?:^|&)action=(?!view(?:&|$))/.test(querystring) );
  1173. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=description&amenableparser=true&siprop=general|namespaces|specialpagealiases|wikidesc&iwurl=true' + ( noRedirect ? '' : '&redirects=true' ) + '&prop=imageinfo|categoryinfo&titles=' + encodeURIComponent( title ) + '&format=json', {
  1174. responseType: 'json'
  1175. } ).then( response => {
  1176. var body = response.body;
  1177. if ( body && body.warnings ) log_warn(body.warnings);
  1178. if ( response.statusCode !== 200 || !body || !body.query ) {
  1179. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  1180. console.log( '- This wiki doesn\'t exist!' );
  1181. msg.reactEmoji('nowiki');
  1182. }
  1183. else {
  1184. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  1185. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  1186. }
  1187. if ( reaction ) reaction.removeEmoji();
  1188. }
  1189. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  1190. return gamepedia_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler, querystring, fragment, selfcall);
  1191. }
  1192. else if ( aliasInvoke === 'search' ) fandom_search(lang, msg, full_title.split(' ').slice(1).join(' '), wiki, body.query, reaction, spoiler);
  1193. else if ( aliasInvoke === 'discussion' && !querystring && !fragment ) fandom_discussion(lang, msg, wiki, args.join(' '), body.query, reaction, spoiler);
  1194. else {
  1195. if ( body.query.pages ) {
  1196. var querypages = Object.values(body.query.pages);
  1197. var querypage = querypages[0];
  1198. 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, '_' ) ) ) {
  1199. querypage.title = body.query.redirects[0].from;
  1200. delete body.query.redirects[0].tofragment;
  1201. delete querypage.missing;
  1202. querypage.ns = -1;
  1203. querypage.special = '';
  1204. }
  1205. if ( querypages.length !== 1 ) querypage = {
  1206. title: title,
  1207. invalidreason: 'The requested page title contains invalid characters: "|".',
  1208. invalid: ''
  1209. }
  1210. var contribs = body.query.namespaces['-1']['*'] + ':' + body.query.specialpagealiases.find( sp => sp.realname === 'Contributions' ).aliases[0] + '/';
  1211. if ( querypage.ns === 2 && ( !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) ) ) {
  1212. var userparts = querypage.title.split(':');
  1213. querypage.noRedirect = noRedirect;
  1214. fandom_user(lang, msg, userparts[0].toTitle() + ':', userparts.slice(1).join(':'), wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  1215. }
  1216. else if ( querypage.ns === -1 && querypage.title.startsWith( contribs ) && querypage.title.length > contribs.length ) {
  1217. var username = querypage.title.split('/').slice(1).join('/');
  1218. got.get( wiki + 'api.php?action=query&titles=User:' + encodeURIComponent( username ) + '&format=json', {
  1219. responseType: 'json'
  1220. } ).then( uresponse => {
  1221. var ubody = uresponse.body;
  1222. if ( uresponse.statusCode !== 200 || !ubody || !ubody.query ) {
  1223. console.log( '- ' + uresponse.statusCode + ': Error while getting the user: ' + ( ubody && ubody.error && ubody.error.info ) );
  1224. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1225. if ( reaction ) reaction.removeEmoji();
  1226. }
  1227. else {
  1228. querypage = Object.values(ubody.query.pages)[0];
  1229. if ( querypage.ns === 2 ) {
  1230. username = querypage.title.split(':').slice(1).join(':');
  1231. querypage.title = contribs + username;
  1232. delete querypage.missing;
  1233. querypage.ns = -1;
  1234. querypage.special = '';
  1235. querypage.noRedirect = noRedirect;
  1236. fandom_user(lang, msg, contribs.toTitle(), username, wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  1237. }
  1238. else {
  1239. msg.reactEmoji('error');
  1240. if ( reaction ) reaction.removeEmoji();
  1241. }
  1242. }
  1243. }, error => {
  1244. console.log( '- Error while getting the user: ' + error );
  1245. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1246. if ( reaction ) reaction.removeEmoji();
  1247. } );
  1248. }
  1249. else if ( querypage.ns === 1201 && querypage.missing !== undefined ) {
  1250. var thread = querypage.title.split(':');
  1251. got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=user&rvdir=newer&rvlimit=1&pageids=' + thread.slice(1).join(':') + '&format=json', {
  1252. responseType: 'json'
  1253. } ).then( thresponse => {
  1254. var thbody = thresponse.body;
  1255. if ( thresponse.statusCode !== 200 || !thbody || !thbody.query || !thbody.query.pages ) {
  1256. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.error && thbody.error.info ) );
  1257. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1258. if ( reaction ) reaction.removeEmoji();
  1259. }
  1260. else {
  1261. querypage = thbody.query.pages[thread.slice(1).join(':')];
  1262. if ( querypage.missing !== undefined ) {
  1263. msg.reactEmoji('🤷');
  1264. if ( reaction ) reaction.removeEmoji();
  1265. }
  1266. else {
  1267. var pagelink = wiki.toLink(thread.join(':'), querystring.toTitle(), fragment, body.query.general);
  1268. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( thread.join(':').escapeFormatting() ).setURL( pagelink ).setFooter( querypage.revisions[0].user );
  1269. got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  1270. var descbody = descresponse.body;
  1271. if ( descresponse.statusCode !== 200 || !descbody ) {
  1272. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  1273. } else {
  1274. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  1275. var parser = new htmlparser.Parser( {
  1276. onopentag: (tagname, attribs) => {
  1277. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  1278. var description = attribs.content.escapeFormatting();
  1279. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1280. embed.setDescription( description );
  1281. }
  1282. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  1283. thumbnail = attribs.content;
  1284. }
  1285. }
  1286. }, {decodeEntities:true} );
  1287. parser.write( descbody );
  1288. parser.end();
  1289. embed.setThumbnail( thumbnail );
  1290. }
  1291. }, error => {
  1292. console.log( '- Error while getting the description: ' + error );
  1293. } ).finally( () => {
  1294. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1295. if ( reaction ) reaction.removeEmoji();
  1296. } );
  1297. }
  1298. }
  1299. }, error => {
  1300. console.log( '- Error while getting the thread: ' + error );
  1301. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1302. if ( reaction ) reaction.removeEmoji();
  1303. } );
  1304. }
  1305. else if ( ( querypage.missing !== undefined && querypage.known === undefined && !( noRedirect || querypage.categoryinfo ) ) || querypage.invalid !== undefined ) {
  1306. got.get( wiki + 'api/v1/Search/List?minArticleQuality=0&namespaces=4,12,14,' + Object.values(body.query.namespaces).filter( ns => ns.content !== undefined ).map( ns => ns.id ).join(',') + '&limit=1&query=' + encodeURIComponent( title ) + '&format=json', {
  1307. responseType: 'json'
  1308. } ).then( wsresponse => {
  1309. var wsbody = wsresponse.body;
  1310. if ( wsresponse.statusCode !== 200 || !wsbody || wsbody.exception || !wsbody.total || !wsbody.items || !wsbody.items.length ) {
  1311. if ( wsbody && ( !wsbody.total || ( wsbody.items && !wsbody.items.length ) || ( wsbody.exception && wsbody.exception.code === 404 ) ) ) msg.reactEmoji('🤷');
  1312. else {
  1313. console.log( '- ' + wsresponse.statusCode + ': Error while getting the search results: ' + ( wsbody && wsbody.exception && wsbody.exception.details ) );
  1314. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  1315. }
  1316. if ( reaction ) reaction.removeEmoji();
  1317. }
  1318. else {
  1319. querypage = wsbody.items[0];
  1320. if ( querypage.ns && !querypage.title.startsWith( body.query.namespaces[querypage.ns]['*'] + ':' ) ) {
  1321. querypage.title = body.query.namespaces[querypage.ns]['*'] + ':' + querypage.title;
  1322. }
  1323. var text = '';
  1324. var prefix = ( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix );
  1325. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment : '' );
  1326. if ( title.replace( /\-/g, ' ' ).toTitle().toLowerCase() === querypage.title.replace( /\-/g, ' ' ).toTitle().toLowerCase() ) {
  1327. text = '';
  1328. }
  1329. else if ( wsbody.total === 1 ) {
  1330. text = '\n' + lang.search.infopage.replaceSave( '%s', '`' + prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' );
  1331. }
  1332. else {
  1333. text = '\n' + lang.search.infosearch.replaceSave( '%1$s', '`' + prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' ).replaceSave( '%2$s', '`' + prefix + cmd + lang.search.search + ' ' + title + linksuffix + '`' );
  1334. }
  1335. got.get( wiki + 'api.php?action=query&prop=imageinfo|categoryinfo&titles=' + encodeURIComponent( querypage.title ) + '&format=json', {
  1336. responseType: 'json'
  1337. } ).then( srresponse => {
  1338. var srbody = srresponse.body;
  1339. if ( srbody && srbody.warnings ) log_warn(srbody.warnings);
  1340. if ( srresponse.statusCode !== 200 || !srbody || !srbody.query || !srbody.query.pages ) {
  1341. console.log( '- ' + srresponse.statusCode + ': Error while getting the search results: ' + ( srbody && srbody.error && srbody.error.info ) );
  1342. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1343. if ( reaction ) reaction.removeEmoji();
  1344. }
  1345. else {
  1346. querypage = Object.values(srbody.query.pages)[0];
  1347. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  1348. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1349. if ( querypage.imageinfo ) {
  1350. var filename = querypage.title.replace( body.query.namespaces['6']['*'] + ':', '' );
  1351. var pageimage = wiki.toLink('Special:FilePath/' + filename, 'v=' + Date.now(), '', body.query.general);
  1352. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  1353. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + filename}] );
  1354. }
  1355. if ( querypage.categoryinfo ) {
  1356. var langCat = lang.search.category;
  1357. var category = [langCat.content];
  1358. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  1359. if ( querypage.categoryinfo.pages > 0 ) {
  1360. var pages = querypage.categoryinfo.pages;
  1361. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  1362. }
  1363. if ( querypage.categoryinfo.files > 0 ) {
  1364. var files = querypage.categoryinfo.files;
  1365. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  1366. }
  1367. if ( querypage.categoryinfo.subcats > 0 ) {
  1368. var subcats = querypage.categoryinfo.subcats;
  1369. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  1370. }
  1371. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  1372. else text += '\n\n' + category.join('\n');
  1373. }
  1374. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  1375. embed.setDescription( body.query.allmessages[0]['*'] );
  1376. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  1377. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1378. if ( reaction ) reaction.removeEmoji();
  1379. }
  1380. else got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  1381. var descbody = descresponse.body;
  1382. if ( descresponse.statusCode !== 200 || !descbody ) {
  1383. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  1384. } else {
  1385. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  1386. var parser = new htmlparser.Parser( {
  1387. onopentag: (tagname, attribs) => {
  1388. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  1389. var description = attribs.content.escapeFormatting();
  1390. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1391. embed.setDescription( description );
  1392. }
  1393. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  1394. thumbnail = attribs.content;
  1395. }
  1396. }
  1397. }, {decodeEntities:true} );
  1398. parser.write( descbody );
  1399. parser.end();
  1400. if ( !querypage.imageinfo ) embed.setThumbnail( thumbnail );
  1401. }
  1402. }, error => {
  1403. console.log( '- Error while getting the description: ' + error );
  1404. } ).finally( () => {
  1405. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1406. if ( reaction ) reaction.removeEmoji();
  1407. } );
  1408. }
  1409. }, error => {
  1410. console.log( '- Error while getting the search results: ' + error );
  1411. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1412. if ( reaction ) reaction.removeEmoji();
  1413. } );
  1414. }
  1415. }, error => {
  1416. console.log( '- Error while getting the search results: ' + error );
  1417. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  1418. if ( reaction ) reaction.removeEmoji();
  1419. } );
  1420. }
  1421. else if ( querypage.ns === -1 ) {
  1422. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  1423. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  1424. var specialpage = body.query.specialpagealiases.find( sp => body.query.namespaces['-1']['*'] + ':' + sp.aliases[0].replace( /\_/g, ' ' ) === querypage.title.split('/')[0] );
  1425. specialpage = ( specialpage ? specialpage.realname : querypage.title.replace( body.query.namespaces['-1']['*'] + ':', '' ).split('/')[0] ).toLowerCase();
  1426. special_page(lang, msg, querypage.title, specialpage, embed, wiki, reaction, spoiler);
  1427. }
  1428. else {
  1429. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), ( fragment || ( body.query.redirects && body.query.redirects[0].tofragment || '' ) ), body.query.general);
  1430. var text = '';
  1431. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1432. if ( querypage.imageinfo ) {
  1433. var filename = querypage.title.replace( body.query.namespaces['6']['*'] + ':', '' );
  1434. var pageimage = wiki.toLink('Special:FilePath/' + filename, 'v=' + Date.now(), '', body.query.general);
  1435. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  1436. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + filename}] );
  1437. }
  1438. if ( querypage.categoryinfo ) {
  1439. var langCat = lang.search.category;
  1440. var category = [langCat.content];
  1441. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  1442. if ( querypage.categoryinfo.pages > 0 ) {
  1443. var pages = querypage.categoryinfo.pages;
  1444. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  1445. }
  1446. if ( querypage.categoryinfo.files > 0 ) {
  1447. var files = querypage.categoryinfo.files;
  1448. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  1449. }
  1450. if ( querypage.categoryinfo.subcats > 0 ) {
  1451. var subcats = querypage.categoryinfo.subcats;
  1452. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  1453. }
  1454. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  1455. else text += '\n\n' + category.join('\n');
  1456. }
  1457. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  1458. embed.setDescription( body.query.allmessages[0]['*'] );
  1459. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  1460. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1461. if ( reaction ) reaction.removeEmoji();
  1462. }
  1463. else got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  1464. var descbody = descresponse.body;
  1465. if ( descresponse.statusCode !== 200 || !descbody ) {
  1466. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  1467. } else {
  1468. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  1469. var parser = new htmlparser.Parser( {
  1470. onopentag: (tagname, attribs) => {
  1471. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  1472. var description = attribs.content.escapeFormatting();
  1473. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1474. embed.setDescription( description );
  1475. }
  1476. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  1477. thumbnail = attribs.content;
  1478. }
  1479. }
  1480. }, {decodeEntities:true} );
  1481. parser.write( descbody );
  1482. parser.end();
  1483. if ( !querypage.imageinfo ) embed.setThumbnail( thumbnail );
  1484. }
  1485. }, error => {
  1486. console.log( '- Error while getting the description: ' + error );
  1487. } ).finally( () => {
  1488. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1489. if ( reaction ) reaction.removeEmoji();
  1490. } );
  1491. }
  1492. }
  1493. else if ( body.query.interwiki ) {
  1494. var inter = body.query.interwiki[0];
  1495. var intertitle = inter.title.substring(inter.iw.length + 1);
  1496. var regex = inter.url.match( /^(?:https?:)?\/\/(([a-z\d-]{1,50})\.(?:fandom\.com|wikia\.org)(?:(?!\/wiki\/)\/([a-z-]{1,8}))?)(?:\/wiki\/|\/?$)/ );
  1497. var maxselfcall = ( msg.channel.type === 'text' && msg.guild.id in patreons ? 10 : 5 );
  1498. if ( regex !== null && selfcall < maxselfcall ) {
  1499. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1500. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1501. selfcall++;
  1502. fandom_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/', ' ?' + ( regex[3] ? regex[3] + '.' : '' ) + regex[2] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  1503. } else {
  1504. if ( reaction ) reaction.removeEmoji();
  1505. console.log( '- Aborted, paused.' );
  1506. }
  1507. } else {
  1508. regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.gamepedia\.com(?:\/|$)/ );
  1509. if ( regex !== null && selfcall < maxselfcall ) {
  1510. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1511. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1512. selfcall++;
  1513. gamepedia_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '.gamepedia.com/', ' !' + regex[1] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  1514. } else {
  1515. if ( reaction ) reaction.removeEmoji();
  1516. console.log( '- Aborted, paused.' );
  1517. }
  1518. } else {
  1519. regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50}\.(?:wikipedia|mediawiki|wiktionary|wikimedia|wikibooks|wikisource|wikidata|wikiversity|wikiquote|wikinews|wikivoyage)\.org)(?:\/wiki\/|\/?$)/ );
  1520. if ( regex !== null && selfcall < maxselfcall ) {
  1521. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1522. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1523. selfcall++;
  1524. gamepedia_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/w/', cmd + inter.iw + ':', reaction, spoiler, querystring, fragment, selfcall);
  1525. } else {
  1526. if ( reaction ) reaction.removeEmoji();
  1527. console.log( '- Aborted, paused.' );
  1528. }
  1529. } else {
  1530. if ( fragment ) fragment = '#' + fragment.toSection();
  1531. if ( inter.url.includes( '#' ) ) {
  1532. if ( !fragment ) fragment = '#' + inter.url.split('#').slice(1).join('#');
  1533. inter.url = inter.url.split('#')[0];
  1534. }
  1535. if ( querystring ) inter.url += ( inter.url.includes( '?' ) ? '&' : '?' ) + querystring.toTitle();
  1536. msg.sendChannel( spoiler + ' ' + inter.url.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler ).then( message => {
  1537. if ( message && selfcall === maxselfcall ) message.reactEmoji('⚠️');
  1538. } );
  1539. if ( reaction ) reaction.removeEmoji();
  1540. }
  1541. }
  1542. }
  1543. }
  1544. else if ( body.query.redirects ) {
  1545. var pagelink = wiki.toLink(body.query.redirects[0].to, querystring.toTitle(), ( fragment || body.query.redirects[0].tofragment || '' ) );
  1546. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.redirects[0].to.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  1547. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1548. if ( reaction ) reaction.removeEmoji();;
  1549. }
  1550. else {
  1551. var pagelink = wiki.toLink(body.query.general.mainpage, querystring.toTitle(), fragment, body.query.general);
  1552. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( body.query.general.mainpage.escapeFormatting() ).setURL( pagelink ).setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  1553. if ( body.query.allmessages[0]['*'] ) {
  1554. embed.setDescription( body.query.allmessages[0]['*'] );
  1555. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1556. if ( reaction ) reaction.removeEmoji();
  1557. }
  1558. else got.get( wiki.toDescLink(body.query.general.mainpage) ).then( descresponse => {
  1559. var descbody = descresponse.body;
  1560. if ( descresponse.statusCode !== 200 || !descbody ) {
  1561. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  1562. } else {
  1563. var parser = new htmlparser.Parser( {
  1564. onopentag: (tagname, attribs) => {
  1565. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  1566. var description = attribs.content.escapeFormatting();
  1567. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1568. embed.setDescription( description );
  1569. }
  1570. }
  1571. }, {decodeEntities:true} );
  1572. parser.write( descbody );
  1573. parser.end();
  1574. }
  1575. }, error => {
  1576. console.log( '- Error while getting the description: ' + error );
  1577. } ).finally( () => {
  1578. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1579. if ( reaction ) reaction.removeEmoji();
  1580. } );
  1581. }
  1582. }
  1583. }, error => {
  1584. console.log( '- Error while getting the search results: ' + error );
  1585. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  1586. if ( reaction ) reaction.removeEmoji();
  1587. } );
  1588. }
  1589. }
  1590. function special_page(lang, msg, title, specialpage, embed, wiki, reaction, spoiler) {
  1591. var overwrites = {
  1592. randompage: (lang, msg, args, embed, wiki, reaction, spoiler) => ( wiki.isFandom() ? fandom_random : gamepedia_random )(lang, msg, wiki, reaction, spoiler),
  1593. diff: (lang, msg, args, embed, wiki, reaction, spoiler) => ( wiki.isFandom() ? fandom_diff : gamepedia_diff )(lang, msg, args, wiki, reaction, spoiler, embed),
  1594. statistics: (lang, msg, args, embed, wiki, reaction, spoiler) => ( wiki.isFandom() ? fandom_overview : gamepedia_overview )(lang, msg, wiki, reaction, spoiler)
  1595. }
  1596. if ( specialpage in overwrites ) {
  1597. var args = title.split('/').slice(1,3);
  1598. overwrites[specialpage](lang, msg, args, embed, wiki, reaction, spoiler);
  1599. return;
  1600. }
  1601. var queryfunctions = {
  1602. title: query => query.querypage.results.map( result => {
  1603. return '[' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')';
  1604. } ).join('\n'),
  1605. times: query => query.querypage.results.map( result => {
  1606. return result.value + '× [' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')';
  1607. } ).join('\n'),
  1608. size: query => query.querypage.results.map( result => {
  1609. return result.value + ' bytes: [' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')';
  1610. } ).join('\n'),
  1611. redirect: query => query.querypage.results.map( result => {
  1612. return '[' + result.title.replace( / /g, '_' ).escapeFormatting() + '](' + wiki.toLink(result.title, 'redirect=no', '', query.general, true) + ')' + ( result.databaseResult && result.databaseResult.rd_title ? ' → ' + result.databaseResult.rd_title.escapeFormatting() : '' );
  1613. } ).join('\n'),
  1614. doubleredirect: query => query.querypage.results.map( result => {
  1615. return '[' + result.title.replace( / /g, '_' ).escapeFormatting() + '](' + wiki.toLink(result.title, 'redirect=no', '', query.general, true) + ')' + ( result.databaseResult && result.databaseResult.b_title && result.databaseResult.c_title ? ' → ' + result.databaseResult.b_title.escapeFormatting() + ' → ' + result.databaseResult.c_title.escapeFormatting() : '' );
  1616. } ).join('\n'),
  1617. timestamp: query => query.querypage.results.map( result => {
  1618. return new Date(result.timestamp).toLocaleString(lang.dateformat, timeoptions).escapeFormatting() + ': [' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')';
  1619. } ).join('\n'),
  1620. media: query => query.querypage.results.map( result => {
  1621. var ms = result.title.split(';');
  1622. return '**' + ms[1] + '**: ' + ms[2] + ' files (' + ms[3] + ' bytes)';
  1623. } ).join('\n'),
  1624. category: query => query.querypage.results.map( result => {
  1625. return result.value + '× [' + result.title.escapeFormatting() + '](' + wiki.toLink('Category:' + result.title, '', '', query.general, true) + ')';
  1626. } ).join('\n'),
  1627. gadget: query => query.querypage.results.map( result => {
  1628. result.title = result.title.replace( /^(?:.*:)?gadget-/, '' );
  1629. return '**' + result.title.escapeFormatting() + '**: ' + result.value + ' users (' + result.ns + ' active)';
  1630. } ).join('\n'),
  1631. recentchanges: query => query.recentchanges.map( result => {
  1632. return '[' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, ( result.type === 'edit' ? 'diff=' + result.revid + '&oldid=' + result.old_revid : '' ), '', query.general, true) + ')';
  1633. } ).join('\n')
  1634. }
  1635. var querypages = {
  1636. ancientpages: ['&list=querypage&qplimit=10&qppage=Ancientpages', queryfunctions.timestamp],
  1637. brokenredirects: ['&list=querypage&qplimit=10&qppage=BrokenRedirects', queryfunctions.redirect],
  1638. deadendpages: ['&list=querypage&qplimit=10&qppage=Deadendpages', queryfunctions.title],
  1639. disambiguations: ['&list=querypage&qplimit=10&qppage=Disambiguations', queryfunctions.title],
  1640. doubleredirects: ['&list=querypage&qplimit=10&qppage=DoubleRedirects', queryfunctions.doubleredirect],
  1641. listduplicatedfiles: ['&list=querypage&qplimit=10&qppage=ListDuplicatedFiles', queryfunctions.times],
  1642. listredirects: ['&list=querypage&qplimit=10&qppage=Listredirects', queryfunctions.redirect],
  1643. lonelypages: ['&list=querypage&qplimit=10&qppage=Lonelypages', queryfunctions.title],
  1644. longpages: ['&list=querypage&qplimit=10&qppage=Longpages', queryfunctions.size],
  1645. mediastatistics: ['&list=querypage&qplimit=10&qppage=MediaStatistics', queryfunctions.media],
  1646. mostcategories: ['&list=querypage&qplimit=10&qppage=Mostcategories', queryfunctions.times],
  1647. mostimages: ['&list=querypage&qplimit=10&qppage=Mostimages', queryfunctions.times],
  1648. mostinterwikis: ['&list=querypage&qplimit=10&qppage=Mostinterwikis', queryfunctions.times],
  1649. mostlinkedcategories: ['&list=querypage&qplimit=10&qppage=Mostlinkedcategories', queryfunctions.times],
  1650. mostlinkedtemplates: ['&list=querypage&qplimit=10&qppage=Mostlinkedtemplates', queryfunctions.times],
  1651. mostlinked: ['&list=querypage&qplimit=10&qppage=Mostlinked', queryfunctions.times],
  1652. mostrevisions: ['&list=querypage&qplimit=10&qppage=Mostrevisions', queryfunctions.times],
  1653. fewestrevisions: ['&list=querypage&qplimit=10&qppage=Fewestrevisions', queryfunctions.times],
  1654. shortpages: ['&list=querypage&qplimit=10&qppage=Shortpages', queryfunctions.size],
  1655. uncategorizedcategories: ['&list=querypage&qplimit=10&qppage=Uncategorizedcategories', queryfunctions.title],
  1656. uncategorizedpages: ['&list=querypage&qplimit=10&qppage=Uncategorizedpages', queryfunctions.title],
  1657. uncategorizedimages: ['&list=querypage&qplimit=10&qppage=Uncategorizedimages', queryfunctions.title],
  1658. uncategorizedtemplates: ['&list=querypage&qplimit=10&qppage=Uncategorizedtemplates', queryfunctions.title],
  1659. unusedcategories: ['&list=querypage&qplimit=10&qppage=Unusedcategories', queryfunctions.title],
  1660. unusedimages: ['&list=querypage&qplimit=10&qppage=Unusedimages', queryfunctions.title],
  1661. wantedcategories: ['&list=querypage&qplimit=10&qppage=Wantedcategories', queryfunctions.times],
  1662. wantedfiles: ['&list=querypage&qplimit=10&qppage=Wantedfiles', queryfunctions.times],
  1663. wantedpages: ['&list=querypage&qplimit=10&qppage=Wantedpages', queryfunctions.times],
  1664. wantedtemplates: ['&list=querypage&qplimit=10&qppage=Wantedtemplates', queryfunctions.times],
  1665. unwatchedpages: ['&list=querypage&qplimit=10&qppage=Unwatchedpages', queryfunctions.title],
  1666. unusedtemplates: ['&list=querypage&qplimit=10&qppage=Unusedtemplates', queryfunctions.title],
  1667. withoutinterwiki: ['&list=querypage&qplimit=10&qppage=Withoutinterwiki', queryfunctions.title],
  1668. mostpopularcategories: ['&list=querypage&qplimit=10&qppage=Mostpopularcategories', queryfunctions.category],
  1669. mostimagesincontent: ['&list=querypage&qplimit=10&qppage=MostLinkedFilesInContent', queryfunctions.times],
  1670. unusedvideos: ['&list=querypage&qplimit=10&qppage=UnusedVideos', queryfunctions.title],
  1671. withoutimages: ['&list=querypage&qplimit=10&qppage=Withoutimages', queryfunctions.title],
  1672. nonportableinfoboxes: ['&list=querypage&qplimit=10&qppage=Nonportableinfoboxes', queryfunctions.title],
  1673. popularpages: ['&list=querypage&qplimit=10&qppage=Popularpages', queryfunctions.title],
  1674. pageswithoutinfobox: ['&list=querypage&qplimit=10&qppage=Pageswithoutinfobox', queryfunctions.title],
  1675. templateswithouttype: ['&list=querypage&qplimit=10&qppage=Templateswithouttype', queryfunctions.title],
  1676. allinfoboxes: ['&list=querypage&qplimit=10&qppage=AllInfoboxes', queryfunctions.title],
  1677. gadgetusage: ['&list=querypage&qplimit=10&qppage=GadgetUsage', queryfunctions.gadget],
  1678. recentchanges: ['&list=recentchanges&rctype=edit|new|log&rclimit=10', queryfunctions.recentchanges]
  1679. }
  1680. got.get( wiki + 'api.php?action=query&meta=siteinfo|allmessages&siprop=general&amenableparser=true&amtitle=' + encodeURIComponent( title ) + '&ammessages=' + encodeURIComponent( specialpage ) + '-summary' + ( specialpage in querypages ? querypages[specialpage][0] : '' ) + '&format=json', {
  1681. responseType: 'json'
  1682. } ).then( response => {
  1683. var body = response.body;
  1684. if ( body && body.warnings ) log_warn(body.warnings);
  1685. if ( response.statusCode !== 200 || !body ) {
  1686. console.log( '- ' + response.statusCode + ': Error while getting the special page: ' + ( body && body.error && body.error.info ) );
  1687. }
  1688. else {
  1689. if ( body.query.allmessages[0]['*'] ) {
  1690. var description = body.query.allmessages[0]['*'].toPlaintext();
  1691. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1692. embed.setDescription( description );
  1693. }
  1694. if ( msg.channel.type === 'text' && msg.guild.id in patreons && specialpage in querypages ) {
  1695. var text = Discord.Util.splitMessage( querypages[specialpage][1](body.query), {maxLength:1000} )[0];
  1696. embed.addField( lang.search.special, ( text || lang.search.empty ) );
  1697. }
  1698. }
  1699. }, error => {
  1700. console.log( '- Error while getting the special page: ' + error );
  1701. } ).finally( () => {
  1702. msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, {embed} );
  1703. if ( reaction ) reaction.removeEmoji();
  1704. } );
  1705. }
  1706. function gamepedia_search(lang, msg, searchterm, wiki, query, reaction, spoiler) {
  1707. if ( searchterm.length > 250 ) {
  1708. searchterm = searchterm.substring(0, 250);
  1709. msg.reactEmoji('⚠️');
  1710. }
  1711. var pagelink = wiki.toLink('Special:Search', 'search=' + searchterm.toSearch() + '&fulltext=1', '', query.general);
  1712. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename ).setTitle( '`' + searchterm + '`' ).setURL( pagelink );
  1713. if ( !searchterm.trim() ) {
  1714. pagelink = wiki.toLink('Special:Search', '', '', query.general);
  1715. embed.setTitle( 'Special:Search' ).setURL( pagelink );
  1716. }
  1717. var description = [];
  1718. got.get( wiki + 'api.php?action=query&titles=Special:Search&list=search&srinfo=totalhits&srprop=redirecttitle|sectiontitle&srnamespace=4|12|14|' + Object.values(query.namespaces).filter( ns => ns.content !== undefined ).map( ns => ns.id ).join('|') + '&srlimit=10&srsearch=' + encodeURIComponent( ( searchterm || ' ' ) ) + '&format=json', {
  1719. responseType: 'json'
  1720. } ).then( response => {
  1721. var body = response.body;
  1722. if ( body && body.warnings ) log_warn(body.warnings);
  1723. if ( response.statusCode !== 200 || !body || !body.query || !body.query.search || body.batchcomplete === undefined ) {
  1724. return console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  1725. }
  1726. if ( body.query.pages && body.query.pages['-1'] && body.query.pages['-1'].title ) {
  1727. if ( searchterm.trim() ) {
  1728. pagelink = wiki.toLink(body.query.pages['-1'].title, 'search=' + searchterm.toSearch() + '&fulltext=1', '', query.general);
  1729. embed.setURL( pagelink );
  1730. }
  1731. else {
  1732. pagelink = wiki.toLink(body.query.pages['-1'].title, '', '', query.general);
  1733. embed.setTitle( body.query.pages['-1'].title ).setURL( pagelink );
  1734. }
  1735. }
  1736. if ( searchterm.trim() ) {
  1737. body.query.search.forEach( result => {
  1738. description.push( '• [' + result.title + '](' + wiki.toLink(result.title, '', '', query.general) + ')' + ( result.sectiontitle ? ' § [' + result.sectiontitle + '](' + wiki.toLink(result.title, '', result.sectiontitle, query.general) + ')' : '' ) + ( result.redirecttitle ? ' (⤷ [' + result.redirecttitle + '](' + wiki.toLink(result.redirecttitle, '', '', query.general) + '))' : '' ) );
  1739. } );
  1740. embed.setFooter( ( lang.search.results[body.query.searchinfo.totalhits] || lang.search.results['*' + body.query.searchinfo.totalhits % 100] || lang.search.results['*' + body.query.searchinfo.totalhits % 10] || lang.search.results.default ).replaceSave( '%s', body.query.searchinfo.totalhits ) );
  1741. }
  1742. }, error => {
  1743. console.log( '- Error while getting the search results.' + error );
  1744. } ).finally( () => {
  1745. embed.setDescription( Discord.Util.splitMessage( description.join('\n') )[0] );
  1746. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1747. if ( reaction ) reaction.removeEmoji();
  1748. } );
  1749. }
  1750. function fandom_search(lang, msg, searchterm, wiki, query, reaction, spoiler) {
  1751. if ( searchterm.length > 250 ) {
  1752. searchterm = searchterm.substring(0, 250);
  1753. msg.reactEmoji('⚠️');
  1754. }
  1755. var pagelink = wiki.toLink('Special:Search', 'search=' + searchterm.toSearch(), '', query.general);
  1756. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename ).setTitle( '`' + searchterm + '`' ).setURL( pagelink );
  1757. if ( !searchterm.trim() ) {
  1758. pagelink = wiki.toLink('Special:Search', '', '', query.general);
  1759. embed.setTitle( 'Special:Search' ).setURL( pagelink );
  1760. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1761. if ( reaction ) reaction.removeEmoji();
  1762. return;
  1763. }
  1764. var description = [];
  1765. got.get( wiki + 'api/v1/Search/List?minArticleQuality=0&namespaces=4,12,14,' + Object.values(query.namespaces).filter( ns => ns.content !== undefined ).map( ns => ns.id ).join(',') + '&limit=10&query=' + encodeURIComponent( searchterm ) + '&format=json', {
  1766. responseType: 'json'
  1767. } ).then( response => {
  1768. var body = response.body;
  1769. if ( response.statusCode !== 200 || !body || body.exception || !body.items ) {
  1770. if ( !( body && body.exception && body.exception.code === 404 ) ) {
  1771. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.exception && body.exception.details ) );
  1772. }
  1773. return;
  1774. }
  1775. body.items.forEach( result => {
  1776. description.push( '• [' + result.title + '](' + wiki.toLink(result.title, '', '', query.general) + ')' );
  1777. } );
  1778. embed.setFooter( ( lang.search.results[body.total] || lang.search.results['*' + body.total % 100] || lang.search.results['*' + body.total % 10] || lang.search.results.default ).replaceSave( '%s', body.total ) );
  1779. }, error => {
  1780. console.log( '- Error while getting the search results.' + error );
  1781. } ).finally( () => {
  1782. embed.setDescription( Discord.Util.splitMessage( description.join('\n') )[0] );
  1783. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1784. if ( reaction ) reaction.removeEmoji();
  1785. } );
  1786. }
  1787. function gamepedia_user(lang, msg, namespace, username, wiki, querystring, fragment, querypage, contribs, reaction, spoiler) {
  1788. if ( /^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  1789. got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=blocks&bkprop=user|by|timestamp|expiry|reason&bkip=' + encodeURIComponent( username ) + '&format=json', {
  1790. responseType: 'json'
  1791. } ).then( response => {
  1792. var body = response.body;
  1793. if ( body && body.warnings ) log_warn(body.warnings);
  1794. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.blocks ) {
  1795. if ( body && body.error && ( body.error.code === 'param_ip' || body.error.code === 'cidrtoobroad' ) ) {
  1796. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('error');
  1797. else {
  1798. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment);
  1799. var embed = new Discord.MessageEmbed().setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1800. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  1801. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  1802. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  1803. embed.setTitle( displaytitle );
  1804. }
  1805. if ( querypage.pageprops && querypage.pageprops.description ) {
  1806. var description = htmlToPlain( querypage.pageprops.description );
  1807. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1808. embed.setDescription( description );
  1809. }
  1810. else if ( querypage.extract ) {
  1811. var extract = querypage.extract.escapeFormatting();
  1812. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1813. embed.setDescription( extract );
  1814. }
  1815. if ( querypage.pageimage && querypage.original ) {
  1816. var pageimage = querypage.original.source;
  1817. embed.setThumbnail( pageimage );
  1818. }
  1819. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1820. }
  1821. }
  1822. else {
  1823. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  1824. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  1825. }
  1826. if ( reaction ) reaction.removeEmoji();
  1827. }
  1828. else {
  1829. if ( !querypage.noRedirect || ( querypage.missing === undefined && querypage.ns !== -1 ) ) namespace = contribs;
  1830. var blocks = body.query.blocks.map( block => {
  1831. var isBlocked = false;
  1832. var blockedtimestamp = new Date(block.timestamp).toLocaleString(lang.dateformat, timeoptions);
  1833. var blockexpiry = block.expiry;
  1834. if ( blockexpiry === 'infinity' ) {
  1835. blockexpiry = lang.user.block.until_infinity;
  1836. isBlocked = true;
  1837. } else if ( blockexpiry ) {
  1838. if ( Date.parse(blockexpiry) > Date.now() ) isBlocked = true;
  1839. blockexpiry = new Date(blockexpiry).toLocaleString(lang.dateformat, timeoptions);
  1840. }
  1841. 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 )];
  1842. } ).filter( block => block !== undefined );
  1843. if ( username.includes( '/' ) ) {
  1844. var rangeprefix = username;
  1845. if ( username.includes( ':' ) ) {
  1846. var range = parseInt(username.replace( /^.+\/(\d{2,3})$/, '$1' ), 10);
  1847. if ( range === 128 ) username = username.replace( /^(.+)\/\d{2,3}$/, '$1' );
  1848. else if ( range >= 112 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){7}).+$/, '$1' );
  1849. else if ( range >= 96 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){6}).+$/, '$1' );
  1850. else if ( range >= 80 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){5}).+$/, '$1' );
  1851. else if ( range >= 64 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){4}).+$/, '$1' );
  1852. else if ( range >= 48 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){3}).+$/, '$1' );
  1853. else if ( range >= 32 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){2}).+$/, '$1' );
  1854. else if ( range >= 19 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){1}).+$/, '$1' );
  1855. }
  1856. else {
  1857. var range = parseInt(username.substring(username.length - 2), 10);
  1858. if ( range === 32 ) username = username.replace( /^(.+)\/\d{2}$/, '$1' );
  1859. else if ( range >= 24 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){3}).+$/, '$1' );
  1860. else if ( range >= 16 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){2}).+$/, '$1' );
  1861. }
  1862. }
  1863. got.get( wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=50' + ( username.includes( '/' ) ? '&ucuserprefix=' + encodeURIComponent( rangeprefix ) : '&ucuser=' + encodeURIComponent( username ) ) + '&format=json', {
  1864. responseType: 'json'
  1865. } ).then( ucresponse => {
  1866. var ucbody = ucresponse.body;
  1867. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  1868. if ( ucbody && ucbody.warnings ) log_warn(ucbody.warnings);
  1869. if ( ucresponse.statusCode !== 200 || !ucbody || ucbody.batchcomplete === undefined || !ucbody.query || !ucbody.query.usercontribs ) {
  1870. if ( ucbody && ucbody.error && ucbody.error.code === 'baduser_ucuser' ) {
  1871. msg.reactEmoji('error');
  1872. }
  1873. else {
  1874. console.log( '- ' + ucresponse.statusCode + ': Error while getting the search results: ' + ( ucbody && ucbody.error && ucbody.error.info ) );
  1875. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1876. }
  1877. }
  1878. else {
  1879. var editcount = [lang.user.info.editcount, ( username.includes( '/' ) && ( ( username.includes( ':' ) && range % 16 ) || range % 8 ) ? '~' : '' ) + ucbody.query.usercontribs.length + ( ucbody.continue ? '+' : '' )];
  1880. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  1881. if ( msg.showEmbed() ) {
  1882. var text = '<' + pagelink + '>';
  1883. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( username ).setURL( pagelink ).addField( editcount[0], '[' + editcount[1] + '](' + wiki.toLink(contribs + username, '', '', body.query.general, true) + ')' );
  1884. if ( blocks.length ) blocks.forEach( block => embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) ) );
  1885. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  1886. }
  1887. else {
  1888. var embed = {};
  1889. var text = '<' + pagelink + '>\n\n' + editcount.join(' ');
  1890. if ( blocks.length ) blocks.forEach( block => text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext() );
  1891. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  1892. }
  1893. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  1894. }
  1895. }, error => {
  1896. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  1897. console.log( '- Error while getting the search results: ' + error );
  1898. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1899. } ).finally( () => {
  1900. if ( reaction ) reaction.removeEmoji();
  1901. } );
  1902. }
  1903. }, error => {
  1904. console.log( '- Error while getting the search results: ' + error );
  1905. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  1906. if ( reaction ) reaction.removeEmoji();
  1907. } );
  1908. } else {
  1909. got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=users&usprop=blockinfo|groups|groupmemberships|editcount|registration|gender&ususers=' + encodeURIComponent( username ) + '&format=json', {
  1910. responseType: 'json'
  1911. } ).then( response => {
  1912. var body = response.body;
  1913. if ( body && body.warnings ) log_warn(body.warnings);
  1914. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.users || !body.query.users[0] ) {
  1915. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  1916. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  1917. if ( reaction ) reaction.removeEmoji();
  1918. }
  1919. else {
  1920. var queryuser = body.query.users[0];
  1921. if ( queryuser.missing !== undefined || queryuser.invalid !== undefined ) {
  1922. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('🤷');
  1923. else {
  1924. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  1925. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1926. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  1927. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  1928. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  1929. embed.setTitle( displaytitle );
  1930. }
  1931. if ( querypage.pageprops && querypage.pageprops.description ) {
  1932. var description = htmlToPlain( querypage.pageprops.description );
  1933. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1934. embed.setDescription( description );
  1935. }
  1936. else if ( querypage.extract ) {
  1937. var extract = querypage.extract.escapeFormatting();
  1938. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1939. embed.setDescription( extract );
  1940. }
  1941. if ( querypage.pageimage && querypage.original ) {
  1942. var pageimage = querypage.original.source;
  1943. embed.setThumbnail( pageimage );
  1944. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  1945. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1946. }
  1947. if ( reaction ) reaction.removeEmoji();
  1948. }
  1949. else {
  1950. username = queryuser.name;
  1951. var gender = [lang.user.info.gender];
  1952. switch (queryuser.gender) {
  1953. case 'male':
  1954. gender.push(lang.user.gender.male);
  1955. break;
  1956. case 'female':
  1957. gender.push(lang.user.gender.female);
  1958. break;
  1959. default:
  1960. gender.push(lang.user.gender.unknown);
  1961. }
  1962. var registration = [lang.user.info.registration, new Date(queryuser.registration).toLocaleString(lang.dateformat, timeoptions)];
  1963. var editcount = [lang.user.info.editcount, queryuser.editcount];
  1964. var groups = queryuser.groups;
  1965. var group = [lang.user.info.group];
  1966. var grouplist = lang.user.groups;
  1967. for ( var i = 0; i < grouplist.length; i++ ) {
  1968. if ( groups.includes( grouplist[i][0] ) && ( group.length === 1 || grouplist[i][0] !== 'user' ) ) {
  1969. var thisSite = allSites.find( site => site.wiki_domain === body.query.general.servername );
  1970. if ( grouplist[i][0] === 'wiki_manager' && thisSite && thisSite.wiki_managers.includes( username ) ) {
  1971. group.push('**' + grouplist[i][1] + '**');
  1972. }
  1973. else if ( !groups.includes( 'global_' + grouplist[i][0] ) || queryuser.groupmemberships.some( member => member.group === grouplist[i][0] ) ) {
  1974. group.push(grouplist[i][1]);
  1975. }
  1976. }
  1977. }
  1978. var isBlocked = false;
  1979. var blockedtimestamp = new Date(queryuser.blockedtimestamp).toLocaleString(lang.dateformat, timeoptions);
  1980. var blockexpiry = queryuser.blockexpiry;
  1981. if ( blockexpiry === 'infinity' ) {
  1982. blockexpiry = lang.user.block.until_infinity;
  1983. isBlocked = true;
  1984. } else if ( blockexpiry ) {
  1985. var blockexpirydate = blockexpiry.replace( /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2,3})/, '$1-$2-$3T$4:$5:$6Z' );
  1986. blockexpiry = new Date(blockexpirydate).toLocaleString(lang.dateformat, timeoptions);
  1987. if ( Date.parse(blockexpirydate) > Date.now() ) isBlocked = true;
  1988. }
  1989. var blockedby = '[[User:' + queryuser.blockedby + '|' + queryuser.blockedby + ']]';
  1990. var blockreason = queryuser.blockreason;
  1991. 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 )];
  1992. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  1993. if ( msg.showEmbed() ) {
  1994. var text = '<' + pagelink + '>';
  1995. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( username.escapeFormatting() ).setURL( pagelink ).addField( editcount[0], '[' + editcount[1] + '](' + wiki.toLink(contribs + username, '', '', body.query.general, true) + ')', true ).addField( group[0], group.slice(1).join(',\n'), true ).addField( gender[0], gender[1], true ).addField( registration[0], registration[1], true );
  1996. if ( querypage.pageprops && querypage.pageprops.description ) {
  1997. var description = htmlToPlain( querypage.pageprops.description );
  1998. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1999. embed.setDescription( description );
  2000. }
  2001. else if ( querypage.extract ) {
  2002. var extract = querypage.extract.escapeFormatting();
  2003. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  2004. embed.setDescription( extract );
  2005. }
  2006. }
  2007. else {
  2008. var embed = {};
  2009. var text = '<' + pagelink + '>\n\n' + gender.join(' ') + '\n' + registration.join(' ') + '\n' + editcount.join(' ') + '\n' + group[0] + ' ' + group.slice(1).join(', ');
  2010. }
  2011. if ( wiki.endsWith( '.gamepedia.com/' ) ) got.get( wiki + 'api.php?action=profile&do=getPublicProfile&user_name=' + encodeURIComponent( username ) + '&format=json', {
  2012. responseType: 'json'
  2013. } ).then( presponse => {
  2014. var pbody = presponse.body;
  2015. if ( presponse.statusCode !== 200 || !pbody || pbody.error || pbody.errormsg || !pbody.profile ) {
  2016. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && ( pbody.error && pbody.error.info || pbody.errormsg ) ) );
  2017. }
  2018. else if ( pbody.profile['link-discord'] ) {
  2019. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  2020. return member.user.tag === pbody.profile['link-discord'].replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2021. } );
  2022. var discordname = [lang.user.info.discord,pbody.profile['link-discord'].escapeFormatting()];
  2023. if ( discordmember ) discordname[1] = discordmember.toString();
  2024. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  2025. else text += '\n' + discordname.join(' ');
  2026. }
  2027. }, error => {
  2028. console.log( '- Error while getting the user profile: ' + error );
  2029. } ).finally( () => {
  2030. if ( msg.showEmbed() ) {
  2031. if ( isBlocked ) embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) );
  2032. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2033. }
  2034. else {
  2035. if ( isBlocked ) text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  2036. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2037. }
  2038. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2039. if ( reaction ) reaction.removeEmoji();
  2040. } );
  2041. else if ( wiki.isFandom() ) got.get( 'https://services.fandom.com/user-attribute/user/' + queryuser.userid + '?format=json', {
  2042. headers: {
  2043. Accept: 'application/hal+json'
  2044. },
  2045. responseType: 'json'
  2046. } ).then( presponse => {
  2047. var pbody = presponse.body;
  2048. if ( presponse.statusCode !== 200 || !pbody || pbody.title || !pbody._embedded || !pbody._embedded.properties ) {
  2049. if ( !( pbody && pbody.status === 404 ) ) {
  2050. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && pbody.title ) );
  2051. }
  2052. }
  2053. else {
  2054. var profile = pbody._embedded.properties;
  2055. var discordfield = profile.find( field => field.name === 'discordHandle' );
  2056. var avatarfield = profile.find( field => field.name === 'avatar' );
  2057. if ( discordfield && discordfield.value ) {
  2058. discordfield.value = htmlToPlain( discordfield.value );
  2059. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  2060. return member.user.tag === htmlToPlain( discordfield.value ).replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2061. } );
  2062. var discordname = [lang.user.info.discord,discordfield.value];
  2063. if ( discordmember ) discordname[1] = discordmember.toString();
  2064. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  2065. else text += '\n' + discordname.join(' ');
  2066. }
  2067. if ( msg.showEmbed() && avatarfield && avatarfield.value ) embed.setThumbnail( avatarfield.value );
  2068. }
  2069. }, error => {
  2070. console.log( '- Error while getting the user profile: ' + error );
  2071. } ).finally( () => {
  2072. if ( msg.showEmbed() ) {
  2073. if ( isBlocked ) embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) );
  2074. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2075. }
  2076. else {
  2077. if ( isBlocked ) text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  2078. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2079. }
  2080. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2081. if ( reaction ) reaction.removeEmoji();
  2082. } );
  2083. else {
  2084. if ( isBlocked ) {
  2085. if ( msg.showEmbed() ) embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) );
  2086. else text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  2087. }
  2088. msg.sendChannel( spoiler + text + spoiler, {embed} );
  2089. if ( reaction ) reaction.removeEmoji();
  2090. }
  2091. }
  2092. }
  2093. }, error => {
  2094. console.log( '- Error while getting the search results: ' + error );
  2095. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2096. if ( reaction ) reaction.removeEmoji();
  2097. } );
  2098. }
  2099. }
  2100. function fandom_user(lang, msg, namespace, username, wiki, querystring, fragment, querypage, contribs, reaction, spoiler) {
  2101. if ( /^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2102. got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=blocks&bkprop=user|by|timestamp|expiry|reason&bkip=' + encodeURIComponent( username ) + '&format=json', {
  2103. responseType: 'json'
  2104. } ).then( response => {
  2105. var body = response.body;
  2106. if ( body && body.warnings ) log_warn(body.warnings);
  2107. if ( response.statusCode !== 200 || !body || !body.query || !body.query.blocks ) {
  2108. if ( body && body.error && ( body.error.code === 'param_ip' || body.error.code === 'cidrtoobroad' ) ) {
  2109. if ( querypage.missing !== undefined || querypage.ns === -1 ) {
  2110. msg.reactEmoji('error');
  2111. if ( reaction ) reaction.removeEmoji();
  2112. }
  2113. else {
  2114. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment);
  2115. var embed = new Discord.MessageEmbed().setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2116. got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  2117. var descbody = descresponse.body;
  2118. if ( descresponse.statusCode !== 200 || !descbody ) {
  2119. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  2120. } else {
  2121. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png');
  2122. var parser = new htmlparser.Parser( {
  2123. onopentag: (tagname, attribs) => {
  2124. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2125. var description = attribs.content.escapeFormatting();
  2126. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2127. embed.setDescription( description );
  2128. }
  2129. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2130. thumbnail = attribs.content;
  2131. }
  2132. }
  2133. }, {decodeEntities:true} );
  2134. parser.write( descbody );
  2135. parser.end();
  2136. embed.setThumbnail( thumbnail );
  2137. }
  2138. }, error => {
  2139. console.log( '- Error while getting the description: ' + error );
  2140. } ).finally( () => {
  2141. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2142. if ( reaction ) reaction.removeEmoji();
  2143. } );
  2144. }
  2145. }
  2146. else {
  2147. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2148. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2149. if ( reaction ) reaction.removeEmoji();
  2150. }
  2151. }
  2152. else {
  2153. if ( !querypage.noRedirect || ( querypage.missing === undefined && querypage.ns !== -1 ) ) namespace = contribs;
  2154. var blocks = body.query.blocks.map( block => {
  2155. var isBlocked = false;
  2156. var blockedtimestamp = new Date(block.timestamp).toLocaleString(lang.dateformat, timeoptions);
  2157. var blockexpiry = block.expiry;
  2158. if ( blockexpiry === 'infinity' ) {
  2159. blockexpiry = lang.user.block.until_infinity;
  2160. isBlocked = true;
  2161. } else if ( blockexpiry ) {
  2162. if ( Date.parse(blockexpiry) > Date.now() ) isBlocked = true;
  2163. blockexpiry = new Date(blockexpiry).toLocaleString(lang.dateformat, timeoptions);
  2164. }
  2165. 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 )];
  2166. } ).filter( block => block !== undefined );
  2167. if ( username.includes( '/' ) ) {
  2168. var rangeprefix = username;
  2169. if ( username.includes( ':' ) ) {
  2170. var range = parseInt(username.replace( /^.+\/(\d{2,3})$/, '$1' ), 10);
  2171. if ( range === 128 ) username = username.replace( /^(.+)\/\d{2,3}$/, '$1' );
  2172. else if ( range >= 112 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){7}).+$/, '$1' );
  2173. else if ( range >= 96 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){6}).+$/, '$1' );
  2174. else if ( range >= 80 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){5}).+$/, '$1' );
  2175. else if ( range >= 64 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){4}).+$/, '$1' );
  2176. else if ( range >= 48 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){3}).+$/, '$1' );
  2177. else if ( range >= 32 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){2}).+$/, '$1' );
  2178. else if ( range >= 19 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){1}).+$/, '$1' );
  2179. }
  2180. else {
  2181. var range = parseInt(username.substring(username.length - 2), 10);
  2182. if ( range === 32 ) username = username.replace( /^(.+)\/\d{2}$/, '$1' );
  2183. else if ( range >= 24 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){3}).+$/, '$1' );
  2184. else if ( range >= 16 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){2}).+$/, '$1' );
  2185. }
  2186. }
  2187. got.get( wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=50&ucuser=' + encodeURIComponent( username ) + '&format=json', {
  2188. responseType: 'json'
  2189. } ).then( ucresponse => {
  2190. var ucbody = ucresponse.body;
  2191. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2192. if ( ucbody && ucbody.warnings ) log_warn(ucbody.warnings);
  2193. if ( ucresponse.statusCode !== 200 || !ucbody || !ucbody.query || !ucbody.query.usercontribs ) {
  2194. if ( ucbody && ucbody.error && ucbody.error.code === 'baduser_ucuser' ) {
  2195. msg.reactEmoji('error');
  2196. }
  2197. else {
  2198. console.log( '- ' + ucresponse.statusCode + ': Error while getting the search results: ' + ( ucbody && ucbody.error && ucbody.error.info ) );
  2199. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2200. }
  2201. }
  2202. else {
  2203. var editcount = [lang.user.info.editcount, ( username.includes( '/' ) ? '~' : '' ) + ucbody.query.usercontribs.length + ( ucbody.continue ? '+' : '' )];
  2204. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2205. if ( msg.showEmbed() ) {
  2206. var text = '<' + pagelink + '>';
  2207. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( username ).setURL( pagelink ).addField( editcount[0], '[' + editcount[1] + '](' + wiki.toLink(contribs + username, '', '', body.query.general, true) + ')' );
  2208. if ( blocks.length ) blocks.forEach( block => embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) ) );
  2209. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2210. }
  2211. else {
  2212. var embed = {};
  2213. var text = '<' + pagelink + '>\n\n' + editcount.join(' ');
  2214. if ( blocks.length ) blocks.forEach( block => text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext() );
  2215. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2216. }
  2217. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2218. }
  2219. }, error => {
  2220. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2221. console.log( '- Error while getting the search results: ' + error );
  2222. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2223. } ).finally( () => {
  2224. if ( reaction ) reaction.removeEmoji();
  2225. } );
  2226. }
  2227. }, error => {
  2228. console.log( '- Error while getting the search results: ' + error );
  2229. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2230. if ( reaction ) reaction.removeEmoji();
  2231. } );
  2232. } else {
  2233. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-Wiki_Manager&amenableparser=true&siprop=general&list=users&usprop=blockinfo|groups|editcount|registration|gender&ususers=' + encodeURIComponent( username ) + '&format=json', {
  2234. responseType: 'json'
  2235. } ).then( response => {
  2236. var body = response.body;
  2237. if ( body && body.warnings ) log_warn(body.warnings);
  2238. if ( response.statusCode !== 200 || !body || !body.query || !body.query.users ) {
  2239. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2240. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2241. if ( reaction ) reaction.removeEmoji();
  2242. }
  2243. else {
  2244. var queryuser = body.query.users[0];
  2245. if ( !queryuser ) {
  2246. if ( querypage.missing !== undefined || querypage.ns === -1 ) {
  2247. msg.reactEmoji('🤷');
  2248. if ( reaction ) reaction.removeEmoji();
  2249. }
  2250. else {
  2251. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  2252. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2253. got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  2254. var descbody = descresponse.body;
  2255. if ( descresponse.statusCode !== 200 || !descbody ) {
  2256. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  2257. } else {
  2258. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  2259. var parser = new htmlparser.Parser( {
  2260. onopentag: (tagname, attribs) => {
  2261. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2262. var description = attribs.content.escapeFormatting();
  2263. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2264. embed.setDescription( description );
  2265. }
  2266. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2267. thumbnail = attribs.content;
  2268. }
  2269. }
  2270. }, {decodeEntities:true} );
  2271. parser.write( descbody );
  2272. parser.end();
  2273. embed.setThumbnail( thumbnail );
  2274. }
  2275. }, error => {
  2276. console.log( '- Error while getting the description: ' + error );
  2277. } ).finally( () => {
  2278. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2279. if ( reaction ) reaction.removeEmoji();
  2280. } );
  2281. }
  2282. }
  2283. else {
  2284. username = queryuser.name;
  2285. var gender = [lang.user.info.gender];
  2286. switch (queryuser.gender) {
  2287. case 'male':
  2288. gender.push(lang.user.gender.male);
  2289. break;
  2290. case 'female':
  2291. gender.push(lang.user.gender.female);
  2292. break;
  2293. default:
  2294. gender.push(lang.user.gender.unknown);
  2295. }
  2296. var registration = [lang.user.info.registration, new Date(queryuser.registration).toLocaleString(lang.dateformat, timeoptions)];
  2297. var editcount = [lang.user.info.editcount, queryuser.editcount];
  2298. var groups = queryuser.groups;
  2299. var group = [lang.user.info.group];
  2300. var grouplist = lang.user.groups;
  2301. for ( var i = 0; i < grouplist.length; i++ ) {
  2302. if ( groups.includes( grouplist[i][0] ) && ( group.length === 1 || grouplist[i][0] !== 'user' ) ) {
  2303. if ( grouplist[i][0] === 'wiki-manager' && body.query.allmessages[0]['*'] === username ) {
  2304. group.push('**' + grouplist[i][1] + '**');
  2305. }
  2306. else group.push(grouplist[i][1]);
  2307. }
  2308. }
  2309. var isBlocked = false;
  2310. var blockedtimestamp = new Date(queryuser.blockedtimestamp).toLocaleString(lang.dateformat, timeoptions);
  2311. var blockexpiry = queryuser.blockexpiry;
  2312. if ( blockexpiry === 'infinity' ) {
  2313. blockexpiry = lang.user.block.until_infinity;
  2314. isBlocked = true;
  2315. } else if ( blockexpiry ) {
  2316. var blockexpirydate = blockexpiry.replace( /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2,3})/, '$1-$2-$3T$4:$5:$6Z' );
  2317. blockexpiry = new Date(blockexpirydate).toLocaleString(lang.dateformat, timeoptions);
  2318. if ( Date.parse(blockexpirydate) > Date.now() ) isBlocked = true;
  2319. }
  2320. var blockedby = '[[User:' + queryuser.blockedby + '|' + queryuser.blockedby + ']]';
  2321. var blockreason = queryuser.blockreason;
  2322. var block = [lang.user.block.header.replaceSave( '%s', username ).escapeFormatting(), lang.user.block['nofrom' + ( blockreason ? 'text' : 'noreason' )].replaceSave( '%1$s', blockedtimestamp ).replaceSave( '%2$s', blockexpiry ).replaceSave( '%3$s', blockedby ).replaceSave( '%4$s', blockreason )];
  2323. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2324. if ( msg.showEmbed() ) {
  2325. var text = '<' + pagelink + '>';
  2326. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( username.escapeFormatting() ).setURL( pagelink ).addField( editcount[0], '[' + editcount[1] + '](' + wiki.toLink(contribs + username, '', '', body.query.general, true) + ')', true ).addField( group[0], group.slice(1).join(',\n'), true ).addField( gender[0], gender[1], true ).addField( registration[0], registration[1], true );
  2327. }
  2328. else {
  2329. var embed = {};
  2330. var text = '<' + pagelink + '>\n\n' + gender.join(' ') + '\n' + registration.join(' ') + '\n' + editcount.join(' ') + '\n' + group[0] + ' ' + group.slice(1).join(', ');
  2331. }
  2332. got.get( 'https://services.fandom.com/user-attribute/user/' + queryuser.userid + '?format=json', {
  2333. headers: {
  2334. Accept: 'application/hal+json'
  2335. },
  2336. responseType: 'json'
  2337. } ).then( presponse => {
  2338. var pbody = presponse.body;
  2339. if ( presponse.statusCode !== 200 || !pbody || pbody.title || !pbody._embedded || !pbody._embedded.properties ) {
  2340. if ( !( pbody && pbody.status === 404 ) ) {
  2341. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && pbody.title ) );
  2342. }
  2343. }
  2344. else {
  2345. var profile = pbody._embedded.properties;
  2346. var discordfield = profile.find( field => field.name === 'discordHandle' );
  2347. var avatarfield = profile.find( field => field.name === 'avatar' );
  2348. if ( discordfield && discordfield.value ) {
  2349. discordfield.value = htmlToPlain( discordfield.value );
  2350. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  2351. return member.user.tag === htmlToPlain( discordfield.value ).replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2352. } );
  2353. var discordname = [lang.user.info.discord,discordfield.value];
  2354. if ( discordmember ) discordname[1] = discordmember.toString();
  2355. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  2356. else text += '\n' + discordname.join(' ');
  2357. }
  2358. if ( msg.showEmbed() && avatarfield && avatarfield.value ) embed.setThumbnail( avatarfield.value );
  2359. }
  2360. }, error => {
  2361. console.log( '- Error while getting the user profile: ' + error );
  2362. } ).finally( () => {
  2363. if ( msg.showEmbed() ) {
  2364. if ( isBlocked ) embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) );
  2365. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2366. }
  2367. else {
  2368. if ( isBlocked ) text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  2369. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2370. }
  2371. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2372. if ( reaction ) reaction.removeEmoji();
  2373. } );
  2374. }
  2375. }
  2376. }, error => {
  2377. console.log( '- Error while getting the search results: ' + error );
  2378. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2379. if ( reaction ) reaction.removeEmoji();
  2380. } );
  2381. }
  2382. }
  2383. function global_block(lang, msg, username, text, embed, wiki, spoiler) {
  2384. if ( !msg || msg.channel.type !== 'text' || !( msg.guild.id in patreons ) ) return;
  2385. if ( msg.showEmbed() ) embed.fields.pop();
  2386. else {
  2387. let splittext = text.split('\n\n');
  2388. splittext.pop();
  2389. text = splittext.join('\n\n');
  2390. }
  2391. if ( wiki.isFandom() ) got.get( 'https://community.fandom.com/Special:Contributions/' + encodeURIComponent( username ) + '?limit=1' ).then( response => {
  2392. var body = response.body;
  2393. if ( response.statusCode !== 200 || !body ) {
  2394. console.log( '- ' + response.statusCode + ': Error while getting the global block.' );
  2395. }
  2396. else {
  2397. let $ = cheerio.load(body);
  2398. if ( $('#mw-content-text .errorbox').length ) {
  2399. if ( msg.showEmbed() ) embed.addField( lang.user.gblock.disabled, '\u200b' );
  2400. else text += '\n\n**' + lang.user.gblock.disabled + '**';
  2401. }
  2402. else if ( $('.mw-warning-with-logexcerpt').length && !$(".mw-warning-with-logexcerpt .mw-logline-block").length ) {
  2403. if ( msg.showEmbed() ) embed.addField( lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting(), '\u200b' );
  2404. else text += '\n\n**' + lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting() + '**';
  2405. }
  2406. }
  2407. }, error => {
  2408. console.log( '- Error while getting the global block: ' + error );
  2409. } ).finally( () => {
  2410. if ( !/^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2411. got.get( 'https://community.fandom.com/wiki/Special:Editcount/' + encodeURIComponent( username ) ).then( gresponse => {
  2412. var gbody = gresponse.body;
  2413. if ( gresponse.statusCode !== 200 || !gbody ) {
  2414. console.log( '- ' + gresponse.statusCode + ': Error while getting the global edit count.' );
  2415. }
  2416. else {
  2417. let $ = cheerio.load(gbody);
  2418. var globaledits = $('#editcount .TablePager th').eq(7).text().replace( /[,\.]/g, '' );
  2419. if ( globaledits ) {
  2420. if ( msg.showEmbed() ) embed.spliceFields(1, 0, {name:lang.user.info.globaleditcount,value:'[' + globaledits + '](https://community.fandom.com/wiki/Special:Editcount/' + username.toTitle(true) + ')',inline:true});
  2421. else {
  2422. let splittext = text.split('\n');
  2423. splittext.splice(5, 0, lang.user.info.globaleditcount + ' ' + globaledits);
  2424. text = splittext.join('\n');
  2425. }
  2426. }
  2427. }
  2428. }, error => {
  2429. console.log( '- Error while getting the global edit count: ' + error );
  2430. } ).finally( () => {
  2431. msg.edit( spoiler + text + spoiler, {embed} ).catch(log_error);
  2432. } );
  2433. }
  2434. else msg.edit( spoiler + text + spoiler, {embed} ).catch(log_error);
  2435. } );
  2436. else if ( wiki.endsWith( '.gamepedia.com/' ) ) got.get( 'https://help.gamepedia.com/Special:GlobalBlockList/' + encodeURIComponent( username ) + '?uselang=qqx' ).then( response => {
  2437. var body = response.body;
  2438. if ( response.statusCode !== 200 || !body ) {
  2439. console.log( '- ' + response.statusCode + ': Error while getting the global block.' );
  2440. }
  2441. else {
  2442. let $ = cheerio.load(body);
  2443. var gblock = $('.mw-blocklist');
  2444. if ( gblock.length ) {
  2445. var reason = gblock.find('.TablePager_col_reason').text().replace( /\)$/, '' ).split(', ');
  2446. var timestamp = new Date(gblock.find('.TablePager_col_timestamp').text().replace( /(\d{2}:\d{2}), (\d{1,2}) \((\w+)\) (\d{4})/, '$3 $2, $4 $1 UTC' )).toLocaleString(lang.dateformat, timeoptions);
  2447. var expiry = gblock.find('.TablePager_col_expiry').text();
  2448. if ( expiry.startsWith( '(infiniteblock)' ) ) expiry = lang.user.block.until_infinity;
  2449. else expiry = new Date(expiry.replace( /(\d{2}:\d{2}), (\d{1,2}) \((\w+)\) (\d{4})/, '$3 $2, $4 $1 UTC' )).toLocaleString(lang.dateformat, timeoptions);
  2450. if ( msg.showEmbed() ) {
  2451. var gblocktitle = lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting();
  2452. var globalblock = embed.fields.find( field => field.inline === false && field.name === lang.user.block.header.replaceSave( '%s', username ).escapeFormatting() && field.value.replace( /\[([^\]]*)\]\([^\)]*\)/g, '$1' ) === lang.user.block[( reason.length > 4 ? 'text' : 'noreason' )].replaceSave( '%1$s', timestamp ).replaceSave( '%2$s', expiry ).replaceSave( '%3$s', reason[1] ).replaceSave( '%4$s', reason.slice(4).join(', ') ).escapeFormatting() );
  2453. if ( globalblock ) globalblock.name = gblocktitle;
  2454. else {
  2455. var gblocktext = lang.user.gblock[( reason.length > 4 ? 'text' : 'noreason' )].replaceSave( '%1$s', timestamp ).replaceSave( '%2$s', expiry ).replaceSave( '%3$s', '[[User:' + reason[1] + '|' + reason[1] + ']]' ).replaceSave( '%4$s', '[[Special:Contribs/' + username.toTitle() + '|' + reason[2] + ']]' ).replaceSave( '%5$s', reason.slice(4).join(', ') );
  2456. embed.addField( gblocktitle, gblocktext.toMarkdown( reason[3].replace( /Special:BlockList$/, '' ) ) );
  2457. }
  2458. }
  2459. else {
  2460. let splittext = text.split('\n\n');
  2461. var globalblock = splittext.indexOf('**' + lang.user.block.header.replaceSave( '%s', username ).escapeFormatting() + '**\n' + lang.user.block[( reason.length > 4 ? 'text' : 'noreason' )].replaceSave( '%1$s', timestamp ).replaceSave( '%2$s', expiry ).replaceSave( '%3$s', reason[1] ).replaceSave( '%4$s', reason.slice(4).join(', ') ).escapeFormatting());
  2462. if ( globalblock !== -1 ) splittext[globalblock] = '**' + lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting() + '**\n' + lang.user.block[( reason.length > 4 ? 'text' : 'noreason' )].replaceSave( '%1$s', timestamp ).replaceSave( '%2$s', expiry ).replaceSave( '%3$s', reason[1] ).replaceSave( '%4$s', reason.slice(4).join(', ') ).escapeFormatting();
  2463. else splittext.push('**' + lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting() + '**\n' + lang.user.gblock[( reason.length > 4 ? 'text' : 'noreason' )].replaceSave( '%1$s', timestamp ).replaceSave( '%2$s', expiry ).replaceSave( '%3$s', reason[1] ).replaceSave( '%4$s', reason[2] ).replaceSave( '%5$s', reason.slice(4).join(', ') ).escapeFormatting());
  2464. text = splittext.join('\n\n');
  2465. }
  2466. }
  2467. }
  2468. }, error => {
  2469. console.log( '- Error while getting the global block: ' + error );
  2470. } ).finally( () => {
  2471. if ( !/^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2472. got.get( 'https://help.gamepedia.com/UserProfile:' + encodeURIComponent( username ) ).then( gresponse => {
  2473. var gbody = gresponse.body;
  2474. if ( gresponse.statusCode !== 200 || !gbody ) {
  2475. console.log( '- ' + gresponse.statusCode + ': Error while getting the global edit count.' );
  2476. }
  2477. else {
  2478. let $ = cheerio.load(gbody);
  2479. var wikisedited = $('.curseprofile .rightcolumn .section.stats dd').eq(0).text().replace( /[,\.]/g, '' );
  2480. if ( wikisedited ) {
  2481. if ( msg.showEmbed() ) embed.spliceFields(1, 0, {name:lang.user.info.wikisedited,value:wikisedited,inline:true});
  2482. else {
  2483. let splittext = text.split('\n');
  2484. splittext.splice(5, 0, lang.user.info.wikisedited + ' ' + wikisedited);
  2485. text = splittext.join('\n');
  2486. }
  2487. }
  2488. var globaledits = $('.curseprofile .rightcolumn .section.stats dd').eq(2).text().replace( /[,\.]/g, '' );
  2489. if ( globaledits ) {
  2490. if ( msg.showEmbed() ) embed.spliceFields(1, 0, {name:lang.user.info.globaleditcount,value:'[' + globaledits + '](https://help.gamepedia.com/Gamepedia_Help_Wiki:Global_user_tracker#' + wiki.replace( /^https:\/\/([a-z\d-]{1,50})\.gamepedia\.com\/$/, '$1/' ) + username.toTitle(true) + ')',inline:true});
  2491. else {
  2492. let splittext = text.split('\n');
  2493. splittext.splice(5, 0, lang.user.info.globaleditcount + ' ' + globaledits);
  2494. text = splittext.join('\n');
  2495. }
  2496. }
  2497. }
  2498. }, error => {
  2499. console.log( '- Error while getting the global edit count: ' + error );
  2500. } ).finally( () => {
  2501. msg.edit( spoiler + text + spoiler, {embed} ).catch(log_error);
  2502. } );
  2503. }
  2504. else msg.edit( spoiler + text + spoiler, {embed} ).catch(log_error);
  2505. } );
  2506. }
  2507. function fandom_discussion(lang, msg, wiki, title, query, reaction, spoiler) {
  2508. if ( !title ) {
  2509. var pagelink = wiki + 'f';
  2510. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename ).setTitle( lang.discussion.main ).setURL( pagelink );
  2511. got.get( wiki + 'f' ).then( descresponse => {
  2512. var descbody = descresponse.body;
  2513. if ( descresponse.statusCode !== 200 || !descbody ) {
  2514. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  2515. } else {
  2516. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', query.general);
  2517. var parser = new htmlparser.Parser( {
  2518. onopentag: (tagname, attribs) => {
  2519. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2520. var description = attribs.content.escapeFormatting();
  2521. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2522. embed.setDescription( description );
  2523. }
  2524. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2525. thumbnail = attribs.content;
  2526. }
  2527. }
  2528. }, {decodeEntities:true} );
  2529. parser.write( descbody );
  2530. parser.end();
  2531. embed.setThumbnail( thumbnail );
  2532. }
  2533. }, error => {
  2534. console.log( '- Error while getting the description: ' + error );
  2535. } ).finally( () => {
  2536. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2537. if ( reaction ) reaction.removeEmoji();
  2538. } );
  2539. }
  2540. else if ( !query.wikidesc ) {
  2541. return got.get( wiki + 'api/v1/Mercury/WikiVariables?format=json', {
  2542. responseType: 'json'
  2543. } ).then( wvresponse => {
  2544. var wvbody = wvresponse.body;
  2545. if ( wvresponse.statusCode !== 200 || !wvbody || !wvbody.data ) {
  2546. console.log( '- ' + wvresponse.statusCode + ': Error while getting the wiki id: ' + ( wvbody && wvbody.exception && wvbody.exception.details ) );
  2547. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2548. if ( reaction ) reaction.removeEmoji();
  2549. }
  2550. else {
  2551. query.wikidesc = {id: wvbody.data.id};
  2552. fandom_discussion(lang, msg, wiki, title, query, reaction, spoiler);
  2553. }
  2554. }, error => {
  2555. console.log( '- Error while getting the wiki id: ' + error );
  2556. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2557. if ( reaction ) reaction.removeEmoji();
  2558. } );
  2559. }
  2560. else if ( title.split(' ')[0].toLowerCase() === 'post' || title.split(' ')[0].toLowerCase() === lang.discussion.post ) {
  2561. title = title.split(' ').slice(1).join(' ');
  2562. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/posts?limit=50&format=json', {
  2563. headers: {
  2564. Accept: 'application/hal+json'
  2565. },
  2566. responseType: 'json'
  2567. } ).then( response => {
  2568. var body = response.body;
  2569. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded['doc:posts'] ) {
  2570. console.log( '- ' + response.statusCode + ': Error while getting the posts: ' + ( body && body.title ) );
  2571. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2572. if ( reaction ) reaction.removeEmoji();
  2573. }
  2574. else if ( body._embedded['doc:posts'].length ) {
  2575. var posts = body._embedded['doc:posts'];
  2576. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename );
  2577. if ( posts.some( post => post.id === title ) ) {
  2578. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.id === title ), embed, spoiler);
  2579. if ( reaction ) reaction.removeEmoji();
  2580. }
  2581. else if ( /^\d+$/.test(title) ) {
  2582. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/posts/' + title + '?format=json', {
  2583. headers: {
  2584. Accept: 'application/hal+json'
  2585. },
  2586. responseType: 'json'
  2587. } ).then( presponse => {
  2588. var pbody = presponse.body;
  2589. if ( presponse.statusCode !== 200 || !pbody || pbody.id !== title ) {
  2590. if ( pbody && pbody.title === 'The requested resource was not found.' ) {
  2591. if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2592. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2593. }
  2594. else msg.reactEmoji('🤷');
  2595. }
  2596. else {
  2597. console.log( '- ' + presponse.statusCode + ': Error while getting the post: ' + ( pbody && pbody.title ) );
  2598. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2599. }
  2600. if ( reaction ) reaction.removeEmoji();
  2601. }
  2602. else if ( pbody.title ) {
  2603. fandom_discussionsend(lang, msg, wiki, pbody, embed, spoiler);
  2604. if ( reaction ) reaction.removeEmoji();
  2605. }
  2606. else got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads/' + pbody.threadId + '?format=json', {
  2607. headers: {
  2608. Accept: 'application/hal+json'
  2609. },
  2610. responseType: 'json'
  2611. } ).then( thresponse => {
  2612. var thbody = thresponse.body;
  2613. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== pbody.threadId ) {
  2614. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  2615. embed.setTitle( '~~' + pbody.threadId + '~~' );
  2616. }
  2617. else embed.setTitle( thbody.title.escapeFormatting() );
  2618. }, error => {
  2619. console.log( '- Error while getting the thread: ' + error );
  2620. embed.setTitle( '~~' + pbody.threadId + '~~' );
  2621. } ).finally( () => {
  2622. fandom_discussionsend(lang, msg, wiki, pbody, embed, spoiler);
  2623. if ( reaction ) reaction.removeEmoji();
  2624. } );
  2625. }, error => {
  2626. console.log( '- Error while getting the post: ' + error );
  2627. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2628. if ( reaction ) reaction.removeEmoji();
  2629. } );
  2630. }
  2631. else if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2632. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2633. if ( reaction ) reaction.removeEmoji();
  2634. }
  2635. else {
  2636. msg.reactEmoji('🤷');
  2637. if ( reaction ) reaction.removeEmoji();
  2638. }
  2639. }
  2640. else {
  2641. msg.reactEmoji('🤷');
  2642. if ( reaction ) reaction.removeEmoji();
  2643. }
  2644. }, error => {
  2645. console.log( '- Error while getting the posts: ' + error );
  2646. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2647. if ( reaction ) reaction.removeEmoji();
  2648. } );
  2649. }
  2650. else {
  2651. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads?sortKey=trending&limit=50&format=json', {
  2652. headers: {
  2653. Accept: 'application/hal+json'
  2654. },
  2655. responseType: 'json'
  2656. } ).then( response => {
  2657. var body = response.body;
  2658. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded.threads ) {
  2659. console.log( '- ' + response.statusCode + ': Error while getting the threads: ' + ( body && body.title ) );
  2660. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2661. if ( reaction ) reaction.removeEmoji();
  2662. }
  2663. else if ( body._embedded.threads.length ) {
  2664. var threads = body._embedded.threads;
  2665. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename );
  2666. if ( threads.some( thread => thread.id === title ) ) {
  2667. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.id === title ), embed, spoiler);
  2668. if ( reaction ) reaction.removeEmoji();
  2669. }
  2670. else if ( threads.some( thread => thread.title === title ) ) {
  2671. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title === title ), embed, spoiler);
  2672. if ( reaction ) reaction.removeEmoji();
  2673. }
  2674. else if ( threads.some( thread => thread.title.toLowerCase() === title.toLowerCase() ) ) {
  2675. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase() === title.toLowerCase() ), embed, spoiler);
  2676. if ( reaction ) reaction.removeEmoji();
  2677. }
  2678. else if ( threads.some( thread => thread.title.includes( title ) ) ) {
  2679. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.includes( title ) ), embed, spoiler);
  2680. if ( reaction ) reaction.removeEmoji();
  2681. }
  2682. else if ( threads.some( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2683. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2684. if ( reaction ) reaction.removeEmoji();
  2685. }
  2686. else if ( /^\d+$/.test(title) ) {
  2687. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads/' + title + '?format=json', {
  2688. headers: {
  2689. Accept: 'application/hal+json'
  2690. },
  2691. responseType: 'json'
  2692. } ).then( thresponse => {
  2693. var thbody = thresponse.body;
  2694. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== title ) {
  2695. if ( thbody && thbody.status === 404 ) {
  2696. if (threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2697. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2698. }
  2699. else msg.reactEmoji('🤷');
  2700. }
  2701. else {
  2702. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  2703. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  2704. }
  2705. }
  2706. else fandom_discussionsend(lang, msg, wiki, thbody, embed, spoiler);
  2707. }, error => {
  2708. console.log( '- Error while getting the thread: ' + error );
  2709. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  2710. } ).finally( () => {
  2711. if ( reaction ) reaction.removeEmoji();
  2712. } );
  2713. }
  2714. else if ( threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2715. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2716. if ( reaction ) reaction.removeEmoji();
  2717. }
  2718. else {
  2719. msg.reactEmoji('🤷');
  2720. if ( reaction ) reaction.removeEmoji();
  2721. }
  2722. }
  2723. else {
  2724. msg.reactEmoji('🤷');
  2725. if ( reaction ) reaction.removeEmoji();
  2726. }
  2727. }, error => {
  2728. console.log( '- Error while getting the threads: ' + error );
  2729. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2730. if ( reaction ) reaction.removeEmoji();
  2731. } );
  2732. }
  2733. }
  2734. function fandom_discussionsend(lang, msg, wiki, discussion, embed, spoiler) {
  2735. if ( discussion.title ) {
  2736. embed.setTitle( discussion.title.escapeFormatting() );
  2737. var pagelink = wiki + 'f/p/' + ( discussion.threadId || discussion.id );
  2738. }
  2739. else {
  2740. if ( discussion._embedded.thread ) embed.setTitle( discussion._embedded.thread[0].title.escapeFormatting() );
  2741. var pagelink = wiki + 'f/p/' + discussion.threadId + '/r/' + discussion.id;
  2742. }
  2743. var text = '<' + pagelink + '>';
  2744. embed.setURL( pagelink ).setFooter( discussion.createdBy.name, discussion.createdBy.avatarUrl ).setTimestamp( discussion.creationDate.epochSecond * 1000 );
  2745. var description = '';
  2746. switch ( discussion.funnel ) {
  2747. case 'IMAGE':
  2748. embed.setImage( discussion._embedded.contentImages[0].url );
  2749. break;
  2750. case 'POLL':
  2751. discussion.poll.answers.forEach( answer => embed.addField( answer.text.escapeFormatting(), ( lang.discussion.votes[answer.votes] || lang.discussion.votes['*' + answer.votes % 100] || lang.discussion.votes['*' + answer.votes % 10] || lang.discussion.votes.default ).replace( '%s', answer.votes ), true ) );
  2752. break;
  2753. case 'QUIZ':
  2754. description = discussion.quiz.title.escapeFormatting();
  2755. if ( discussion._embedded.openGraph ) embed.setThumbnail( discussion._embedded.openGraph[0].imageUrl );
  2756. break;
  2757. default:
  2758. if ( discussion.jsonModel ) {
  2759. try {
  2760. description = discussion_formatting(JSON.parse(discussion.jsonModel)).replace( /(?:\*\*\*\*|(?<!\\)\_\_)/g, '' ).replace( /{@wiki}/g, wiki );
  2761. if ( discussion._embedded.contentImages.length ) {
  2762. if ( description.trim().endsWith( '{@0}' ) ) {
  2763. embed.setImage( discussion._embedded.contentImages[0].url );
  2764. description = description.replace( '{@0}', '' ).trim();
  2765. }
  2766. else {
  2767. description = description.replace( /\{\@(\d+)\}/g, (match, n) => {
  2768. return '[__' + lang.discussion.image.escapeFormatting() + '__](' + discussion._embedded.contentImages[n].url + ')';
  2769. } );
  2770. embed.setThumbnail( discussion._embedded.contentImages[0].url );
  2771. }
  2772. }
  2773. else embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  2774. }
  2775. catch ( jsonerror ) {
  2776. console.log( '- Error while getting the formatting: ' + jsonerror );
  2777. description = discussion.rawContent.escapeFormatting();
  2778. }
  2779. }
  2780. else if ( discussion.renderedContent ) {
  2781. var parser = new htmlparser.Parser( {
  2782. ontext: (htmltext) => {
  2783. description += htmltext.escapeFormatting();
  2784. },
  2785. onclosetag: (tagname) => {
  2786. if ( tagname === 'p' ) description += '\n';
  2787. }
  2788. }, {decodeEntities:true} );
  2789. parser.write( discussion.renderedContent );
  2790. parser.end();
  2791. }
  2792. else {
  2793. description = discussion.rawContent.escapeFormatting();
  2794. }
  2795. }
  2796. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2797. embed.setDescription( description );
  2798. msg.sendChannel( spoiler + text + spoiler, {embed} );
  2799. }
  2800. function gamepedia_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  2801. if ( args[0] ) {
  2802. var error = false;
  2803. var title = '';
  2804. var revision = 0;
  2805. var diff = 0;
  2806. var relative = 'prev';
  2807. if ( /^\d+$/.test(args[0]) ) {
  2808. revision = parseInt(args[0], 10);
  2809. if ( args[1] ) {
  2810. if ( /^\d+$/.test(args[1]) ) {
  2811. diff = parseInt(args[1], 10);
  2812. }
  2813. else if ( args[1] === 'prev' || args[1] === 'next' || args[1] === 'cur' ) {
  2814. relative = args[1];
  2815. }
  2816. else error = true;
  2817. }
  2818. }
  2819. else if ( args[0] === 'prev' || args[0] === 'next' || args[0] === 'cur' ) {
  2820. relative = args[0];
  2821. if ( args[1] ) {
  2822. if ( /^\d+$/.test(args[1]) ) {
  2823. revision = parseInt(args[1], 10);
  2824. }
  2825. else error = true;
  2826. }
  2827. else error = true;
  2828. }
  2829. else title = args.join(' ');
  2830. if ( error ) {
  2831. msg.reactEmoji('error');
  2832. if ( reaction ) reaction.removeEmoji();
  2833. }
  2834. else if ( diff ) {
  2835. gamepedia_diffsend(lang, msg, [diff, revision], wiki, reaction, spoiler);
  2836. }
  2837. else {
  2838. got.get( wiki + 'api.php?action=compare&prop=ids|diff' + ( title ? '&fromtitle=' + encodeURIComponent( title ) : '&fromrev=' + revision ) + '&torelative=' + relative + '&format=json', {
  2839. responseType: 'json'
  2840. } ).then( response => {
  2841. var body = response.body;
  2842. if ( body && body.warnings ) log_warn(body.warnings);
  2843. if ( response.statusCode !== 200 || !body || !body.compare ) {
  2844. var noerror = false;
  2845. if ( body && body.error ) {
  2846. switch ( body.error.code ) {
  2847. case 'nosuchrevid':
  2848. noerror = true;
  2849. break;
  2850. case 'missingtitle':
  2851. noerror = true;
  2852. break;
  2853. case 'invalidtitle':
  2854. noerror = true;
  2855. break;
  2856. case 'missingcontent':
  2857. noerror = true;
  2858. break;
  2859. default:
  2860. noerror = false;
  2861. }
  2862. }
  2863. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  2864. console.log( '- This wiki doesn\'t exist!' );
  2865. msg.reactEmoji('nowiki');
  2866. }
  2867. else if ( noerror ) {
  2868. msg.replyMsg( lang.diff.badrev );
  2869. }
  2870. else {
  2871. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2872. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + relative + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  2873. }
  2874. if ( reaction ) reaction.removeEmoji();
  2875. }
  2876. else {
  2877. if ( body.compare.fromarchive !== undefined || body.compare.toarchive !== undefined ) {
  2878. msg.reactEmoji('error');
  2879. if ( reaction ) reaction.removeEmoji();
  2880. } else {
  2881. var argids = [];
  2882. var ids = body.compare;
  2883. if ( ids.fromrevid && !ids.torevid ) argids = [ids.fromrevid];
  2884. else if ( !ids.fromrevid && ids.torevid ) argids = [ids.torevid];
  2885. else {
  2886. argids = [ids.torevid, ids.fromrevid];
  2887. var compare = ['', ''];
  2888. if ( ids.fromtexthidden === undefined && ids.totexthidden === undefined && ids['*'] !== undefined ) {
  2889. var more = '\n__' + lang.diff.info.more + '__';
  2890. var current_tag = '';
  2891. var small_prev_ins = '';
  2892. var small_prev_del = '';
  2893. var ins_length = more.length;
  2894. var del_length = more.length;
  2895. var added = false;
  2896. var parser = new htmlparser.Parser( {
  2897. onopentag: (tagname, attribs) => {
  2898. if ( tagname === 'ins' || tagname == 'del' ) {
  2899. current_tag = tagname;
  2900. }
  2901. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  2902. current_tag = tagname+'a';
  2903. }
  2904. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  2905. current_tag = tagname+"d";
  2906. }
  2907. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  2908. added = true;
  2909. }
  2910. },
  2911. ontext: (htmltext) => {
  2912. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  2913. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  2914. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  2915. else small_prev_ins += more;
  2916. }
  2917. if ( current_tag === 'del' && del_length <= 1000 ) {
  2918. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  2919. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  2920. else small_prev_del += more;
  2921. }
  2922. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  2923. ins_length += htmltext.escapeFormatting().length;
  2924. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  2925. else small_prev_ins += more;
  2926. }
  2927. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  2928. del_length += htmltext.escapeFormatting().length;
  2929. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  2930. else small_prev_del += more;
  2931. }
  2932. if ( added ) {
  2933. if ( htmltext === '+' && ins_length <= 1000 ) {
  2934. ins_length++;
  2935. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  2936. else small_prev_ins += more;
  2937. }
  2938. if ( htmltext === '−' && del_length <= 1000 ) {
  2939. del_length++;
  2940. if ( del_length <= 1000 ) small_prev_del += '\n';
  2941. else small_prev_del += more;
  2942. }
  2943. added = false;
  2944. }
  2945. },
  2946. onclosetag: (tagname) => {
  2947. if ( tagname === 'ins' ) {
  2948. current_tag = 'afterins';
  2949. } else if ( tagname === 'del' ) {
  2950. current_tag = 'afterdel';
  2951. } else {
  2952. current_tag = '';
  2953. }
  2954. }
  2955. }, {decodeEntities:true} );
  2956. parser.write( ids['*'] );
  2957. parser.end();
  2958. if ( small_prev_del.length ) {
  2959. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  2960. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  2961. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  2962. }
  2963. if ( small_prev_ins.length ) {
  2964. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  2965. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  2966. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  2967. }
  2968. }
  2969. else if ( ids.fromtexthidden !== undefined ) compare[0] = '__' + lang.diff.hidden + '__';
  2970. else if ( ids.totexthidden !== undefined ) compare[1] = '__' + lang.diff.hidden + '__';
  2971. }
  2972. gamepedia_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  2973. }
  2974. }
  2975. }, error => {
  2976. console.log( '- Error while getting the search results: ' + error );
  2977. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + relative + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  2978. if ( reaction ) reaction.removeEmoji();
  2979. } );
  2980. }
  2981. }
  2982. else {
  2983. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, {embed} );
  2984. else msg.reactEmoji('error');
  2985. if ( reaction ) reaction.removeEmoji();
  2986. }
  2987. }
  2988. function gamepedia_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  2989. got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=tags&tglimit=500&tgprop=displayname&prop=revisions&rvslots=main&rvprop=ids|timestamp|flags|user|size|comment|tags' + ( args.length === 1 || args[0] === args[1] ? '|content' : '' ) + '&revids=' + args.join('|') + '&format=json', {
  2990. responseType: 'json'
  2991. } ).then( response => {
  2992. var body = response.body;
  2993. if ( body && body.warnings ) log_warn(body.warnings);
  2994. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  2995. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  2996. console.log( '- This wiki doesn\'t exist!' );
  2997. msg.reactEmoji('nowiki');
  2998. }
  2999. else {
  3000. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3001. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3002. }
  3003. if ( reaction ) reaction.removeEmoji();
  3004. }
  3005. else {
  3006. if ( body.query.badrevids ) {
  3007. msg.replyMsg( lang.diff.badrev );
  3008. if ( reaction ) reaction.removeEmoji();
  3009. }
  3010. else if ( body.query.pages && !body.query.pages['-1'] ) {
  3011. var pages = Object.values(body.query.pages);
  3012. if ( pages.length !== 1 ) {
  3013. msg.sendChannel( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0], '', '', body.query.general) + '>' + spoiler );
  3014. if ( reaction ) reaction.removeEmoji();
  3015. }
  3016. else {
  3017. var title = pages[0].title;
  3018. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  3019. var diff = revisions[0].revid;
  3020. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  3021. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  3022. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  3023. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  3024. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  3025. var comment = [lang.diff.info.comment, ( revisions[0].commenthidden !== undefined ? lang.diff.hidden : ( revisions[0].comment ? revisions[0].comment.toFormatting(msg.showEmbed(), wiki, body.query.general, title) : lang.diff.nocomment ) )];
  3026. 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(', ')];
  3027. var pagelink = wiki.toLink(title, 'diff=' + diff + '&oldid=' + oldid, '', body.query.general);
  3028. if ( msg.showEmbed() ) {
  3029. var text = '<' + pagelink + '>';
  3030. var editorlink = '[' + editor[1] + '](' + wiki.toLink('User:' + editor[1], '', '', body.query.general, true) + ')';
  3031. if ( revisions[0].anon !== undefined ) {
  3032. editorlink = '[' + editor[1] + '](' + wiki.toLink('Special:Contributions/' + editor[1], '', '', body.query.general, true) + ')';
  3033. }
  3034. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  3035. var embed = new Discord.MessageEmbed().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] );
  3036. if ( tags ) {
  3037. var taglink = '';
  3038. var tagtext = '';
  3039. var tagparser = new htmlparser.Parser( {
  3040. onopentag: (tagname, attribs) => {
  3041. if ( tagname === 'a' ) taglink = attribs.href;
  3042. },
  3043. ontext: (htmltext) => {
  3044. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  3045. else tagtext += htmltext.escapeFormatting();
  3046. },
  3047. onclosetag: (tagname) => {
  3048. if ( tagname === 'a' ) taglink = '';
  3049. }
  3050. }, {decodeEntities:true} );
  3051. tagparser.write( tags[1] );
  3052. tagparser.end();
  3053. embed.addField( tags[0], tagtext );
  3054. }
  3055. var more = '\n__' + lang.diff.info.more + '__';
  3056. if ( !compare && oldid ) got.get( wiki + 'api.php?action=compare&prop=diff&fromrev=' + oldid + '&torev=' + diff + '&format=json', {
  3057. responseType: 'json'
  3058. } ).then( cpresponse => {
  3059. var cpbody = cpresponse.body;
  3060. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  3061. if ( cpresponse.statusCode !== 200 || !cpbody || !cpbody.compare || cpbody.compare['*'] === undefined ) {
  3062. var noerror = false;
  3063. if ( cpbody && cpbody.error ) {
  3064. switch ( cpbody.error.code ) {
  3065. case 'nosuchrevid':
  3066. noerror = true;
  3067. break;
  3068. case 'missingcontent':
  3069. noerror = true;
  3070. break;
  3071. default:
  3072. noerror = false;
  3073. }
  3074. }
  3075. if ( !noerror ) console.log( '- ' + cpresponse.statusCode + ': Error while getting the diff: ' + ( cpbody && cpbody.error && cpbody.error.info ) );
  3076. }
  3077. else if ( cpbody.compare.fromtexthidden === undefined && cpbody.compare.totexthidden === undefined && cpbody.compare.fromarchive === undefined && cpbody.compare.toarchive === undefined ) {
  3078. var current_tag = '';
  3079. var small_prev_ins = '';
  3080. var small_prev_del = '';
  3081. var ins_length = more.length;
  3082. var del_length = more.length;
  3083. var added = false;
  3084. var parser = new htmlparser.Parser( {
  3085. onopentag: (tagname, attribs) => {
  3086. if ( tagname === 'ins' || tagname == 'del' ) {
  3087. current_tag = tagname;
  3088. }
  3089. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3090. current_tag = tagname+'a';
  3091. }
  3092. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3093. current_tag = tagname+"d";
  3094. }
  3095. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3096. added = true;
  3097. }
  3098. },
  3099. ontext: (htmltext) => {
  3100. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3101. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3102. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3103. else small_prev_ins += more;
  3104. }
  3105. if ( current_tag === 'del' && del_length <= 1000 ) {
  3106. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3107. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3108. else small_prev_del += more;
  3109. }
  3110. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3111. ins_length += htmltext.escapeFormatting().length;
  3112. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3113. else small_prev_ins += more;
  3114. }
  3115. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3116. del_length += htmltext.escapeFormatting().length;
  3117. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3118. else small_prev_del += more;
  3119. }
  3120. if ( added ) {
  3121. if ( htmltext === '+' && ins_length <= 1000 ) {
  3122. ins_length++;
  3123. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3124. else small_prev_ins += more;
  3125. }
  3126. if ( htmltext === '−' && del_length <= 1000 ) {
  3127. del_length++;
  3128. if ( del_length <= 1000 ) small_prev_del += '\n';
  3129. else small_prev_del += more;
  3130. }
  3131. added = false;
  3132. }
  3133. },
  3134. onclosetag: (tagname) => {
  3135. if ( tagname === 'ins' ) {
  3136. current_tag = 'afterins';
  3137. } else if ( tagname === 'del' ) {
  3138. current_tag = 'afterdel';
  3139. } else {
  3140. current_tag = '';
  3141. }
  3142. }
  3143. }, {decodeEntities:true} );
  3144. parser.write( cpbody.compare['*'] );
  3145. parser.end();
  3146. if ( small_prev_del.length ) {
  3147. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3148. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  3149. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  3150. }
  3151. if ( small_prev_ins.length ) {
  3152. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3153. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  3154. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3155. }
  3156. }
  3157. else if ( cpbody.compare.fromtexthidden !== undefined ) {
  3158. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  3159. }
  3160. else if ( cpbody.compare.totexthidden !== undefined ) {
  3161. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  3162. }
  3163. }, error => {
  3164. console.log( '- Error while getting the diff: ' + error );
  3165. } ).finally( () => {
  3166. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3167. if ( reaction ) reaction.removeEmoji();
  3168. } );
  3169. else {
  3170. if ( compare ) {
  3171. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  3172. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  3173. }
  3174. else if ( revisions[0]['*'] ) {
  3175. var content = revisions[0]['*'].escapeFormatting();
  3176. if ( content.trim().length ) {
  3177. if ( content.length <= 1000 ) content = '**' + content + '**';
  3178. else {
  3179. content = content.substring(0, 1000 - more.length);
  3180. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  3181. }
  3182. embed.addField( lang.diff.info.added, content, true );
  3183. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3184. }
  3185. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3186. if ( reaction ) reaction.removeEmoji();
  3187. }
  3188. }
  3189. else {
  3190. var embed = {};
  3191. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  3192. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  3193. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3194. if ( reaction ) reaction.removeEmoji();
  3195. }
  3196. }
  3197. }
  3198. else {
  3199. msg.reactEmoji('error');
  3200. if ( reaction ) reaction.removeEmoji();
  3201. }
  3202. }
  3203. }, error => {
  3204. console.log( '- Error while getting the search results: ' + error );
  3205. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3206. if ( reaction ) reaction.removeEmoji();
  3207. } );
  3208. }
  3209. function fandom_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  3210. if ( args[0] ) {
  3211. var error = false;
  3212. var title = '';
  3213. var revision = 0;
  3214. var diff = 'prev';
  3215. if ( /^\d+$/.test(args[0]) ) {
  3216. revision = args[0];
  3217. if ( args[1] ) {
  3218. if ( /^\d+$/.test(args[1]) ) {
  3219. diff = args[1];
  3220. }
  3221. else if ( args[1] === 'prev' || args[1] === 'next' ) {
  3222. diff = args[1];
  3223. }
  3224. else error = true;
  3225. }
  3226. }
  3227. else if ( args[0] === 'prev' || args[0] === 'next' ) {
  3228. diff = args[0];
  3229. if ( args[1] ) {
  3230. if ( /^\d+$/.test(args[1]) ) {
  3231. revision = args[1];
  3232. }
  3233. else error = true;
  3234. }
  3235. else error = true;
  3236. }
  3237. else title = args.join(' ');
  3238. if ( error ) msg.reactEmoji('error');
  3239. else if ( /^\d+$/.test(diff) ) {
  3240. var argids = [];
  3241. if ( parseInt(revision, 10) > parseInt(diff, 10) ) argids = [revision, diff];
  3242. else if ( parseInt(revision, 10) === parseInt(diff, 10) ) argids = [revision];
  3243. else argids = [diff, revision];
  3244. fandom_diffsend(lang, msg, argids, wiki, reaction, spoiler);
  3245. }
  3246. else {
  3247. got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=' + ( title ? '&titles=' + encodeURIComponent( title ) : '&revids=' + revision ) + '&rvdiffto=' + diff + '&format=json', {
  3248. responseType: 'json'
  3249. } ).then( response => {
  3250. var body = response.body;
  3251. if ( body && body.warnings ) log_warn(body.warnings);
  3252. if ( response.statusCode !== 200 || !body || !body.query ) {
  3253. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3254. console.log( '- This wiki doesn\'t exist!' );
  3255. msg.reactEmoji('nowiki');
  3256. }
  3257. else {
  3258. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3259. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + diff + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  3260. }
  3261. if ( reaction ) reaction.removeEmoji();
  3262. }
  3263. else {
  3264. if ( body.query.badrevids ) {
  3265. msg.replyMsg( lang.diff.badrev );
  3266. if ( reaction ) reaction.removeEmoji();
  3267. } else if ( body.query.pages && !body.query.pages[-1] ) {
  3268. var revisions = Object.values(body.query.pages)[0].revisions[0];
  3269. if ( revisions.texthidden === undefined ) {
  3270. var argids = [];
  3271. var ids = revisions.diff;
  3272. if ( !ids.from ) argids = [ids.to];
  3273. else {
  3274. argids = [ids.to, ids.from];
  3275. var compare = ['', ''];
  3276. if ( ids['*'] !== undefined ) {
  3277. var more = '\n__' + lang.diff.info.more + '__';
  3278. var current_tag = '';
  3279. var small_prev_ins = '';
  3280. var small_prev_del = '';
  3281. var ins_length = more.length;
  3282. var del_length = more.length;
  3283. var added = false;
  3284. var parser = new htmlparser.Parser( {
  3285. onopentag: (tagname, attribs) => {
  3286. if ( tagname === 'ins' || tagname == 'del' ) {
  3287. current_tag = tagname;
  3288. }
  3289. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3290. current_tag = tagname+'a';
  3291. }
  3292. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3293. current_tag = tagname+"d";
  3294. }
  3295. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3296. added = true;
  3297. }
  3298. },
  3299. ontext: (htmltext) => {
  3300. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3301. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3302. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3303. else small_prev_ins += more;
  3304. }
  3305. if ( current_tag === 'del' && del_length <= 1000 ) {
  3306. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3307. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3308. else small_prev_del += more;
  3309. }
  3310. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3311. ins_length += htmltext.escapeFormatting().length;
  3312. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3313. else small_prev_ins += more;
  3314. }
  3315. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3316. del_length += htmltext.escapeFormatting().length;
  3317. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3318. else small_prev_del += more;
  3319. }
  3320. if ( added ) {
  3321. if ( htmltext === '+' && ins_length <= 1000 ) {
  3322. ins_length++;
  3323. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3324. else small_prev_ins += more;
  3325. }
  3326. if ( htmltext === '−' && del_length <= 1000 ) {
  3327. del_length++;
  3328. if ( del_length <= 1000 ) small_prev_del += '\n';
  3329. else small_prev_del += more;
  3330. }
  3331. added = false;
  3332. }
  3333. },
  3334. onclosetag: (tagname) => {
  3335. if ( tagname === 'ins' ) {
  3336. current_tag = 'afterins';
  3337. } else if ( tagname === 'del' ) {
  3338. current_tag = 'afterdel';
  3339. } else {
  3340. current_tag = '';
  3341. }
  3342. }
  3343. }, {decodeEntities:true} );
  3344. parser.write( ids['*'] );
  3345. parser.end();
  3346. if ( small_prev_del.length ) {
  3347. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3348. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  3349. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  3350. }
  3351. if ( small_prev_ins.length ) {
  3352. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3353. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  3354. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  3355. }
  3356. }
  3357. }
  3358. fandom_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  3359. } else {
  3360. msg.replyMsg( lang.diff.badrev );
  3361. if ( reaction ) reaction.removeEmoji();
  3362. }
  3363. } else {
  3364. if ( body.query.pages && body.query.pages[-1] ) msg.replyMsg( lang.diff.badrev );
  3365. else msg.reactEmoji('error');
  3366. if ( reaction ) reaction.removeEmoji();
  3367. }
  3368. }
  3369. }, error => {
  3370. console.log( '- Error while getting the search results: ' + error );
  3371. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + diff + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  3372. if ( reaction ) reaction.removeEmoji();
  3373. } );
  3374. }
  3375. }
  3376. else {
  3377. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, {embed} );
  3378. else msg.reactEmoji('error');
  3379. if ( reaction ) reaction.removeEmoji();
  3380. }
  3381. }
  3382. function fandom_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  3383. got.get( 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', {
  3384. responseType: 'json'
  3385. } ).then( response => {
  3386. var body = response.body;
  3387. if ( body && body.warnings ) log_warn(body.warnings);
  3388. if ( response.statusCode !== 200 || !body || !body.query ) {
  3389. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3390. console.log( '- This wiki doesn\'t exist!' );
  3391. msg.reactEmoji('nowiki');
  3392. }
  3393. else {
  3394. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3395. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3396. }
  3397. if ( reaction ) reaction.removeEmoji();
  3398. }
  3399. else {
  3400. if ( body.query.badrevids ) {
  3401. msg.replyMsg( lang.diff.badrev );
  3402. if ( reaction ) reaction.removeEmoji();
  3403. }
  3404. else if ( body.query.pages && !body.query.pages['-1'] ) {
  3405. var pages = Object.values(body.query.pages);
  3406. if ( pages.length !== 1 ) {
  3407. msg.sendChannel( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0], '', '', body.query.general) + '>' + spoiler );
  3408. if ( reaction ) reaction.removeEmoji();
  3409. }
  3410. else {
  3411. var title = pages[0].title;
  3412. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  3413. var diff = revisions[0].revid;
  3414. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  3415. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  3416. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  3417. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  3418. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  3419. var comment = [lang.diff.info.comment, ( revisions[0].commenthidden !== undefined ? lang.diff.hidden : ( revisions[0].comment ? revisions[0].comment.toFormatting(msg.showEmbed(), wiki, body.query.general, title) : lang.diff.nocomment ) )];
  3420. 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(', ')];
  3421. var pagelink = wiki.toLink(title, 'diff=' + diff + '&oldid=' + oldid, '', body.query.general);
  3422. if ( msg.showEmbed() ) {
  3423. var text = '<' + pagelink + '>';
  3424. var editorlink = '[' + editor[1] + '](' + wiki.toLink('User:' + editor[1], '', '', body.query.general, true) + ')';
  3425. if ( revisions[0].anon !== undefined ) {
  3426. editorlink = '[' + editor[1] + '](' + wiki.toLink('Special:Contributions/' + editor[1], '', '', body.query.general, true) + ')';
  3427. }
  3428. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  3429. var embed = new Discord.MessageEmbed().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] );
  3430. if ( tags ) {
  3431. var taglink = '';
  3432. var tagtext = '';
  3433. var tagparser = new htmlparser.Parser( {
  3434. onopentag: (tagname, attribs) => {
  3435. if ( tagname === 'a' ) taglink = attribs.href;
  3436. },
  3437. ontext: (htmltext) => {
  3438. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  3439. else tagtext += htmltext.escapeFormatting();
  3440. },
  3441. onclosetag: (tagname) => {
  3442. if ( tagname === 'a' ) taglink = '';
  3443. }
  3444. }, {decodeEntities:true} );
  3445. tagparser.write( tags[1] );
  3446. tagparser.end();
  3447. embed.addField( tags[0], tagtext );
  3448. }
  3449. var more = '\n__' + lang.diff.info.more + '__';
  3450. if ( !compare && oldid ) got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=&revids=' + oldid + '&rvdiffto=' + diff + '&format=json', {
  3451. responseType: 'json'
  3452. } ).then( cpresponse => {
  3453. var cpbody = cpresponse.body;
  3454. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  3455. if ( cpresponse.statusCode !== 200 || !cpbody || !cpbody.query || cpbody.query.badrevids || !cpbody.query.pages && cpbody.query.pages[-1] ) {
  3456. console.log( '- ' + cpresponse.statusCode + ': Error while getting the diff: ' + ( cpbody && cpbody.error && cpbody.error.info ) );
  3457. }
  3458. else {
  3459. var revision = Object.values(cpbody.query.pages)[0].revisions[0];
  3460. if ( revision.texthidden === undefined && revision.diff && revision.diff['*'] !== undefined ) {
  3461. var current_tag = '';
  3462. var small_prev_ins = '';
  3463. var small_prev_del = '';
  3464. var ins_length = more.length;
  3465. var del_length = more.length;
  3466. var added = false;
  3467. var parser = new htmlparser.Parser( {
  3468. onopentag: (tagname, attribs) => {
  3469. if ( tagname === 'ins' || tagname == 'del' ) {
  3470. current_tag = tagname;
  3471. }
  3472. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3473. current_tag = tagname+'a';
  3474. }
  3475. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3476. current_tag = tagname+"d";
  3477. }
  3478. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3479. added = true;
  3480. }
  3481. },
  3482. ontext: (htmltext) => {
  3483. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3484. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3485. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3486. else small_prev_ins += more;
  3487. }
  3488. if ( current_tag === 'del' && del_length <= 1000 ) {
  3489. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3490. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3491. else small_prev_del += more;
  3492. }
  3493. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3494. ins_length += htmltext.escapeFormatting().length;
  3495. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3496. else small_prev_ins += more;
  3497. }
  3498. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3499. del_length += htmltext.escapeFormatting().length;
  3500. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3501. else small_prev_del += more;
  3502. }
  3503. if ( added ) {
  3504. if ( htmltext === '+' && ins_length <= 1000 ) {
  3505. ins_length++;
  3506. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3507. else small_prev_ins += more;
  3508. }
  3509. if ( htmltext === '−' && del_length <= 1000 ) {
  3510. del_length++;
  3511. if ( del_length <= 1000 ) small_prev_del += '\n';
  3512. else small_prev_del += more;
  3513. }
  3514. added = false;
  3515. }
  3516. },
  3517. onclosetag: (tagname) => {
  3518. if ( tagname === 'ins' ) {
  3519. current_tag = 'afterins';
  3520. } else if ( tagname === 'del' ) {
  3521. current_tag = 'afterdel';
  3522. } else {
  3523. current_tag = '';
  3524. }
  3525. }
  3526. }, {decodeEntities:true} );
  3527. parser.write( revision.diff['*'] );
  3528. parser.end();
  3529. if ( small_prev_del.length ) {
  3530. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3531. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  3532. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  3533. }
  3534. if ( small_prev_ins.length ) {
  3535. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3536. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  3537. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3538. }
  3539. }
  3540. else if ( revision.texthidden !== undefined ) {
  3541. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  3542. }
  3543. else if ( revision.diff && revision.diff['*'] === undefined ) {
  3544. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  3545. }
  3546. }
  3547. }, error => {
  3548. console.log( '- Error while getting the diff: ' + error );
  3549. } ).finally( () => {
  3550. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3551. if ( reaction ) reaction.removeEmoji();
  3552. } );
  3553. else {
  3554. if ( compare ) {
  3555. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  3556. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  3557. }
  3558. else if ( revisions[0]['*'] ) {
  3559. var content = revisions[0]['*'].escapeFormatting();
  3560. if ( content.trim().length ) {
  3561. if ( content.length <= 1000 ) content = '**' + content + '**';
  3562. else {
  3563. content = content.substring(0, 1000 - more.length);
  3564. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  3565. }
  3566. embed.addField( lang.diff.info.added, content, true );
  3567. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3568. }
  3569. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3570. if ( reaction ) reaction.removeEmoji();
  3571. }
  3572. }
  3573. else {
  3574. var embed = {};
  3575. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  3576. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  3577. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3578. if ( reaction ) reaction.removeEmoji();
  3579. }
  3580. }
  3581. }
  3582. else {
  3583. msg.reactEmoji('error');
  3584. if ( reaction ) reaction.removeEmoji();
  3585. }
  3586. }
  3587. }, error => {
  3588. console.log( '- Error while getting the search results: ' + error );
  3589. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3590. if ( reaction ) reaction.removeEmoji();
  3591. } );
  3592. }
  3593. function gamepedia_random(lang, msg, wiki, reaction, spoiler) {
  3594. got.get( 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', {
  3595. responseType: 'json'
  3596. } ).then( response => {
  3597. var body = response.body;
  3598. if ( body && body.warnings ) log_warn(body.warnings);
  3599. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  3600. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3601. console.log( '- This wiki doesn\'t exist!' );
  3602. msg.reactEmoji('nowiki');
  3603. }
  3604. else {
  3605. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3606. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  3607. }
  3608. }
  3609. else {
  3610. var querypage = Object.values(body.query.pages)[0];
  3611. var pagelink = wiki.toLink(querypage.title, '', '', body.query.general);
  3612. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  3613. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  3614. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  3615. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  3616. embed.setTitle( displaytitle );
  3617. }
  3618. if ( querypage.pageprops && querypage.pageprops.description ) {
  3619. var description = htmlToPlain( querypage.pageprops.description );
  3620. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  3621. embed.setDescription( description );
  3622. }
  3623. else if ( querypage.extract ) {
  3624. var extract = querypage.extract.escapeFormatting();
  3625. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  3626. embed.setDescription( extract );
  3627. }
  3628. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  3629. embed.setThumbnail( querypage.original.source );
  3630. }
  3631. else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  3632. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  3633. }
  3634. }, error => {
  3635. console.log( '- Error while getting the search results: ' + error );
  3636. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  3637. } ).finally( () => {
  3638. if ( reaction ) reaction.removeEmoji();
  3639. } );
  3640. }
  3641. function fandom_random(lang, msg, wiki, reaction, spoiler) {
  3642. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=description&siprop=general&generator=random&grnnamespace=0&format=json', {
  3643. responseType: 'json'
  3644. } ).then( response => {
  3645. var body = response.body;
  3646. if ( body && body.warnings ) log_warn(body.warnings);
  3647. if ( response.statusCode !== 200 || !body || !body.query || !body.query.pages ) {
  3648. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3649. console.log( '- This wiki doesn\'t exist!' );
  3650. msg.reactEmoji('nowiki');
  3651. }
  3652. else {
  3653. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3654. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  3655. }
  3656. if ( reaction ) reaction.removeEmoji();
  3657. }
  3658. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  3659. return gamepedia_random(lang, msg, wiki, reaction, spoiler);
  3660. }
  3661. else {
  3662. var querypage = Object.values(body.query.pages)[0];
  3663. var pagelink = wiki.toLink(querypage.title, '', '', body.query.general);
  3664. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  3665. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  3666. embed.setDescription( body.query.allmessages[0]['*'] );
  3667. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  3668. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  3669. if ( reaction ) reaction.removeEmoji();
  3670. }
  3671. else got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  3672. var descbody = descresponse.body;
  3673. if ( descresponse.statusCode !== 200 || !descbody ) {
  3674. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  3675. } else {
  3676. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  3677. var parser = new htmlparser.Parser( {
  3678. onopentag: (tagname, attribs) => {
  3679. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  3680. var description = attribs.content.escapeFormatting();
  3681. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  3682. embed.setDescription( description );
  3683. }
  3684. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  3685. thumbnail = attribs.content;
  3686. }
  3687. }
  3688. }, {decodeEntities:true} );
  3689. parser.write( descbody );
  3690. parser.end();
  3691. embed.setThumbnail( thumbnail );
  3692. }
  3693. }, error => {
  3694. console.log( '- Error while getting the description: ' + error );
  3695. } ).finally( () => {
  3696. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  3697. if ( reaction ) reaction.removeEmoji();
  3698. } );
  3699. }
  3700. }, error => {
  3701. console.log( '- Error while getting the search results: ' + error );
  3702. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  3703. if ( reaction ) reaction.removeEmoji();
  3704. } );
  3705. }
  3706. function gamepedia_overview(lang, msg, wiki, reaction, spoiler) {
  3707. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-Wiki_Manager&amenableparser=true&siprop=general|statistics&titles=Special:Statistics&format=json', {
  3708. responseType: 'json'
  3709. } ).then( response => {
  3710. var body = response.body;
  3711. if ( body && body.warnings ) log_warn(body.warnings);
  3712. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  3713. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3714. console.log( '- This wiki doesn\'t exist!' );
  3715. msg.reactEmoji('nowiki');
  3716. }
  3717. else {
  3718. console.log( '- ' + response.statusCode + ': Error while getting the statistics: ' + ( body && body.error && body.error.info ) );
  3719. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  3720. }
  3721. if ( reaction ) reaction.removeEmoji();
  3722. }
  3723. else {
  3724. var site = false;
  3725. if ( allSites.some( site => site.wiki_domain === body.query.general.servername ) ) {
  3726. site = allSites.find( site => site.wiki_domain === body.query.general.servername );
  3727. var name = [lang.overview.name, site.wiki_display_name];
  3728. var created = [lang.overview.created, new Date(parseInt(site.created + '000', 10)).toLocaleString(lang.dateformat, timeoptions)];
  3729. var manager = [lang.overview.manager, site.wiki_managers];
  3730. var official = [lang.overview.official, ( site.official_wiki ? lang.overview.yes : lang.overview.no )];
  3731. var crossover = [lang.overview.crossover, ( site.wiki_crossover ? 'https://' + site.wiki_crossover + '/' : '' )];
  3732. var description = [lang.overview.description, site.wiki_description];
  3733. var image = [lang.overview.image, site.wiki_image];
  3734. if ( description[1] ) {
  3735. description[1] = description[1].escapeFormatting();
  3736. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  3737. }
  3738. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  3739. }
  3740. var articles = [lang.overview.articles, body.query.statistics.articles];
  3741. var pages = [lang.overview.pages, body.query.statistics.pages];
  3742. var edits = [lang.overview.edits, body.query.statistics.edits];
  3743. var users = [lang.overview.users, body.query.statistics.activeusers];
  3744. var title = body.query.pages['-1'].title;
  3745. var pagelink = wiki.toLink(title, '', '', body.query.general);
  3746. if ( msg.showEmbed() ) {
  3747. var text = '<' + pagelink + '>';
  3748. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( title.escapeFormatting() ).setURL( pagelink ).setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  3749. }
  3750. else {
  3751. var embed = {};
  3752. var text = '<' + pagelink + '>\n\n';
  3753. }
  3754. if ( wiki.isFandom() ) got.get( 'https://c.fandom.com/api/v1/Wikis/ByString?expand=true&includeDomain=true&limit=10&string=' + body.query.general.servername + body.query.general.scriptpath + '&format=json', {
  3755. responseType: 'json'
  3756. } ).then( ovresponse => {
  3757. var ovbody = ovresponse.body;
  3758. if ( ovresponse.statusCode !== 200 || !ovbody || ovbody.exception || !ovbody.items || !ovbody.items.length ) {
  3759. console.log( '- ' + ovresponse.statusCode + ': Error while getting the wiki details: ' + ( ovbody && ovbody.exception && ovbody.exception.details ) );
  3760. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  3761. if ( reaction ) reaction.removeEmoji();
  3762. }
  3763. else if ( ovbody.items.some( site => site.url === body.query.general.server + ( body.query.general.scriptpath ? body.query.general.scriptpath + '/' : '' ) ) ) {
  3764. site = ovbody.items.find( site => site.url === body.query.general.server + ( body.query.general.scriptpath ? body.query.general.scriptpath + '/' : '' ) );
  3765. var vertical = [lang.overview.vertical, site.hub];
  3766. var topic = [lang.overview.topic, site.topic];
  3767. var founder = [lang.overview.founder, site.founding_user_id];
  3768. var manager = [lang.overview.manager, body.query.allmessages[0]['*']];
  3769. var created = [lang.overview.created, new Date(site.creation_date).toLocaleString(lang.dateformat, timeoptions)];
  3770. var description = [lang.overview.description, site.desc];
  3771. var image = [lang.overview.image, site.image];
  3772. if ( description[1] ) {
  3773. description[1] = description[1].escapeFormatting();
  3774. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  3775. }
  3776. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  3777. if ( msg.showEmbed() ) {
  3778. embed.addField( vertical[0], vertical[1], true );
  3779. if ( topic[1] ) embed.addField( topic[0], topic[1], true );
  3780. }
  3781. else text += vertical.join(' ') + ( topic[1] ? '\n' + topic.join(' ') : '' );
  3782. if ( founder[1] > 0 ) got.get( wiki + 'api.php?action=query&list=users&usprop=&ususerids=' + founder[1] + '&format=json', {
  3783. responseType: 'json'
  3784. } ).then( usresponse => {
  3785. var usbody = usresponse.body;
  3786. if ( usbody && usbody.warnings ) log_warn(usbody.warnings);
  3787. if ( usresponse.statusCode !== 200 || !usbody || !usbody.query || !usbody.query.users || !usbody.query.users[0] ) {
  3788. console.log( '- ' + usresponse.statusCode + ': Error while getting the wiki founder: ' + ( usbody && usbody.error && usbody.error.info ) );
  3789. founder[1] = 'ID: ' + founder[1];
  3790. }
  3791. else {
  3792. var user = usbody.query.users[0].name;
  3793. if ( msg.showEmbed() ) founder[1] = '[' + user + '](' + wiki.toLink('User:' + user, '', '', body.query.general, true) + ')';
  3794. else founder[1] = user;
  3795. }
  3796. }, error => {
  3797. console.log( '- Error while getting the wiki founder: ' + error );
  3798. founder[1] = 'ID: ' + founder[1];
  3799. } ).finally( () => {
  3800. if ( msg.showEmbed() ) {
  3801. embed.addField( founder[0], founder[1], true );
  3802. if ( manager[1] ) embed.addField( manager[0], '[' + manager[1] + '](' + wiki.toLink('User:' + manager[1], '', '', body.query.general, true) + ') ([' + lang.overview.talk + '](' + wiki.toLink('User talk:' + manager[1], '', '', body.query.general, true) + '))', true );
  3803. embed.addField( created[0], created[1], true ).addField( articles[0], articles[1], true ).addField( pages[0], pages[1], true ).addField( edits[0], edits[1], true ).addField( users[0], users[1], true ).setFooter( lang.overview.inaccurate );
  3804. if ( description[1] ) embed.addField( description[0], description[1] );
  3805. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  3806. }
  3807. else {
  3808. text += '\n' + founder.join(' ') + ( manager[1] ? '\n' + manager.join(' ') : '' ) + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  3809. if ( description[1] ) text += '\n' + description.join(' ');
  3810. if ( image[1] ) {
  3811. text += '\n' + image.join(' ');
  3812. if ( msg.uploadFiles() ) embed.files = [image[1]];
  3813. }
  3814. text += '\n\n*' + lang.overview.inaccurate + '*';
  3815. }
  3816. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3817. if ( reaction ) reaction.removeEmoji();
  3818. } );
  3819. else {
  3820. founder[1] = lang.overview.none;
  3821. if ( msg.showEmbed() ) {
  3822. embed.addField( founder[0], founder[1], true ).addField( created[0], created[1], true ).addField( articles[0], articles[1], true ).addField( pages[0], pages[1], true ).addField( edits[0], edits[1], true ).addField( users[0], users[1], true ).setFooter( lang.overview.inaccurate );
  3823. if ( description[1] ) embed.addField( description[0], description[1] );
  3824. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  3825. }
  3826. else {
  3827. text += '\n' + founder.join(' ') + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  3828. if ( description[1] ) text += '\n' + description.join(' ');
  3829. if ( image[1] ) {
  3830. text += '\n' + image.join(' ');
  3831. if ( msg.uploadFiles() ) embed.files = [image[1]];
  3832. }
  3833. text += '\n\n*' + lang.overview.inaccurate + '*';
  3834. }
  3835. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3836. if ( reaction ) reaction.removeEmoji();
  3837. }
  3838. }
  3839. else {
  3840. if ( msg.showEmbed() ) 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 );
  3841. else text = articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ') + '\n\n*' + lang.overview.inaccurate + '*';
  3842. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3843. if ( reaction ) reaction.removeEmoji();
  3844. }
  3845. }, error => {
  3846. console.log( '- Error while getting the wiki details: ' + error );
  3847. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  3848. if ( reaction ) reaction.removeEmoji();
  3849. } );
  3850. else {
  3851. if ( msg.showEmbed() ) {
  3852. if ( site ) {
  3853. var managerlist = manager[1].map( wm => '[' + wm + '](' + wiki.toLink('User:' + wm, '', '', body.query.general, true) + ') ([' + lang.overview.talk + '](' + wiki.toLink('User talk:' + wm, '', '', body.query.general, true) + '))' ).join('\n');
  3854. 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 );
  3855. }
  3856. 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 );
  3857. if ( site ) {
  3858. if ( crossover[1] ) embed.addField( crossover[0], crossover[1], true );
  3859. if ( description[1] ) embed.addField( description[0], description[1] );
  3860. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  3861. }
  3862. }
  3863. else {
  3864. if ( site ) text += name.join(' ') + '\n' + created.join(' ') + '\n' + manager[0] + ' ' + ( manager[1].join(', ') || lang.overview.none ) + '\n' + official.join(' ') + '\n';
  3865. text += articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  3866. if ( site ) {
  3867. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  3868. if ( description[1] ) text += '\n' + description.join(' ');
  3869. if ( image[1] ) {
  3870. text += '\n' + image.join(' ');
  3871. if ( msg.uploadFiles() ) embed.files = [{attachment:image[1],name:( spoiler ? 'SPOILER ' : '' ) + name[1] + image[1].substring(image[1].lastIndexOf('.'))}];
  3872. }
  3873. }
  3874. text += '\n\n*' + lang.overview.inaccurate + '*';
  3875. }
  3876. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3877. if ( reaction ) reaction.removeEmoji();
  3878. }
  3879. }
  3880. }, error => {
  3881. console.log( '- Error while getting the statistics: ' + error );
  3882. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  3883. if ( reaction ) reaction.removeEmoji();
  3884. } );
  3885. }
  3886. function fandom_overview(lang, msg, wiki, reaction, spoiler) {
  3887. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-Wiki_Manager&amenableparser=true&siprop=general|statistics|wikidesc&titles=Special:Statistics&format=json', {
  3888. responseType: 'json'
  3889. } ).then( response => {
  3890. var body = response.body;
  3891. if ( body && body.warnings ) log_warn(body.warnings);
  3892. if ( response.statusCode !== 200 || !body || !body.query || !body.query.pages ) {
  3893. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3894. console.log( '- This wiki doesn\'t exist!' );
  3895. msg.reactEmoji('nowiki');
  3896. }
  3897. else {
  3898. console.log( '- ' + response.statusCode + ': Error while getting the statistics: ' + ( body && body.error && body.error.info ) );
  3899. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  3900. }
  3901. if ( reaction ) reaction.removeEmoji();
  3902. }
  3903. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  3904. return gamepedia_overview(lang, msg, wiki, reaction, spoiler);
  3905. }
  3906. else got.get( 'https://community.fandom.com/api/v1/Wikis/Details?ids=' + body.query.wikidesc.id + '&format=json', {
  3907. responseType: 'json'
  3908. } ).then( ovresponse => {
  3909. var ovbody = ovresponse.body;
  3910. if ( ovresponse.statusCode !== 200 || !ovbody || ovbody.exception || !ovbody.items || !ovbody.items[body.query.wikidesc.id] ) {
  3911. console.log( '- ' + ovresponse.statusCode + ': Error while getting the wiki details: ' + ( ovbody && ovbody.exception && ovbody.exception.details ) );
  3912. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  3913. if ( reaction ) reaction.removeEmoji();
  3914. }
  3915. else {
  3916. var site = ovbody.items[body.query.wikidesc.id];
  3917. var vertical = [lang.overview.vertical, site.hub];
  3918. var topic = [lang.overview.topic, site.topic];
  3919. var founder = [lang.overview.founder, site.founding_user_id];
  3920. var manager = [lang.overview.manager, body.query.allmessages[0]['*']];
  3921. var created = [lang.overview.created, new Date(site.creation_date).toLocaleString(lang.dateformat, timeoptions)];
  3922. var articles = [lang.overview.articles, body.query.statistics.articles];
  3923. var pages = [lang.overview.pages, body.query.statistics.pages];
  3924. var edits = [lang.overview.edits, body.query.statistics.edits];
  3925. var users = [lang.overview.users, body.query.statistics.activeusers];
  3926. var description = [lang.overview.description, site.desc];
  3927. var image = [lang.overview.image, site.image];
  3928. if ( description[1] ) {
  3929. description[1] = description[1].escapeFormatting();
  3930. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  3931. }
  3932. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  3933. var title = body.query.pages['-1'].title;
  3934. var pagelink = wiki.toLink(title, '', '', body.query.general);
  3935. if ( msg.showEmbed() ) {
  3936. var text = '<' + pagelink + '>';
  3937. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( title.escapeFormatting() ).setURL( pagelink ).setThumbnail( site.wordmark ).addField( vertical[0], vertical[1], true );
  3938. if ( topic[1] ) embed.addField( topic[0], topic[1], true );
  3939. }
  3940. else {
  3941. var embed = {};
  3942. var text = '<' + pagelink + '>\n\n' + vertical.join(' ') + ( topic[1] ? '\n' + topic.join(' ') : '' );
  3943. }
  3944. if ( founder[1] > 0 ) got.get( wiki + 'api.php?action=query&list=users&usprop=&usids=' + founder[1] + '&format=json', {
  3945. responseType: 'json'
  3946. } ).then( usresponse => {
  3947. var usbody = usresponse.body;
  3948. if ( usbody && usbody.warnings ) log_warn(usbody.warnings);
  3949. if ( usresponse.statusCode !== 200 || !usbody || !usbody.query || !usbody.query.users || !usbody.query.users[0] ) {
  3950. console.log( '- ' + usresponse.statusCode + ': Error while getting the wiki founder: ' + ( usbody && usbody.error && usbody.error.info ) );
  3951. founder[1] = 'ID: ' + founder[1];
  3952. }
  3953. else {
  3954. var user = usbody.query.users[0].name;
  3955. if ( msg.showEmbed() ) founder[1] = '[' + user + '](' + wiki.toLink('User:' + user, '', '', body.query.general, true) + ')';
  3956. else founder[1] = user;
  3957. }
  3958. }, error => {
  3959. console.log( '- Error while getting the wiki founder: ' + error );
  3960. founder[1] = 'ID: ' + founder[1];
  3961. } ).finally( () => {
  3962. if ( msg.showEmbed() ) {
  3963. embed.addField( founder[0], founder[1], true );
  3964. if ( manager[1] ) embed.addField( manager[0], '[' + manager[1] + '](' + wiki.toLink('User:' + manager[1], '', '', body.query.general, true) + ') ([' + lang.overview.talk + '](' + wiki.toLink('User talk:' + manager[1], '', '', body.query.general, true) + '))', true );
  3965. embed.addField( created[0], created[1], true ).addField( articles[0], articles[1], true ).addField( pages[0], pages[1], true ).addField( edits[0], edits[1], true ).addField( users[0], users[1], true ).setFooter( lang.overview.inaccurate );
  3966. if ( description[1] ) embed.addField( description[0], description[1] );
  3967. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  3968. }
  3969. else {
  3970. text += '\n' + founder.join(' ') + ( manager[1] ? '\n' + manager.join(' ') : '' ) + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  3971. if ( description[1] ) text += '\n' + description.join(' ');
  3972. if ( image[1] ) {
  3973. text += '\n' + image.join(' ');
  3974. if ( msg.uploadFiles() ) embed.files = [image[1]];
  3975. }
  3976. text += '\n\n*' + lang.overview.inaccurate + '*';
  3977. }
  3978. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3979. if ( reaction ) reaction.removeEmoji();
  3980. } );
  3981. else {
  3982. founder[1] = lang.overview.none;
  3983. if ( msg.showEmbed() ) {
  3984. embed.addField( founder[0], founder[1], true ).addField( created[0], created[1], true ).addField( articles[0], articles[1], true ).addField( pages[0], pages[1], true ).addField( edits[0], edits[1], true ).addField( users[0], users[1], true ).setFooter( lang.overview.inaccurate );
  3985. if ( description[1] ) embed.addField( description[0], description[1] );
  3986. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  3987. }
  3988. else {
  3989. text += '\n' + founder.join(' ') + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  3990. if ( description[1] ) text += '\n' + description.join(' ');
  3991. if ( image[1] ) {
  3992. text += '\n' + image.join(' ');
  3993. if ( msg.uploadFiles() ) embed.files = [image[1]];
  3994. }
  3995. text += '\n\n*' + lang.overview.inaccurate + '*';
  3996. }
  3997. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3998. if ( reaction ) reaction.removeEmoji();
  3999. }
  4000. }
  4001. }, error => {
  4002. console.log( '- Error while getting the wiki details: ' + error );
  4003. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4004. if ( reaction ) reaction.removeEmoji();
  4005. } );
  4006. }, error => {
  4007. console.log( '- Error while getting the statistics: ' + error );
  4008. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4009. if ( reaction ) reaction.removeEmoji();
  4010. } );
  4011. }
  4012. function minecraft_bug(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4013. var invoke = args[0];
  4014. args = args.slice(1);
  4015. if ( invoke && /\d+$/.test(invoke) && !args.length ) {
  4016. if ( /^\d+$/.test(invoke) ) invoke = 'MC-' + invoke;
  4017. var link = 'https://bugs.mojang.com/browse/';
  4018. got.get( 'https://bugs.mojang.com/rest/api/2/issue/' + encodeURIComponent( invoke ) + '?fields=summary,issuelinks,fixVersions,resolution,status', {
  4019. responseType: 'json'
  4020. } ).then( response => {
  4021. var body = response.body;
  4022. if ( response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  4023. if ( body && body.errorMessages ) {
  4024. if ( body.errorMessages.includes( 'Issue Does Not Exist' ) ) {
  4025. msg.reactEmoji('🤷');
  4026. }
  4027. else if ( body.errorMessages.includes( 'You do not have the permission to see the specified issue.' ) ) {
  4028. msg.sendChannel( spoiler + mclang.bug.private + '\n<' + link + invoke + '>' + spoiler );
  4029. }
  4030. else {
  4031. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + body.errorMessages.join(' - ') );
  4032. msg.reactEmoji('error');
  4033. }
  4034. }
  4035. else {
  4036. console.log( '- ' + response.statusCode + ': Error while getting the issue: ' + ( body && body.message ) );
  4037. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  4038. else msg.sendChannelError( spoiler + '<' + link + invoke + '>' + spoiler );
  4039. }
  4040. }
  4041. else {
  4042. if ( !body.fields ) {
  4043. msg.reactEmoji('error');
  4044. }
  4045. else {
  4046. var bugs = body.fields.issuelinks.filter( bug => bug.outwardIssue || ( bug.inwardIssue && bug.type.name != 'Duplicate' ) );
  4047. if ( bugs.length ) {
  4048. var embed = new Discord.MessageEmbed();
  4049. var extrabugs = [];
  4050. bugs.forEach( bug => {
  4051. var ward = ( bug.outwardIssue ? 'outward' : 'inward' );
  4052. var issue = bug[ward + 'Issue'];
  4053. var name = bug.type[ward] + ' ' + issue.key;
  4054. var value = issue.fields.status.name + ': [' + issue.fields.summary.escapeFormatting() + '](' + link + issue.key + ')';
  4055. if ( embed.fields.length < 25 ) embed.addField( name, value );
  4056. else extrabugs.push({name,value,inline:false});
  4057. } );
  4058. if ( extrabugs.length ) embed.setFooter( mclang.bug.more.replaceSave( '%s', extrabugs.length ) );
  4059. }
  4060. var status = '**' + ( body.fields.resolution ? body.fields.resolution.name : body.fields.status.name ) + ':** ';
  4061. var fixed = '';
  4062. if ( body.fields.resolution && body.fields.fixVersions && body.fields.fixVersions.length ) {
  4063. fixed = '\n' + mclang.bug.fixed + ' ' + body.fields.fixVersions.map( v => v.name ).join(', ');
  4064. }
  4065. msg.sendChannel( spoiler + status + body.fields.summary.escapeFormatting() + '\n<' + link + body.key + '>' + fixed + spoiler, {embed} );
  4066. }
  4067. }
  4068. }, error => {
  4069. console.log( '- Error while getting the issue: ' + error );
  4070. msg.sendChannelError( spoiler + '<' + link + invoke + '>' + spoiler );
  4071. } ).finally( () => {
  4072. if ( reaction ) reaction.removeEmoji();
  4073. } );
  4074. }
  4075. else if ( invoke && invoke.toLowerCase() === 'version' && args.length && args.join(' ').length < 100 ) {
  4076. var jql = 'fixVersion="' + args.join(' ').replace( /(["\\])/g, '\\$1' ).toSearch() + '"+order+by+key';
  4077. var link = 'https://bugs.mojang.com/issues/?jql=' + jql;
  4078. got.get( 'https://bugs.mojang.com/rest/api/2/search?fields=summary,resolution,status&jql=' + jql + '&maxResults=25', {
  4079. responseType: 'json'
  4080. } ).then( response => {
  4081. var body = response.body;
  4082. if ( response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  4083. if ( body && body.errorMessages ) {
  4084. if ( body.errorMessages.includes( 'The value \'' + args.join(' ') + '\' does not exist for the field \'fixVersion\'.' ) ) {
  4085. msg.reactEmoji('🤷');
  4086. }
  4087. else {
  4088. console.log( '- ' + response.statusCode + ': Error while getting the issues: ' + body.errorMessages.join(' - ') );
  4089. msg.reactEmoji('error');
  4090. }
  4091. }
  4092. else {
  4093. console.log( '- ' + response.statusCode + ': Error while getting the issues: ' + ( body && body.message ) );
  4094. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  4095. else msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  4096. }
  4097. }
  4098. else {
  4099. if ( !body.issues ) {
  4100. msg.reactEmoji('error');
  4101. }
  4102. else {
  4103. if ( body.total > 0 ) {
  4104. var embed = new Discord.MessageEmbed();
  4105. body.issues.forEach( bug => {
  4106. var status = ( bug.fields.resolution ? bug.fields.resolution.name : bug.fields.status.name );
  4107. var value = status + ': [' + bug.fields.summary.escapeFormatting() + '](https://bugs.mojang.com/browse/' + bug.key + ')';
  4108. embed.addField( bug.key, value );
  4109. } );
  4110. if ( body.total > 25 ) embed.setFooter( mclang.bug.more.replaceSave( '%s', body.total - 25 ) );
  4111. }
  4112. var total = '**' + args.join(' ') + ':** ' + mclang.bug.total.replaceSave( '%s', body.total );
  4113. msg.sendChannel( spoiler + total + '\n<' + link + '>' + spoiler, {embed} );
  4114. }
  4115. }
  4116. }, error => {
  4117. console.log( '- Error while getting the issues: ' + error );
  4118. msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  4119. } ).finally( () => {
  4120. if ( reaction ) reaction.removeEmoji();
  4121. } );
  4122. }
  4123. else {
  4124. msg.notminecraft = true;
  4125. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4126. }
  4127. }
  4128. function minecraft_command(lang, mclang, msg, befehl, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4129. befehl = befehl.toLowerCase();
  4130. var aliasCmd = ( minecraft.cmd.aliase[befehl] || befehl );
  4131. if ( aliasCmd in minecraft.cmd.list ) {
  4132. var cmdSyntaxMap = minecraft.cmd.list[aliasCmd].map( command => {
  4133. var cmdargs = command.split(' ');
  4134. if ( cmdargs[0].startsWith( '/' ) ) cmdargs = cmdargs.slice(1);
  4135. var argmatches = cmdargs.map( (arg, i) => {
  4136. if ( arg === args[i] ) return true;
  4137. } );
  4138. var matchCount = 0;
  4139. argmatches.forEach( match => {
  4140. if ( match ) matchCount++;
  4141. } );
  4142. return [argmatches.lastIndexOf(true),matchCount];
  4143. } );
  4144. var lastIndex = Math.max(...cmdSyntaxMap.map( command => command[0] ));
  4145. var matchCount = Math.max(...cmdSyntaxMap.filter( command => command[0] === lastIndex ).map( command => command[1] ));
  4146. var regex = new RegExp('/' + aliasCmd, 'g');
  4147. var cmdSyntax = minecraft.cmd.list[aliasCmd].filter( (command, i) => ( lastIndex === -1 || cmdSyntaxMap[i][0] === lastIndex ) && cmdSyntaxMap[i][1] === matchCount ).join('\n').replaceSave( regex, '/' + befehl );
  4148. msg.sendChannel( spoiler + '```md\n' + cmdSyntax + '```<' + mclang.link + mclang.cmd.page + aliasCmd + '>' + spoiler, {split:{maxLength:2000,prepend:spoiler + '```md\n',append:'```' + spoiler}} );
  4149. if ( reaction ) reaction.removeEmoji();
  4150. }
  4151. else {
  4152. msg.reactEmoji('❓');
  4153. msg.notminecraft = true;
  4154. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4155. }
  4156. }
  4157. function minecraft_command2(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4158. if ( args.join('') ) {
  4159. if ( args[0].startsWith( '/' ) ) minecraft_command(lang, mclang, msg, args[0].substring(1), args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  4160. else minecraft_command(lang, mclang, msg, args[0], args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  4161. }
  4162. else {
  4163. msg.notminecraft = true;
  4164. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4165. }
  4166. }
  4167. function cmd_get(lang, msg, args, line, wiki) {
  4168. var id = args.join().replace( /^\\?<(?:@!?|#)(\d+)>$/, '$1' );
  4169. if ( /^\d+$/.test(id) ) {
  4170. if ( client.guilds.cache.has(id) ) {
  4171. var guild = client.guilds.cache.get(id);
  4172. var guildname = ['Guild:', guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( pause[guild.id] ? '\\*' : '' )];
  4173. var guildowner = ['Owner:', ( guild.owner ? guild.owner.user.tag.escapeFormatting() + ' `' + guild.ownerID + '` ' + guild.owner.toString() : '`' + guild.ownerID + '`' )];
  4174. var guildsize = ['Size:', guild.memberCount + ' members (' + guild.members.cache.filter( member => member.user.bot ).size + ' bots)'];
  4175. var guildpermissions = ['Missing permissions:', ( guild.me.permissions.has(defaultPermissions) ? '*none*' : '`' + guild.me.permissions.missing(defaultPermissions).join('`, `') + '`' )];
  4176. var guildsettings = ['Settings:', '*unknown*'];
  4177. db.all( 'SELECT channel, prefix, lang, wiki, inline FROM discord WHERE guild = ? ORDER BY channel ASC', [guild.id], (dberror, rows) => {
  4178. if ( dberror ) {
  4179. console.log( '- Error while getting the settings: ' + dberror );
  4180. }
  4181. else if ( rows.length ) {
  4182. row = rows.find( row => !row.channel );
  4183. row.patreon = guild.id in patreons;
  4184. row.voice = guild.id in voice;
  4185. guildsettings[1] = '```json\n' + JSON.stringify( rows, null, '\t' ) + '\n```';
  4186. }
  4187. else guildsettings[1] = '*default*';
  4188. if ( msg.showEmbed() ) {
  4189. var embed = new Discord.MessageEmbed().addField( guildname[0], guildname[1] ).addField( guildowner[0], guildowner[1] ).addField( guildsize[0], guildsize[1] ).addField( guildpermissions[0], guildpermissions[1] );
  4190. var split = Discord.Util.splitMessage( guildsettings[1], {char:',\n',maxLength:1000,prepend:'```json\n',append:',\n```'} );
  4191. if ( split.length > 5 ) {
  4192. msg.sendChannel( '', {embed}, true );
  4193. msg.sendChannel( guildsettings.join(' '), {split:{char:',\n',prepend:'```json\n',append:',\n```'}}, true );
  4194. }
  4195. else {
  4196. split.forEach( guildsettingspart => embed.addField( guildsettings[0], guildsettingspart ) );
  4197. msg.sendChannel( '', {embed}, true );
  4198. }
  4199. }
  4200. else {
  4201. var text = guildname.join(' ') + '\n' + guildowner.join(' ') + '\n' + guildsize.join(' ') + '\n' + guildpermissions.join(' ') + '\n' + guildsettings.join(' ');
  4202. msg.sendChannel( text, {split:{char:',\n',prepend:'```json\n',append:',\n```'}}, true );
  4203. }
  4204. } );
  4205. } else if ( client.guilds.cache.some( guild => guild.members.cache.has(id) ) ) {
  4206. var username = [];
  4207. var guildlist = ['Guilds:'];
  4208. var guilds = client.guilds.cache.filter( guild => guild.members.cache.has(id) );
  4209. guildlist.push('\n' + guilds.map( function(guild) {
  4210. var member = guild.members.cache.get(id);
  4211. if ( !username.length ) username.push('User:', member.user.tag.escapeFormatting() + ' `' + member.id + '` ' + member.toString());
  4212. return guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( member.permissions.has('MANAGE_GUILD') ? '\\*' : '' );
  4213. } ).join('\n'));
  4214. if ( guildlist[1].length > 1000 ) guildlist[1] = guilds.size;
  4215. if ( msg.showEmbed() ) {
  4216. var text = '';
  4217. var embed = new Discord.MessageEmbed().addField( username[0], username[1] ).addField( guildlist[0], guildlist[1] );
  4218. }
  4219. else {
  4220. var embed = {};
  4221. var text = username.join(' ') + '\n' + guildlist.join(' ');
  4222. }
  4223. msg.sendChannel( text, {embed}, true );
  4224. } else if ( client.guilds.cache.some( guild => guild.channels.cache.filter( chat => chat.type === 'text' ).has(id) ) ) {
  4225. var channel = client.guilds.cache.find( guild => guild.channels.cache.filter( chat => chat.type === 'text' ).has(id) ).channels.cache.get(id);
  4226. var channelguild = ['Guild:', channel.guild.name.escapeFormatting() + ' `' + channel.guild.id + '`' + ( pause[channel.guild.id] ? '\\*' : '' )];
  4227. var channelname = ['Channel:', '#' + channel.name.escapeFormatting() + ' `' + channel.id + '` ' + channel.toString()];
  4228. var channelpermissions = ['Missing permissions:', ( channel.permissionsFor(channel.guild.me).has(defaultPermissions) ? '*none*' : '`' + channel.permissionsFor(channel.guild.me).missing(defaultPermissions).join('`, `') + '`' )];
  4229. var channellang = ['Language:', '*unknown*'];
  4230. var channelwiki = ['Default Wiki:', '*unknown*'];
  4231. var channelinline = ['Inline commands:', '*unknown*'];
  4232. db.get( 'SELECT lang, wiki, inline FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [channel.guild.id, channel.id], (dberror, row) => {
  4233. if ( dberror ) {
  4234. console.log( '- Error while getting the settings: ' + dberror );
  4235. }
  4236. else if ( row ) {
  4237. channellang[1] = row.lang;
  4238. channelwiki[1] = row.wiki;
  4239. channelinline[1] = ( row.inline ? 'disabled' : 'enabled' );
  4240. }
  4241. else {
  4242. channellang[1] = defaultSettings.lang;
  4243. channelwiki[1] = defaultSettings.wiki;
  4244. channelinline[1] = 'enabled';
  4245. }
  4246. if ( msg.showEmbed() ) {
  4247. var text = '';
  4248. var embed = new Discord.MessageEmbed().addField( channelguild[0], channelguild[1] ).addField( channelname[0], channelname[1] ).addField( channelpermissions[0], channelpermissions[1] ).addField( channellang[0], channellang[1] ).addField( channelwiki[0], channelwiki[1] ).addField( channelinline[0], channelinline[1] );
  4249. }
  4250. else {
  4251. var embed = {};
  4252. var text = channelguild.join(' ') + '\n' + channelname.join(' ') + '\n' + channelpermissions.join(' ') + '\n' + channellang.join(' ') + '\n' + channelwiki[0] + ' <' + channelwiki[1] + '>\n' + channelinline.join(' ');
  4253. }
  4254. msg.sendChannel( text, {embed}, true );
  4255. } );
  4256. } else msg.replyMsg( 'I couldn\'t find a result for `' + id + '`', {}, true );
  4257. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4258. }
  4259. function cmd_patreon(lang, msg, args, line, wiki) {
  4260. if ( msg.channel.id !== process.env.channel || !args.join('') ) {
  4261. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4262. return;
  4263. }
  4264. if ( args[0] === 'enable' && /^\d+$/.test(args.slice(1).join(' ')) ) {
  4265. if ( !client.guilds.cache.has(args[1]) ) return msg.replyMsg( 'I\'m not on a server with the id `' + args[1] + '`.', {}, true );
  4266. if ( args[1] in patreons ) return msg.replyMsg( '"' + client.guilds.cache.get(args[1]) + '" has the patreon features already enabled.', {}, true );
  4267. return db.get( 'SELECT count, COUNT(guild) guilds FROM patreons LEFT JOIN discord ON discord.patreon = patreons.patreon WHERE patreons.patreon = ? GROUP BY patreons.patreon', [msg.author.id], (dberror, row) => {
  4268. if ( dberror ) {
  4269. console.log( '- Error while getting the patreon: ' + dberror );
  4270. msg.replyMsg( 'I got an error while searching for you, please try again later.', {}, true );
  4271. return dberror;
  4272. }
  4273. if ( !row ) return msg.replyMsg( 'you can\'t have any server.', {}, true );
  4274. if ( row.count <= row.guilds ) return msg.replyMsg( 'you already reached your maximal server count.', {}, true );
  4275. db.run( 'UPDATE discord SET patreon = ? WHERE guild = ? AND channel IS NULL', [msg.author.id, args[1]], function (error) {
  4276. if ( error ) {
  4277. console.log( '- Error while updating the guild: ' + error );
  4278. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4279. return error;
  4280. }
  4281. if ( !this.changes ) return db.run( 'INSERT INTO discord(guild, patreon) VALUES(?, ?)', [args[1], msg.author.id], function (inserror) {
  4282. if ( inserror ) {
  4283. console.log( '- Error while adding the guild: ' + inserror );
  4284. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4285. return inserror;
  4286. }
  4287. console.log( '- Guild successfully added.' );
  4288. patreons[args[1]] = process.env.prefix;
  4289. msg.replyMsg( 'the patreon features are now enabled on "' + client.guilds.cache.get(args[1]) + '".', {}, true );
  4290. } );
  4291. console.log( '- Guild successfully updated.' );
  4292. patreons[args[1]] = process.env.prefix;
  4293. msg.replyMsg( 'the patreon features are now enabled on "' + client.guilds.cache.get(args[1]) + '".', {}, true );
  4294. } );
  4295. } );
  4296. }
  4297. if ( args[0] === 'disable' && /^\d+$/.test(args.slice(1).join(' ')) ) {
  4298. if ( !client.guilds.cache.has(args[1]) ) return msg.replyMsg( 'I\'m not on a server with the id `' + args[1] + '`.', {}, true );
  4299. if ( !( args[1] in patreons ) ) return msg.replyMsg( '"' + client.guilds.cache.get(args[1]) + '" doesn\'t have the patreon features enabled.', {}, true );
  4300. return db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND patreon = ?', [args[1], msg.author.id], (dberror, row) => {
  4301. if ( dberror ) {
  4302. console.log( '- Error while getting the guild: ' + dberror );
  4303. msg.replyMsg( 'I got an error while searching for the server, please try again later.', {}, true );
  4304. return dberror;
  4305. }
  4306. if ( !row ) return msg.replyMsg( 'you didn\'t enable the patreon features for "' + client.guilds.cache.get(args[1]) + '"!', {}, true );
  4307. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, args[1]], function (error) {
  4308. if ( error ) {
  4309. console.log( '- Error while updating the guild: ' + error );
  4310. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4311. return error;
  4312. }
  4313. console.log( '- Guild successfully updated.' );
  4314. delete patreons[args[1]];
  4315. msg.replyMsg( 'the patreon features are now disabled on "' + client.guilds.cache.get(args[1]) + '".', {}, true );
  4316. } );
  4317. } );
  4318. }
  4319. if ( args[1] ) args[1] = args[1].replace( /^\\?<@!?(\d+)>$/, '$1' );
  4320. if ( args[0] === 'check' ) {
  4321. if ( !args.slice(1).join('') ) return db.get( 'SELECT count, GROUP_CONCAT(guild) guilds FROM patreons LEFT JOIN discord ON discord.patreon = patreons.patreon WHERE patreons.patreon = ? GROUP BY patreons.patreon', [msg.author.id], (dberror, row) => {
  4322. if ( dberror ) {
  4323. console.log( '- Error while getting the patreon: ' + dberror );
  4324. msg.replyMsg( 'I got an error while searching for you, please try again later.', {}, true );
  4325. return dberror;
  4326. }
  4327. if ( !row ) return msg.replyMsg( 'you can\'t have any server.', {}, true );
  4328. var text = 'you can have up to ' + row.count + ' server.\n\n';
  4329. if ( row.guilds ) {
  4330. var guilds = row.guilds.split(',').map( guild => '`' + guild + '` ' + ( client.guilds.cache.has(guild) ? client.guilds.cache.get(guild).name : '' ) );
  4331. text += 'Currently you have ' + guilds.length + ' server:\n' + guilds.join('\n');
  4332. }
  4333. else text += '*You don\'t have any server yet.*';
  4334. msg.replyMsg( text, {}, true );
  4335. } );
  4336. if ( msg.isOwner() && /^\d+$/.test(args.slice(1).join(' ')) ) return db.get( 'SELECT count, GROUP_CONCAT(guild) guilds FROM patreons LEFT JOIN discord ON discord.patreon = patreons.patreon WHERE patreons.patreon = ? GROUP BY patreons.patreon', [args[1]], (dberror, row) => {
  4337. if ( dberror ) {
  4338. console.log( '- Error while getting the patreon: ' + dberror );
  4339. msg.replyMsg( 'I got an error while searching for <@' + args[1] + '>, please try again later.', {}, true );
  4340. return dberror;
  4341. }
  4342. if ( !row ) return msg.replyMsg( '<@' + args[1] + '> can\'t have any server.', {}, true );
  4343. var text = '<@' + args[1] + '> can have up to ' + row.count + ' server.\n\n';
  4344. if ( row.guilds ) {
  4345. var guilds = row.guilds.split(',').map( guild => '`' + guild + '` ' + ( client.guilds.cache.has(guild) ? client.guilds.cache.get(guild).name : '' ) );
  4346. text += 'Currently they have ' + guilds.length + ' server:\n' + guilds.join('\n');
  4347. }
  4348. else text += '*They don\'t have any server yet.*';
  4349. msg.replyMsg( text, {}, true );
  4350. } );
  4351. }
  4352. if ( args[0] === 'edit' && msg.isOwner() && /^\d+ [\+\-]?\d+$/.test(args.slice(1).join(' ')) ) return db.get( 'SELECT count, GROUP_CONCAT(guild) guilds FROM patreons LEFT JOIN discord ON discord.patreon = patreons.patreon WHERE patreons.patreon = ? GROUP BY patreons.patreon', [args[1]], (dberror, row) => {
  4353. if ( dberror ) {
  4354. console.log( '- Error while getting the patreon: ' + dberror );
  4355. msg.replyMsg( 'I got an error while searching for <@' + args[1] + '>, please try again later.', {}, true );
  4356. return dberror;
  4357. }
  4358. var value = parseInt(args[2], 10);
  4359. var count = ( row ? row.count : 0 );
  4360. var guilds = ( row && row.guilds ? row.guilds.split(',') : [] );
  4361. if ( args[2].startsWith( '+' ) || args[2].startsWith( '-' ) ) count += value;
  4362. else count = value;
  4363. if ( count <= 0 ) return db.run( 'DELETE FROM patreons WHERE patreon = ?', [args[1]], function (error) {
  4364. if ( error ) {
  4365. console.log( '- Error while deleting the patreon: ' + error );
  4366. msg.replyMsg( 'I got an error while deleting <@' + args[1] + '>, please try again later.', {}, true );
  4367. return error;
  4368. }
  4369. console.log( '- Patreon successfully deleted.' );
  4370. if ( !guilds.length ) return msg.replyMsg( '<@' + args[1] + '> is no longer a patreon.', {}, true );
  4371. db.each( 'SELECT guild, lang, inline FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ') AND channel IS NULL', guilds, (eacherror, eachrow) => {
  4372. if ( eacherror ) {
  4373. console.log( '- Error while getting the guild: ' + eacherror );
  4374. msg.replyMsg( 'I couldn\'t disable the patreon features.', {}, true );
  4375. return eacherror;
  4376. }
  4377. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ? WHERE guild = ?', [eachrow.lang, eachrow.inline, process.env.prefix, eachrow.guild], function (uperror) {
  4378. if ( uperror ) {
  4379. console.log( '- Error while updating the guild: ' + uperror );
  4380. msg.replyMsg( 'I couldn\'t disable the patreon features for `' + eachrow.guild + '`.', {}, true );
  4381. return uperror;
  4382. }
  4383. console.log( '- Guild successfully updated.' );
  4384. delete patreons[eachrow.guild];
  4385. } );
  4386. }, (eacherror) => {
  4387. if ( eacherror ) {
  4388. console.log( '- Error while getting the guilds: ' + eacherror );
  4389. msg.replyMsg( 'I couldn\'t disable the patreon features for `' + guilds.join('`, `') + '`.', {}, true );
  4390. return eacherror;
  4391. }
  4392. msg.replyMsg( '<@' + args[1] + '> is no longer a patreon.', {}, true );
  4393. } );
  4394. } );
  4395. if ( !row ) return db.run( 'INSERT INTO patreons(patreon, count) VALUES(?, ?)', [args[1], count], function (error) {
  4396. if ( error ) {
  4397. console.log( '- Error while adding the patreon: ' + error );
  4398. msg.replyMsg( 'I got an error while adding <@' + args[1] + '>, please try again later.', {}, true );
  4399. return error;
  4400. }
  4401. console.log( '- Patreon successfully added.' );
  4402. msg.replyMsg( '<@' + args[1] + '> can now have up to ' + count + ' server.', {}, true );
  4403. } );
  4404. db.run( 'UPDATE patreons SET count = ? WHERE patreon = ?', [count, args[1]], function (error) {
  4405. if ( error ) {
  4406. console.log( '- Error while updating the patreon: ' + error );
  4407. msg.replyMsg( 'I got an error while updating <@' + args[1] + '>, please try again later.', {}, true );
  4408. return error;
  4409. }
  4410. console.log( '- Patreon successfully updated.' );
  4411. var text = '<@' + args[1] + '> can now have up to ' + count + ' server.';
  4412. if ( count < guilds.length ) text += '\n\n**They are now above their server limit!**';
  4413. msg.replyMsg( text, {}, true );
  4414. } );
  4415. } );
  4416. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4417. }
  4418. function discussion_formatting(jsonModel) {
  4419. var description = '';
  4420. switch ( jsonModel.type ) {
  4421. case 'doc':
  4422. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  4423. break;
  4424. case 'paragraph':
  4425. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  4426. description += '\n';
  4427. break;
  4428. case 'openGraph':
  4429. if ( !jsonModel.attrs.wasAddedWithInlineLink ) description += jsonModel.attrs.url + '\n';
  4430. break;
  4431. case 'text':
  4432. var prepend = '';
  4433. var append = '';
  4434. if ( jsonModel.marks ) {
  4435. jsonModel.marks.forEach( mark => {
  4436. switch ( mark.type ) {
  4437. case 'mention':
  4438. prepend += '[';
  4439. append = ']({@wiki}f/u/' + mark.attrs.userId + ')' + append;
  4440. break;
  4441. case 'link':
  4442. prepend += '[';
  4443. append = '](' + mark.attrs.href + ')' + append;
  4444. break;
  4445. case 'strong':
  4446. prepend += '**';
  4447. append = '**' + append;
  4448. break;
  4449. case 'em':
  4450. prepend += '_';
  4451. append = '_' + append;
  4452. break;
  4453. }
  4454. } );
  4455. }
  4456. description += prepend + jsonModel.text.escapeFormatting() + append;
  4457. break;
  4458. case 'image':
  4459. description += '{@' + jsonModel.attrs.id + '}\n';
  4460. break;
  4461. case 'code_block':
  4462. description += '```\n';
  4463. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  4464. description += '\n```\n';
  4465. break;
  4466. case 'bulletList':
  4467. jsonModel.content.forEach( listItem => {
  4468. description += '\t• ';
  4469. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  4470. } );
  4471. break;
  4472. case 'orderedList':
  4473. var n = 1;
  4474. jsonModel.content.forEach( listItem => {
  4475. description += '\t' + n + '. ';
  4476. n++;
  4477. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  4478. } );
  4479. break;
  4480. }
  4481. return description;
  4482. }
  4483. function htmlToPlain(html) {
  4484. var text = '';
  4485. var parser = new htmlparser.Parser( {
  4486. ontext: (htmltext) => {
  4487. text += htmltext.escapeFormatting();
  4488. }
  4489. }, {decodeEntities:true} );
  4490. parser.write( html );
  4491. parser.end();
  4492. return text;
  4493. };
  4494. function htmlToDiscord(html) {
  4495. var text = '';
  4496. var parser = new htmlparser.Parser( {
  4497. onopentag: (tagname, attribs) => {
  4498. switch (tagname) {
  4499. case 'b':
  4500. text += '**';
  4501. break;
  4502. case 'i':
  4503. text += '*';
  4504. break;
  4505. case 's':
  4506. text += '~~';
  4507. break;
  4508. case 'u':
  4509. text += '__';
  4510. break;
  4511. }
  4512. },
  4513. ontext: (htmltext) => {
  4514. text += htmltext.escapeFormatting();
  4515. },
  4516. onclosetag: (tagname) => {
  4517. switch (tagname) {
  4518. case 'b':
  4519. text += '**';
  4520. break;
  4521. case 'i':
  4522. text += '*';
  4523. break;
  4524. case 's':
  4525. text += '~~';
  4526. break;
  4527. case 'u':
  4528. text += '__';
  4529. break;
  4530. }
  4531. }
  4532. }, {decodeEntities:true} );
  4533. parser.write( html );
  4534. parser.end();
  4535. return text;
  4536. };
  4537. String.prototype.noWiki = function(href) {
  4538. if ( !href ) return false;
  4539. else if ( this.startsWith( 'https://www.' ) ) return true;
  4540. else if ( this.endsWith( '.gamepedia.com/' ) ) return 'https://www.gamepedia.com/' === href;
  4541. else return [
  4542. this.replace( /^https:\/\/([a-z\d-]{1,50}\.(?:fandom\.com|wikia\.org))\/(?:[a-z-]{1,8}\/)?$/, 'https://community.fandom.com/wiki/Community_Central:Not_a_valid_community?from=$1' ),
  4543. this + 'language-wikis'
  4544. ].includes( href.replace( /Unexpected token < in JSON at position 0 in "([^ ]+)"/, '$1' ) );
  4545. };
  4546. String.prototype.isFandom = function() {
  4547. return /^https:\/\/[a-z\d-]{1,50}\.(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?$/.test(this);
  4548. };
  4549. String.prototype.isMention = function(guild) {
  4550. var text = this.trim();
  4551. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  4552. };
  4553. Discord.Message.prototype.isAdmin = function() {
  4554. return this.channel.type === 'text' && this.member && ( this.member.permissions.has('MANAGE_GUILD') || ( this.isOwner() && this.evalUsed ) );
  4555. };
  4556. Discord.Message.prototype.isOwner = function() {
  4557. return this.author.id === process.env.owner;
  4558. };
  4559. Discord.Message.prototype.showEmbed = function() {
  4560. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  4561. };
  4562. Discord.Message.prototype.uploadFiles = function() {
  4563. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  4564. };
  4565. Array.prototype.toEmojis = function() {
  4566. var text = this.join(' ');
  4567. var regex = /(<a?:)(\d+)(>)/g;
  4568. if ( regex.test(text) ) {
  4569. regex.lastIndex = 0;
  4570. var emojis = client.emojis.cache;
  4571. var entry = null;
  4572. while ( ( entry = regex.exec(text) ) !== null ) {
  4573. if ( emojis.has(entry[2]) ) {
  4574. text = text.replaceSave(entry[0], emojis.get(entry[2]).toString());
  4575. } else {
  4576. text = text.replaceSave(entry[0], entry[1] + 'unknown_emoji:' + entry[2] + entry[3]);
  4577. }
  4578. }
  4579. return text.split(' ');
  4580. }
  4581. else return this;
  4582. };
  4583. String.prototype.toLink = function(title = '', querystring = '', fragment = '', path, isMarkdown = false) {
  4584. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment.toSection() : '' );
  4585. if ( path ) return ( path.server.startsWith( '//' ) ? 'https:' : '' ) + path.server + path.articlepath.replaceSave( '$1', title.toTitle(isMarkdown, path.articlepath.includes( '?' )) ) + ( path.articlepath.includes( '?' ) && linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  4586. else if ( this.endsWith( '.gamepedia.com/' ) ) return this + title.toTitle(isMarkdown) + linksuffix;
  4587. else if ( this.isFandom() ) return this + 'wiki/' + title.toTitle(isMarkdown) + linksuffix;
  4588. else return this + 'index.php?title=' + title.toTitle(isMarkdown, true) + ( linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  4589. };
  4590. String.prototype.toDescLink = function(title = '') {
  4591. return this + 'wiki/' + encodeURIComponent( title.replace( / /g, '_' ) );
  4592. };
  4593. String.prototype.toTitle = function(isMarkdown = false, inQuery = false) {
  4594. var title = this.replace( / /g, '_' ).replace( /\%/g, '%25' ).replace( /\\/g, '%5C' ).replace( /\?/g, '%3F' ).replace( /@(here|everyone)/g, '%40$1' );
  4595. if ( inQuery ) title = title.replace( /\&/g, '%26' );
  4596. if ( isMarkdown ) title = title.replace( /([\(\)])/g, '\\$1' );
  4597. return title;
  4598. };
  4599. String.prototype.toSearch = function() {
  4600. return encodeURIComponent( this ).replace( /%20/g, '+' );
  4601. };
  4602. String.prototype.toSection = function() {
  4603. return encodeURIComponent( this.replace( / /g, '_' ) ).replace( /\'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\%/g, '.' );
  4604. };
  4605. String.prototype.toFormatting = function(showEmbed = false, ...args) {
  4606. if ( showEmbed ) return this.toMarkdown(...args);
  4607. else return this.toPlaintext();
  4608. };
  4609. String.prototype.toMarkdown = function(wiki, path, title = '') {
  4610. var text = this.replace( /[\(\)\\]/g, '\\$&' );
  4611. var link = null;
  4612. while ( ( link = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g.exec(text) ) !== null ) {
  4613. var pagetitle = ( link[1] || link[2] );
  4614. var page = wiki.toLink(( /^[#\/]/.test(pagetitle) ? title + ( pagetitle.startsWith( '/' ) ? pagetitle : '' ) : pagetitle ), '', ( pagetitle.startsWith( '#' ) ? pagetitle.substring(1) : '' ), path, true);
  4615. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + page + ')' );
  4616. }
  4617. while ( title !== '' && ( link = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g.exec(text) ) !== null ) {
  4618. text = text.replaceSave( link[0], '[→' + link[1] + '](' + wiki.toLink(title, '', link[1], path, true) + ')' + ( link[2] ? ': ' + link[2] : '' ) );
  4619. }
  4620. return text.escapeFormatting(true);
  4621. };
  4622. String.prototype.toPlaintext = function() {
  4623. return this.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' ).escapeFormatting();
  4624. };
  4625. String.prototype.escapeFormatting = function(isMarkdown) {
  4626. var text = this;
  4627. if ( !isMarkdown ) text = text.replace( /[\(\)\\]/g, '\\$&' );
  4628. return text.replace( /[`_\*~:<>{}@\|]|\/\//g, '\\$&' );
  4629. };
  4630. String.prototype.replaceSave = function(pattern, replacement) {
  4631. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  4632. };
  4633. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  4634. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  4635. var emoji = '440871715938238494';
  4636. switch ( name ) {
  4637. case 'nowiki':
  4638. emoji = '505884572001763348';
  4639. break;
  4640. case 'error':
  4641. emoji = '440871715938238494';
  4642. break;
  4643. case 'support':
  4644. emoji = '448222377009086465';
  4645. break;
  4646. case 'oppose':
  4647. emoji = '448222455425794059';
  4648. break;
  4649. default:
  4650. emoji = name;
  4651. }
  4652. return this.react(emoji).catch(log_error);
  4653. } else {
  4654. console.log( '- Aborted, paused.' );
  4655. return Promise.resolve();
  4656. }
  4657. };
  4658. Discord.MessageReaction.prototype.removeEmoji = function() {
  4659. return this.users.remove().catch(log_error);
  4660. };
  4661. Discord.Message.prototype.sendChannel = function(content, options = {}, ignorePause = false) {
  4662. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  4663. if ( !options.allowedMentions ) options.allowedMentions = {parse:[]};
  4664. return this.channel.send(content, options).then( msg => {
  4665. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  4666. else msg.allowDelete(this.author.id);
  4667. return msg;
  4668. }, log_error );
  4669. } else {
  4670. console.log( '- Aborted, paused.' );
  4671. return Promise.resolve();
  4672. }
  4673. };
  4674. Discord.Message.prototype.sendChannelError = function(content, options = {}) {
  4675. if ( !options.allowedMentions ) options.allowedMentions = {parse:[]};
  4676. return this.channel.send(content, options).then( msg => {
  4677. if ( msg.length ) msg.forEach( message => {
  4678. message.reactEmoji('error');
  4679. message.allowDelete(this.author.id);
  4680. } );
  4681. else {
  4682. msg.reactEmoji('error');
  4683. msg.allowDelete(this.author.id);
  4684. }
  4685. return msg;
  4686. }, log_error );
  4687. };
  4688. Discord.Message.prototype.replyMsg = function(content, options = {}, ignorePause = false, allowDelete = true) {
  4689. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  4690. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  4691. return this.reply(content, options).then( msg => {
  4692. if ( allowDelete ) {
  4693. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  4694. else msg.allowDelete(this.author.id);
  4695. }
  4696. return msg;
  4697. }, log_error );
  4698. } else {
  4699. console.log( '- Aborted, paused.' );
  4700. return Promise.resolve();
  4701. }
  4702. };
  4703. Discord.Message.prototype.deleteMsg = function(timeout = 0) {
  4704. return this.delete({timeout}).catch(log_error);
  4705. };
  4706. Discord.Message.prototype.allowDelete = function(author) {
  4707. return this.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:120000} ).then( reaction => {
  4708. if ( reaction.size ) {
  4709. this.deleteMsg();
  4710. }
  4711. } );
  4712. };
  4713. String.prototype.hasPrefix = function(prefix, flags = '') {
  4714. return new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + '(?: |$)', flags ).test(this.replace( /\u200b/g, '' ).toLowerCase());
  4715. };
  4716. client.on( 'message', msg => {
  4717. if ( stop || msg.type !== 'DEFAULT' || msg.system || msg.webhookID || msg.author.id === client.user.id ) return;
  4718. if ( !msg.content.hasPrefix(( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  4719. if ( msg.content === process.env.prefix + ' help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  4720. if ( msg.channel.permissionsFor(client.user).has('SEND_MESSAGES') ) {
  4721. console.log( msg.guild.name + ': ' + msg.content );
  4722. db.get( 'SELECT lang FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id], (dberror, row) => {
  4723. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  4724. msg.replyMsg( i18n[( row || defaultSettings ).lang].prefix.replaceSave( /%s/g, patreons[msg.guild.id] ), {}, true );
  4725. } );
  4726. }
  4727. }
  4728. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  4729. }
  4730. if ( !ready.allSites && !allSites.length ) getAllSites();
  4731. if ( msg.channel.type === 'text' ) {
  4732. var permissions = msg.channel.permissionsFor(client.user);
  4733. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  4734. if ( missing.length ) {
  4735. if ( msg.isAdmin() || msg.isOwner() ) {
  4736. console.log( msg.guild.id + ': Missing permissions - ' + missing.join(', ') );
  4737. if ( !missing.includes( 'SEND_MESSAGES' ) ) {
  4738. db.get( 'SELECT lang FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id], (dberror, row) => {
  4739. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  4740. if ( msg.content.hasPrefix(( patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  4741. msg.replyMsg( i18n[( row || defaultSettings ).lang].missingperm + ' `' + missing.join('`, `') + '`', {}, true );
  4742. }
  4743. } );
  4744. }
  4745. }
  4746. return;
  4747. }
  4748. db.get( 'SELECT wiki, lang, inline FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id], (dberror, row) => {
  4749. if ( dberror ) {
  4750. console.log( '- Error while getting the wiki: ' + dberror );
  4751. if ( permissions.has('SEND_MESSAGES') ) {
  4752. msg.sendChannel( '⚠️ **Limited Functionality** ⚠️\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  4753. newMessage(msg);
  4754. }
  4755. return dberror;
  4756. }
  4757. if ( row ) newMessage(msg, row.wiki, i18n[row.lang], patreons[msg.guild.id], row.inline);
  4758. else {
  4759. msg.defaultSettings = true;
  4760. newMessage(msg);
  4761. }
  4762. } );
  4763. }
  4764. else newMessage(msg);
  4765. } );
  4766. function newMessage(msg, wiki = defaultSettings.wiki, lang = i18n[defaultSettings.lang], prefix = process.env.prefix, noInline = null, content) {
  4767. msg.noInline = noInline;
  4768. var cont = ( content || msg.content );
  4769. var cleanCont = ( content || msg.cleanContent );
  4770. var author = msg.author;
  4771. var channel = msg.channel;
  4772. var invoke = ( cont.split(' ')[1] ? cont.split(' ')[1].split('\n')[0].toLowerCase() : '' );
  4773. var aliasInvoke = ( lang.aliase[invoke] || invoke );
  4774. var ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  4775. if ( cont.hasPrefix(prefix) && ownercmd ) {
  4776. var args = cont.split(' ').slice(2);
  4777. if ( cont.split(' ')[1].split('\n')[1] ) args.unshift( '', cont.split(' ')[1].split('\n')[1] );
  4778. else console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + cont );
  4779. ownercmdmap[aliasInvoke](lang, msg, args, cont, wiki);
  4780. } else {
  4781. var count = 0;
  4782. var maxcount = ( channel.type === 'text' && msg.guild.id in patreons ? 15 : 10 );
  4783. cleanCont.replace( /\u200b/g, '' ).split('\n').forEach( line => {
  4784. if ( line.hasPrefix(prefix) && count < maxcount ) {
  4785. count++;
  4786. invoke = ( line.split(' ')[1] ? line.split(' ')[1].toLowerCase() : '' );
  4787. var args = line.split(' ').slice(2);
  4788. aliasInvoke = ( lang.aliase[invoke] || invoke );
  4789. ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  4790. if ( channel.type === 'text' && pause[msg.guild.id] && !( ( msg.isAdmin() && aliasInvoke in pausecmdmap ) || ownercmd ) ) console.log( msg.guild.id + ': Paused' );
  4791. else console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + line );
  4792. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, line, wiki);
  4793. else if ( channel.type !== 'text' || !pause[msg.guild.id] || ( msg.isAdmin() && aliasInvoke in pausecmdmap ) ) {
  4794. if ( aliasInvoke in cmdmap ) cmdmap[aliasInvoke](lang, msg, args, line, wiki);
  4795. else if ( /^![a-z\d-]{1,50}$/.test(invoke) ) {
  4796. cmd_link(lang, msg, args.join(' '), 'https://' + invoke.substring(1) + '.gamepedia.com/', ' ' + invoke + ' ');
  4797. }
  4798. else if ( /^\?(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  4799. if ( invoke.includes( '.' ) ) wiki = 'https://' + invoke.split('.')[1] + '.fandom.com/' + invoke.substring(1).split('.')[0] + '/';
  4800. else wiki = 'https://' + invoke.substring(1) + '.fandom.com/';
  4801. cmd_link(lang, msg, args.join(' '), wiki, ' ' + invoke + ' ');
  4802. }
  4803. else if ( /^\?\?(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  4804. if ( invoke.includes( '.' ) ) wiki = 'https://' + invoke.split('.')[1] + '.wikia.org/' + invoke.substring(2).split('.')[0] + '/';
  4805. else wiki = 'https://' + invoke.substring(2) + '.wikia.org/';
  4806. cmd_link(lang, msg, args.join(' '), wiki, ' ' + invoke + ' ');
  4807. }
  4808. else cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4809. }
  4810. } else if ( line.hasPrefix(prefix) && count === maxcount ) {
  4811. count++;
  4812. console.log( '- Message contains too many commands!' );
  4813. msg.reactEmoji('⚠️');
  4814. msg.sendChannelError( lang.limit.replaceSave( '%s', '<@' + author.id + '>' ), {allowedMentions:{users:[author.id]}} );
  4815. }
  4816. } );
  4817. if ( ( channel.type !== 'text' || !pause[msg.guild.id] ) && !noInline && ( cont.includes( '[[' ) || cont.includes( '{{' ) ) ) {
  4818. var links = [];
  4819. var embeds = [];
  4820. var linkcount = 0;
  4821. var linkmaxcount = maxcount + 5;
  4822. msg.cleanContent.replace( /\u200b/g, '' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).replace( /(?<!\\)`.+?`/gs, '<code>' ).split('\n').forEach( line => {
  4823. if ( line.hasPrefix(prefix) || !( line.includes( '[[' ) || line.includes( '{{' ) ) ) return;
  4824. if ( line.includes( '[[' ) && line.includes( ']]' ) && linkcount <= linkmaxcount ) {
  4825. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)\\[\\[([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\]\\]\\1', 'g' );
  4826. let entry = null;
  4827. while ( ( entry = regex.exec(line) ) !== null ) {
  4828. if ( linkcount < linkmaxcount ) {
  4829. linkcount++;
  4830. console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  4831. let title = entry[2].split('#')[0];
  4832. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  4833. links.push({title,section,spoiler:entry[1]});
  4834. }
  4835. else if ( linkcount === linkmaxcount ) {
  4836. linkcount++;
  4837. console.log( '- Message contains too many links!' );
  4838. msg.reactEmoji('⚠️');
  4839. break;
  4840. }
  4841. }
  4842. }
  4843. if ( line.includes( '{{' ) && line.includes( '}}' ) && count <= maxcount ) {
  4844. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)(?<!\\{)\\{\\{([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\}\\}\\1', 'g' );
  4845. let entry = null;
  4846. while ( ( entry = regex.exec(line) ) !== null ) {
  4847. if ( count < maxcount ) {
  4848. count++;
  4849. console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  4850. let title = entry[2].split('#')[0];
  4851. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  4852. embeds.push({title,section,spoiler:entry[1]});
  4853. }
  4854. else if ( count === maxcount ) {
  4855. count++;
  4856. console.log( '- Message contains too many links!' );
  4857. msg.reactEmoji('⚠️');
  4858. break;
  4859. }
  4860. }
  4861. }
  4862. } );
  4863. if ( links.length ) got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&iwurl=true&titles=' + encodeURIComponent( links.map( link => link.title ).join('|') ) + '&format=json', {
  4864. responseType: 'json'
  4865. } ).then( response => {
  4866. var body = response.body;
  4867. if ( response.statusCode !== 200 || !body || !body.query ) {
  4868. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4869. console.log( '- This wiki doesn\'t exist!' );
  4870. msg.reactEmoji('nowiki');
  4871. return;
  4872. }
  4873. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  4874. return;
  4875. }
  4876. if ( body.query.normalized ) {
  4877. body.query.normalized.forEach( title => links.filter( link => link.title === title.from ).forEach( link => link.title = title.to ) );
  4878. }
  4879. if ( body.query.interwiki ) {
  4880. body.query.interwiki.forEach( interwiki => links.filter( link => link.title === interwiki.title ).forEach( link => {
  4881. link.url = interwiki.url + ( link.section ? '#' + link.section.toSection() : '' );
  4882. } ) );
  4883. }
  4884. if ( body.query.pages ) {
  4885. var querypages = Object.values(body.query.pages);
  4886. querypages.filter( page => page.invalid !== undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  4887. links.splice(links.indexOf(link), 1);
  4888. } ) );
  4889. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  4890. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  4891. link.url = wiki.toLink(link.title, 'action=edit&redlink=1', '', body.query.general);
  4892. } ) );
  4893. }
  4894. if ( links.length ) msg.sendChannel( links.map( link => link.spoiler + '<' + ( link.url || wiki.toLink(link.title, '', link.section, body.query.general) ) + '>' + link.spoiler ).join('\n'), {split:true} );
  4895. }, error => {
  4896. console.log( '- Error while following the links: ' + error );
  4897. } );
  4898. if ( embeds.length ) got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general' + ( wiki.isFandom() ? '' : '|variables' ) + '&titles=' + encodeURIComponent( embeds.map( embed => embed.title + '|Template:' + embed.title ).join('|') ) + '&format=json', {
  4899. responseType: 'json'
  4900. } ).then( response => {
  4901. var body = response.body;
  4902. if ( response.statusCode !== 200 || !body || !body.query ) {
  4903. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4904. console.log( '- This wiki doesn\'t exist!' );
  4905. msg.reactEmoji('nowiki');
  4906. return;
  4907. }
  4908. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  4909. return;
  4910. }
  4911. if ( body.query.normalized ) {
  4912. body.query.normalized.forEach( title => embeds.filter( embed => embed.title === title.from ).forEach( embed => embed.title = title.to ) );
  4913. }
  4914. if ( body.query.pages ) {
  4915. var querypages = Object.values(body.query.pages);
  4916. querypages.filter( page => page.invalid !== undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  4917. embeds.splice(embeds.indexOf(embed), 1);
  4918. } ) );
  4919. var missing = [];
  4920. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  4921. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  4922. embeds.splice(embeds.indexOf(embed), 1);
  4923. if ( page.ns === 0 && !embed.section ) {
  4924. var template = querypages.find( template => template.ns === 10 && template.title.split(':').slice(1).join(':') === embed.title );
  4925. if ( template && template.missing === undefined ) embed.template = wiki.toLink(template.title, '', '', body.query.general);
  4926. }
  4927. if ( embed.template || !body.query.variables || !body.query.variables.some( variable => variable.toUpperCase() === embed.title ) ) missing.push(embed);
  4928. } ) );
  4929. if ( missing.length ) {
  4930. msg.sendChannel( missing.map( embed => embed.spoiler + '<' + ( embed.template || wiki.toLink(embed.title, 'action=edit&redlink=1', '', body.query.general) ) + '>' + embed.spoiler ).join('\n'), {split:true} );
  4931. }
  4932. }
  4933. if ( embeds.length ) {
  4934. if ( wiki.isFandom() ) embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  4935. fandom_check_wiki(lang, msg, embed.title, wiki, ' ', reaction, embed.spoiler, '', embed.section);
  4936. } ) );
  4937. else embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  4938. gamepedia_check_wiki(lang, msg, embed.title, wiki, ' ', reaction, embed.spoiler, '', embed.section);
  4939. } ) );
  4940. }
  4941. }, error => {
  4942. console.log( '- Error while following the links: ' + error );
  4943. } );
  4944. }
  4945. }
  4946. }
  4947. client.on( 'voiceStateUpdate', (olds, news) => {
  4948. if ( stop || !( olds.guild.id in voice ) || !olds.guild.me.permissions.has('MANAGE_ROLES') || olds.channelID === news.channelID ) return;
  4949. if ( !ready.allSites && !allSites.length ) getAllSites();
  4950. var lang = i18n[voice[olds.guild.id]].voice;
  4951. if ( olds.member && olds.channel ) {
  4952. var oldrole = olds.member.roles.cache.find( role => role.name === lang.channel + ' – ' + olds.channel.name );
  4953. if ( oldrole && oldrole.comparePositionTo(olds.guild.me.roles.highest) < 0 ) {
  4954. console.log( olds.guild.id + ': ' + olds.member.id + ' left the voice channel "' + olds.channel.id + '".' );
  4955. olds.member.roles.remove( oldrole, lang.left.replaceSave( '%1$s', olds.member.displayName ).replaceSave( '%2$s', olds.channel.name ) ).catch(log_error);
  4956. }
  4957. }
  4958. if ( news.member && news.channel ) {
  4959. var newrole = news.guild.roles.cache.find( role => role.name === lang.channel + ' – ' + news.channel.name );
  4960. if ( newrole && newrole.comparePositionTo(news.guild.me.roles.highest) < 0 ) {
  4961. console.log( news.guild.id + ': ' + news.member.id + ' joined the voice channel "' + news.channel.id + '".' );
  4962. news.member.roles.add( newrole, lang.join.replaceSave( '%1$s', news.member.displayName ).replaceSave( '%2$s', news.channel.name ) ).catch(log_error);
  4963. }
  4964. }
  4965. } );
  4966. client.on( 'guildCreate', guild => {
  4967. console.log( '- I\'ve been added to a server.' );
  4968. } );
  4969. client.on( 'guildDelete', guild => {
  4970. if ( !guild.available ) {
  4971. console.log( '- ' + guild.id + ': This server isn\'t responding.' );
  4972. return;
  4973. }
  4974. console.log( '- I\'ve been removed from a server.' );
  4975. db.run( 'DELETE FROM discord WHERE guild = ?', [guild.id], function (dberror) {
  4976. if ( dberror ) {
  4977. console.log( '- Error while removing the settings: ' + dberror );
  4978. return dberror;
  4979. }
  4980. if ( guild.id in patreons ) delete patreons[guild.id];
  4981. if ( guild.id in voice ) delete voice[guild.id];
  4982. console.log( '- Settings successfully removed.' );
  4983. } );
  4984. } );
  4985. function removePatreons(guild, msg) {
  4986. try {
  4987. if ( !guild ) return 'removePatreons(guild, msg) – No guild provided!';
  4988. db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND channel IS NULL', [guild], (dberror, row) => {
  4989. try {
  4990. if ( dberror ) {
  4991. console.log( '- Error while getting the guild: ' + dberror );
  4992. if ( msg ) msg.replyMsg( 'I got an error while searching for the guild!', {}, true );
  4993. return dberror;
  4994. }
  4995. if ( !row ) {
  4996. if ( msg ) msg.replyMsg( 'that guild doesn\'t exist!', {}, true );
  4997. return;
  4998. }
  4999. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, guild], function (error) {
  5000. try {
  5001. if ( error ) {
  5002. console.log( '- Error while updating the guild: ' + error );
  5003. if ( msg ) msg.replyMsg( 'I got an error while updating the guild!', {}, true );
  5004. return error;
  5005. }
  5006. console.log( '- Guild successfully updated.' );
  5007. delete patreons[guild];
  5008. if ( msg ) msg.replyMsg( 'the patreon features are now disabled on that guild.', {}, true );
  5009. }
  5010. catch ( tryerror ) {
  5011. console.log( '- Error while removing the patreon features: ' + tryerror );
  5012. }
  5013. } );
  5014. }
  5015. catch ( tryerror ) {
  5016. console.log( '- Error while removing the patreon features: ' + tryerror );
  5017. }
  5018. } );
  5019. }
  5020. catch ( tryerror ) {
  5021. console.log( '- Error while removing the patreon features: ' + tryerror );
  5022. return 'removePatreons(guild, msg) – Error while removing the patreon features: ' + tryerror;
  5023. }
  5024. }
  5025. function removeSettings() {
  5026. var guilds = [];
  5027. var channels = [];
  5028. db.each( 'SELECT guild, channel FROM discord', [], (dberror, row) => {
  5029. if ( dberror ) {
  5030. console.log( '- Error while getting the setting: ' + dberror );
  5031. return dberror;
  5032. }
  5033. if ( !row.channel && !client.guilds.cache.has(row.guild) ) {
  5034. if ( row.guild in patreons ) delete patreons[row.guild];
  5035. if ( row.guild in voice ) delete voice[row.guild];
  5036. return guilds.push(row.guild);
  5037. }
  5038. if ( row.channel && client.guilds.cache.has(row.guild) && !client.channels.cache.filter( channel => channel.type === 'text' ).has(row.channel) ) return channels.push(row.channel);
  5039. }, (error) => {
  5040. if ( error ) {
  5041. console.log( '- Error while getting the settings: ' + error );
  5042. return error;
  5043. }
  5044. if ( guilds.length ) db.run( 'DELETE FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  5045. if ( dberror ) {
  5046. console.log( '- Error while removing the guilds: ' + dberror );
  5047. return dberror;
  5048. }
  5049. console.log( '- Guilds successfully removed.' );
  5050. } );
  5051. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( channel => '?' ).join(', ') + ')', channels, function (dberror) {
  5052. if ( dberror ) {
  5053. console.log( '- Error while removing the channels: ' + dberror );
  5054. return dberror;
  5055. }
  5056. console.log( '- Channels successfully removed.' );
  5057. } );
  5058. if ( !guilds.length && !channels.length ) console.log( '- Settings successfully removed.' );
  5059. } );
  5060. }
  5061. client.login(process.env.token).catch( error => {
  5062. log_error(error, true, 'LOGIN-');
  5063. client.login(process.env.token).catch( error => {
  5064. log_error(error, true, 'LOGIN-');
  5065. client.login(process.env.token).catch( error => {
  5066. log_error(error, true, 'LOGIN-');
  5067. process.exit(1);
  5068. } );
  5069. } );
  5070. } );
  5071. client.on( 'error', error => log_error(error, true) );
  5072. client.on( 'warn', warning => log_warn(warning, false) );
  5073. if ( isDebug ) client.on( 'debug', debug => {
  5074. if ( isDebug ) console.log( '- Debug: ' + debug );
  5075. } );
  5076. function log_error(error, isBig = false, type = '') {
  5077. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  5078. if ( isDebug ) {
  5079. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  5080. } else {
  5081. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  5082. else console.log( '- ' + error.name + ': ' + error.message );
  5083. }
  5084. }
  5085. function log_warn(warning, api = true) {
  5086. if ( isDebug ) {
  5087. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  5088. } else {
  5089. if ( api ) console.warn( '- Warning: ' + Object.keys(warning).join(', ') );
  5090. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  5091. }
  5092. }
  5093. async function graceful(code = 0) {
  5094. stop = true;
  5095. console.log( '- SIGTERM: Preparing to close...' );
  5096. setTimeout( async () => {
  5097. console.log( '- SIGTERM: Destroying client...' );
  5098. await client.destroy();
  5099. await db.close( dberror => {
  5100. if ( dberror ) {
  5101. console.log( '- SIGTERM: Error while closing the database connection: ' + dberror );
  5102. return dberror;
  5103. }
  5104. console.log( '- SIGTERM: Closed the database connection.' );
  5105. } );
  5106. setTimeout( async () => {
  5107. console.log( '- SIGTERM: Closing takes too long, terminating!' );
  5108. process.exit(code);
  5109. }, 2000 ).unref();
  5110. }, 1000 ).unref();
  5111. }
  5112. process.once( 'SIGINT', graceful );
  5113. process.once( 'SIGTERM', graceful );