bot.js 317 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319
  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. global.shardId = null;
  6. var ready = {
  7. patreons: false,
  8. voice: false,
  9. allSites: true
  10. }
  11. const Discord = require('discord.js');
  12. const got = require('got').extend( {
  13. throwHttpErrors: false,
  14. timeout: 5000,
  15. headers: {
  16. 'User-Agent': 'Wiki-Bot/' + ( isDebug ? 'testing' : process.env.npm_package_version ) + ' (Discord; ' + process.env.npm_package_name + ')'
  17. }
  18. } );
  19. const htmlparser = require('htmlparser2');
  20. const cheerio = require('cheerio');
  21. const sqlite3 = require('sqlite3').verbose();
  22. var db = new sqlite3.Database( './wikibot.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, dberror => {
  23. if ( dberror ) {
  24. console.log( '- ' + shardId + ': Error while connecting to the database: ' + dberror );
  25. return dberror;
  26. }
  27. console.log( '- ' + shardId + ': Connected to the database.' );
  28. } );
  29. var client = new Discord.Client( {
  30. messageCacheLifetime: 300,
  31. messageSweepInterval: 300,
  32. allowedMentions: {
  33. parse: []
  34. },
  35. presence: {
  36. status: 'online',
  37. activity: {
  38. type: 'STREAMING',
  39. name: process.env.prefix + ' help',
  40. url: 'https://www.twitch.tv/wikibot'
  41. }
  42. },
  43. ws: {
  44. large_threshold: 1000,
  45. intents: [
  46. 'GUILDS',
  47. 'GUILD_MESSAGES',
  48. 'GUILD_MESSAGE_REACTIONS',
  49. 'GUILD_VOICE_STATES',
  50. 'GUILD_INTEGRATIONS',
  51. 'DIRECT_MESSAGES',
  52. 'DIRECT_MESSAGE_REACTIONS'
  53. ]
  54. }
  55. } );
  56. var i18n = require('./i18n/allLangs.json');
  57. Object.keys(i18n.allLangs[1]).forEach( lang => i18n[lang] = require('./i18n/' + lang + '.json') );
  58. const minecraft = require('./minecraft.json');
  59. global.pause = {};
  60. var stop = false;
  61. const defaultPermissions = 403033152;
  62. const timeoptions = {
  63. year: 'numeric',
  64. month: 'short',
  65. day: 'numeric',
  66. hour: '2-digit',
  67. minute: '2-digit',
  68. timeZone: 'UTC',
  69. timeZoneName: 'short'
  70. }
  71. const defaultSettings = {
  72. lang: "en",
  73. wiki: "https://community.fandom.com/"
  74. }
  75. global.patreons = {};
  76. function getSettings(trysettings = 1) {
  77. db.each( 'SELECT guild, prefix FROM discord WHERE patreon IS NOT NULL', [], (dberror, row) => {
  78. if ( dberror ) {
  79. console.log( '- ' + shardId + ': ' + trysettings + '. Error while getting the patreon: ' + dberror );
  80. if ( trysettings < 10 ) {
  81. trysettings++;
  82. getSettings(trysettings);
  83. }
  84. return dberror;
  85. }
  86. patreons[row.guild] = row.prefix;
  87. }, (dberror) => {
  88. if ( dberror ) {
  89. console.log( '- ' + trysettings + '. Error while getting the patreons: ' + dberror );
  90. if ( dberror.message === 'SQLITE_ERROR: no such table: discord' ) db.serialize( () => {
  91. db.run( 'CREATE TABLE IF NOT EXISTS patreons(patreon TEXT PRIMARY KEY UNIQUE NOT NULL, count INTEGER NOT NULL)', [], function (error) {
  92. if ( error ) {
  93. console.log( '- ' + shardId + ': Error while creating the patreons table: ' + error );
  94. return error;
  95. }
  96. console.log( '- Created the patreons table.' );
  97. db.run( 'CREATE INDEX idx_patreons_patreon ON patreons(patreon)', [], function (idxerror) {
  98. if ( idxerror ) {
  99. console.log( '- ' + shardId + ': Error while creating the patreons index: ' + idxerror );
  100. return error;
  101. }
  102. console.log( '- ' + shardId + ': Created the patreons index.' );
  103. } );
  104. } );
  105. 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) {
  106. if ( error ) {
  107. console.log( '- ' + shardId + ': Error while creating the discord table: ' + error );
  108. return error;
  109. }
  110. console.log( '- Created the discord table.' );
  111. 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) {
  112. if ( idxerror ) {
  113. console.log( '- ' + shardId + ': Error while creating the discord guild trigger: ' + idxerror );
  114. return error;
  115. }
  116. console.log( '- ' + shardId + ': Created the discord guild trigger.' );
  117. } );
  118. db.run( 'CREATE INDEX idx_discord_patreon ON discord(patreon) WHERE patreon IS NOT NULL', [], function (idxerror) {
  119. if ( idxerror ) {
  120. console.log( '- ' + shardId + ': Error while creating the discord patreon index: ' + idxerror );
  121. return error;
  122. }
  123. console.log( '- ' + shardId + ': Created the discord patreon index.' );
  124. } );
  125. db.run( 'CREATE INDEX idx_discord_voice ON discord(voice) WHERE voice IS NOT NULL', [], function (idxerror) {
  126. if ( idxerror ) {
  127. console.log( '- ' + shardId + ': Error while creating the discord voice index: ' + idxerror );
  128. return error;
  129. }
  130. console.log( '- ' + shardId + ': Created the discord voice index.' );
  131. } );
  132. db.run( 'CREATE INDEX idx_discord_channel ON discord(guild, channel DESC)', [], function (idxerror) {
  133. if ( idxerror ) {
  134. console.log( '- ' + shardId + ': Error while creating the discord channel index: ' + idxerror );
  135. return error;
  136. }
  137. console.log( '- ' + shardId + ': Created the discord channel index.' );
  138. } );
  139. if ( trysettings < 10 ) {
  140. trysettings++;
  141. getSettings(trysettings);
  142. }
  143. } );
  144. db.run( 'CREATE TABLE IF NOT EXISTS verification(guild TEXT NOT NULL, configid INTEGER NOT NULL, channel TEXT NOT NULL, role TEXT NOT NULL, editcount INTEGER NOT NULL DEFAULT [0], usergroup TEXT NOT NULL DEFAULT [user], accountage INTEGER NOT NULL DEFAULT [0], rename INTEGER NOT NULL DEFAULT [0], UNIQUE(guild, configid))', [], function (error) {
  145. if ( error ) {
  146. console.log( '- ' + shardId + ': Error while creating the verification table: ' + error );
  147. return error;
  148. }
  149. console.log( '- ' + shardId + ': Created the verification table.' );
  150. db.run( 'CREATE INDEX idx_verification_config ON verification(guild, configid ASC, channel)', [], function (idxerror) {
  151. if ( idxerror ) {
  152. console.log( '- ' + shardId + ': Error while creating the verification index: ' + idxerror );
  153. return error;
  154. }
  155. console.log( '- ' + shardId + ': Created the verification index.' );
  156. } );
  157. } );
  158. } );
  159. else {
  160. if ( trysettings < 10 ) {
  161. trysettings++;
  162. getSettings(trysettings);
  163. }
  164. }
  165. return dberror;
  166. }
  167. console.log( '- ' + shardId + ': Patreons successfully loaded.' );
  168. ready.patreons = true;
  169. getVoice();
  170. } );
  171. }
  172. global.voice = {};
  173. function getVoice(trysettings = 1) {
  174. db.each( 'SELECT guild, lang FROM discord WHERE voice IS NOT NULL', [], (dberror, row) => {
  175. if ( dberror ) {
  176. console.log( '- ' + shardId + ': ' + trysettings + '. Error while getting the voice channel: ' + dberror );
  177. if ( trysettings < 10 ) {
  178. trysettings++;
  179. getVoice(trysettings);
  180. }
  181. return dberror;
  182. }
  183. if ( client.guilds.cache.has(row.guild) ) voice[row.guild] = row.lang;
  184. }, (dberror) => {
  185. if ( dberror ) {
  186. console.log( '- ' + shardId + ': ' + trysettings + '. Error while getting the voice channels: ' + dberror );
  187. if ( trysettings < 10 ) {
  188. trysettings++;
  189. getVoice(trysettings);
  190. }
  191. return dberror;
  192. }
  193. console.log( '- ' + shardId + ': Voice channels successfully loaded.' );
  194. ready.voice = true;
  195. } );
  196. }
  197. var allSites = [];
  198. function getAllSites() {
  199. ready.allSites = true;
  200. got.get( 'https://help.gamepedia.com/api.php?action=allsites&formatversion=2&do=getSiteStats&filter=wikis|md5_key,wiki_domain,wiki_display_name,wiki_image,wiki_description,wiki_managers,official_wiki,wiki_crossover,created&format=json', {
  201. responseType: 'json'
  202. } ).then( response => {
  203. var body = response.body;
  204. if ( response.statusCode !== 200 || !body || body.status !== 'okay' || !body.data || !body.data.wikis ) {
  205. console.log( '- ' + shardId + ': ' + response.statusCode + ': Error while gettings all sites: ' + ( body && body.error && body.error.info ) );
  206. ready.allSites = false;
  207. }
  208. else {
  209. console.log( '- ' + shardId + ': Sites successfully loaded.' );
  210. allSites = JSON.parse(JSON.stringify(body.data.wikis.filter( site => /^[a-z\d-]{1,50}\.gamepedia\.com$/.test(site.wiki_domain) )));
  211. 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' ) );
  212. }
  213. }, error => {
  214. console.log( '- ' + shardId + ': Error while gettings all sites: ' + error );
  215. } );
  216. }
  217. client.on( 'ready', () => {
  218. client.ready = true;
  219. console.log( '\n- ' + shardId + ': Successfully logged in as ' + client.user.username + '!\n' );
  220. getSettings();
  221. getAllSites();
  222. if ( !isDebug ) client.setInterval( () => {
  223. console.log( '- ' + shardId + ': Current server count: ' + client.guilds.cache.size );
  224. if ( process.env.dbltoken ) got.post( 'https://top.gg/api/bots/' + client.user.id + '/stats', {
  225. headers: {
  226. Authorization: process.env.dbltoken
  227. },
  228. json: {
  229. server_count: client.guilds.cache.size,
  230. shard_count: client.shard.count,
  231. shard_id: shardId
  232. },
  233. responseType: 'json'
  234. } ).catch( error => {
  235. console.log( '- ' + shardId + ': Error while posting statistics to https://top.gg/bot/' + client.user.id + ': ' + error );
  236. } );
  237. if ( process.env.dbggtoken ) got.post( 'https://discord.bots.gg/api/v1/bots/' + client.user.id + '/stats', {
  238. headers: {
  239. Authorization: process.env.dbggtoken
  240. },
  241. json: {
  242. guildCount: client.guilds.cache.size,
  243. shardCount: client.shard.count,
  244. shardId: shardId
  245. },
  246. responseType: 'json'
  247. } ).catch( error => {
  248. console.log( '- ' + shardId + ': Error while posting statistics to https://discord.bots.gg/bots/' + client.user.id + ': ' + error );
  249. } );
  250. }, 10800000 ).unref();
  251. } );
  252. client.on( 'shardDisconnect', () => client.ready = false );
  253. var cmdmap = {
  254. help: cmd_help,
  255. test: cmd_test,
  256. pause: cmd_pause,
  257. invite: cmd_invite,
  258. voice: cmd_voice,
  259. verify: cmd_verify,
  260. verification: cmd_verification,
  261. settings: cmd_settings,
  262. info: cmd_info,
  263. patreon: cmd_patreon
  264. }
  265. var ownercmdmap = {
  266. stop: cmd_stop,
  267. pause: cmd_pause,
  268. say: cmd_say,
  269. eval: cmd_eval,
  270. get: cmd_get,
  271. patreon: cmd_patreon
  272. }
  273. var pausecmdmap = {
  274. help: cmd_help,
  275. test: cmd_test,
  276. pause: cmd_pause,
  277. voice: cmd_voice,
  278. verification: cmd_verification,
  279. settings: cmd_settings,
  280. patreon: cmd_patreon
  281. }
  282. var minecraftcmdmap = {
  283. command: minecraft_command2,
  284. bug: minecraft_bug
  285. }
  286. function cmd_helpsetup(lang, msg) {
  287. msg.defaultSettings = false;
  288. msg.replyMsg( lang.settings.missing.replaceSave( '%1$s', '`' + process.env.prefix + ' settings lang`' ).replaceSave( '%2$s', '`' + process.env.prefix + ' settings wiki`' ) );
  289. }
  290. function cmd_settings(lang, msg, args, line, wiki) {
  291. if ( !msg.isAdmin() ) return msg.reactEmoji('❌');
  292. db.all( 'SELECT channel, lang, wiki, prefix, inline FROM discord WHERE guild = ? ORDER BY channel DESC', [msg.guild.id], (error, rows) => {
  293. if ( error ) {
  294. console.log( '- Error while getting the settings: ' + error );
  295. msg.reactEmoji('error', true);
  296. return error;
  297. }
  298. var guild = rows.find( row => !row.channel );
  299. if ( !guild ) guild = Object.assign({prefix: process.env.prefix}, defaultSettings);
  300. var prefix = guild.prefix;
  301. var text = lang.settings.missing.replaceSave( '%1$s', '`' + prefix + ' settings lang`' ).replaceSave( '%2$s', '`' + prefix + ' settings wiki`' );
  302. if ( rows.length ) {
  303. text = lang.settings.current + '\n' + lang.settings.currentlang + ' `' + i18n.allLangs[2][guild.lang] + '` - `' + prefix + ' settings lang`';
  304. if ( msg.guild.id in patreons ) text += '\n' + lang.settings.currentprefix + ' `' + prefix + '` - `' + prefix + ' settings prefix`';
  305. text += '\n' + lang.settings.currentinline + ' ' + ( guild.inline ? '~~' : '' ) + '`[[' + lang.search.page + ']]`' + ( guild.inline ? '~~' : '' ) + ' - `' + prefix + ' settings inline`';
  306. text += '\n' + lang.settings.currentwiki + ' ' + guild.wiki + ' - `' + prefix + ' settings wiki`';
  307. text += '\n' + lang.settings.currentchannel + ' `' + prefix + ' settings channel`\n';
  308. if ( rows.length === 1 ) text += lang.settings.nochannels;
  309. 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');
  310. }
  311. if ( !args.length ) {
  312. return msg.replyMsg( text, {split:true}, true );
  313. }
  314. var prelang = '';
  315. args[0] = args[0].toLowerCase();
  316. if ( args[0] === 'channel' ) {
  317. prelang = 'channel ';
  318. if ( !rows.length ) return msg.replyMsg( text, {split:true}, true );
  319. var channel = rows.find( row => row.channel === msg.channel.id );
  320. if ( !channel ) channel = Object.assign({channel:msg.channel.id}, guild);
  321. text = lang.settings[prelang + 'current'];
  322. if ( msg.guild.id in patreons ) {
  323. text += '\n' + lang.settings.currentlang + ' `' + i18n.allLangs[2][channel.lang] + '` - `' + prefix + ' settings channel lang`';
  324. text += '\n' + lang.settings.currentinline + ' ' + ( channel.inline ? '~~' : '' ) + '`[[' + lang.search.page + ']]`' + ( channel.inline ? '~~' : '' ) + ' - `' + prefix + ' settings channel inline`';
  325. }
  326. text += '\n' + lang.settings.currentwiki + ' ' + channel.wiki + ' - `' + prefix + ' settings channel wiki`';
  327. if ( !args[1] ) return msg.replyMsg( text, {}, true );
  328. args[0] = args[1].toLowerCase();
  329. args[1] = args.slice(2).join(' ').toLowerCase().trim().replace( /^<(.*)>$/, '$1' );
  330. }
  331. else args[1] = args.slice(1).join(' ').toLowerCase().trim().replace( /^<(.*)>$/, '$1' );
  332. if ( args[0] === 'wiki' ) {
  333. prelang += 'wiki';
  334. var wikihelp = '\n' + lang.settings.wikihelp.replaceSave( '%s', prefix + ' settings ' + prelang );
  335. if ( !args[1] ) {
  336. if ( !rows.length ) return msg.replyMsg( lang.settings.wikimissing + wikihelp, {}, true );
  337. else return msg.replyMsg( lang.settings[prelang] + ' ' + ( channel || guild ).wiki + wikihelp, {}, true );
  338. }
  339. var regex = args[1].match( /^(?:https:\/\/)?([a-z\d-]{1,50}\.(?:gamepedia\.com|(?:fandom\.com|wikia\.org)(?:(?!\/wiki\/)\/[a-z-]{1,8})?))(?:\/|$)/ );
  340. if ( !regex ) {
  341. var value = args[1].split(' ');
  342. if ( value.length === 2 && value[1] === '--force' ) return msg.reactEmoji('⏳', true).then( reaction => {
  343. got.get( value[0] + 'api.php?action=query&format=json', {
  344. responseType: 'json'
  345. } ).then( response => {
  346. var body = response.body;
  347. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !( body instanceof Object ) ) {
  348. console.log( '- ' + response.statusCode + ': Error while testing the wiki: ' + ( body && body.error && body.error.info ) );
  349. if ( reaction ) reaction.removeEmoji();
  350. msg.reactEmoji('nowiki', true);
  351. return msg.replyMsg( lang.settings.wikiinvalid + wikihelp, {}, true );
  352. }
  353. var sql = 'UPDATE discord SET wiki = ? WHERE guild = ? AND wiki = ?';
  354. var sqlargs = [value[0], msg.guild.id, guild.wiki];
  355. if ( !rows.length ) {
  356. sql = 'INSERT INTO discord(wiki, guild) VALUES(?, ?)';
  357. sqlargs.pop();
  358. }
  359. if ( channel ) {
  360. sql = 'UPDATE discord SET wiki = ? WHERE guild = ? AND channel = ?';
  361. sqlargs[2] = msg.channel.id;
  362. if ( !rows.includes( channel ) ) {
  363. if ( channel.wiki === value[0] ) {
  364. if ( reaction ) reaction.removeEmoji();
  365. return msg.replyMsg( lang.settings[prelang + 'changed'] + ' ' + channel.wiki + wikihelp, {}, true );
  366. }
  367. sql = 'INSERT INTO discord(wiki, guild, channel, lang, prefix) VALUES(?, ?, ?, ?, ?)';
  368. sqlargs.push(guild.lang, guild.prefix);
  369. }
  370. }
  371. return db.run( sql, sqlargs, function (dberror) {
  372. if ( dberror ) {
  373. console.log( '- Error while editing the settings: ' + dberror );
  374. msg.replyMsg( lang.settings.save_failed, {}, true );
  375. if ( reaction ) reaction.removeEmoji();
  376. return dberror;
  377. }
  378. console.log( '- Settings successfully updated.' );
  379. if ( channel ) channel.wiki = value[0];
  380. else guild.wiki = value[0];
  381. if ( channel || !rows.some( row => row.channel === msg.channel.id ) ) wiki = value[0];
  382. if ( reaction ) reaction.removeEmoji();
  383. msg.replyMsg( lang.settings[prelang + 'changed'] + ' ' + value[0] + wikihelp, {}, true );
  384. 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 );
  385. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( row => '?' ).join('|') + ')', channels, function (delerror) {
  386. if ( delerror ) {
  387. console.log( '- Error while removing the settings: ' + delerror );
  388. return delerror;
  389. }
  390. console.log( '- Settings successfully removed.' );
  391. } );
  392. } );
  393. }, ferror => {
  394. console.log( '- Error while testing the wiki: ' + ferror );
  395. if ( reaction ) reaction.removeEmoji();
  396. msg.reactEmoji('nowiki', true);
  397. return msg.replyMsg( lang.settings.wikiinvalid + wikihelp, {}, true );
  398. } );
  399. } );
  400. if ( allSites.some( site => site.wiki_domain === value.join('') + '.gamepedia.com' ) ) {
  401. regex = ['https://' + value.join('') + '.gamepedia.com/',value.join('') + '.gamepedia.com'];
  402. }
  403. else if ( /^(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(value.join('')) ) {
  404. if ( !value.join('').includes( '.' ) ) regex = ['https://' + value.join('') + '.fandom.com/',value.join('') + '.fandom.com'];
  405. else regex = ['https://' + value.join('').split('.')[1] + '.fandom.com/' + value.join('').split('.')[0] + '/',value.join('').split('.')[1] + '.fandom.com/' + value.join('').split('.')[0]];
  406. } else {
  407. var text = lang.settings.wikiinvalid + wikihelp;
  408. var sites = allSites.filter( site => site.wiki_display_name.toLowerCase().includes( value.join(' ') ) );
  409. if ( 0 < sites.length && sites.length < 21 ) {
  410. text += '\n\n' + lang.settings.foundwikis + '\n' + sites.map( site => site.wiki_display_name + ': `' + site.wiki_domain + '`' ).join('\n');
  411. }
  412. return msg.replyMsg( text, {split:true}, true );
  413. }
  414. }
  415. var sql = 'UPDATE discord SET wiki = ? WHERE guild = ? AND wiki = ?';
  416. var sqlargs = ['https://' + regex[1] + '/', msg.guild.id, guild.wiki];
  417. if ( !rows.length ) {
  418. sql = 'INSERT INTO discord(wiki, guild) VALUES(?, ?)';
  419. sqlargs.pop();
  420. }
  421. if ( channel ) {
  422. sql = 'UPDATE discord SET wiki = ? WHERE guild = ? AND channel = ?';
  423. sqlargs[2] = msg.channel.id;
  424. if ( !rows.includes( channel ) ) {
  425. if ( channel.wiki === 'https://' + regex[1] + '/' ) {
  426. return msg.replyMsg( lang.settings[prelang + 'changed'] + ' ' + channel.wiki + wikihelp, {}, true );
  427. }
  428. sql = 'INSERT INTO discord(wiki, guild, channel, lang, prefix) VALUES(?, ?, ?, ?, ?)';
  429. sqlargs.push(guild.lang, guild.prefix);
  430. }
  431. }
  432. return db.run( sql, sqlargs, function (dberror) {
  433. if ( dberror ) {
  434. console.log( '- Error while editing the settings: ' + dberror );
  435. msg.replyMsg( lang.settings.save_failed, {}, true );
  436. return dberror;
  437. }
  438. console.log( '- Settings successfully updated.' );
  439. if ( channel ) channel.wiki = 'https://' + regex[1] + '/';
  440. else guild.wiki = 'https://' + regex[1] + '/';
  441. if ( channel || !rows.some( row => row.channel === msg.channel.id ) ) wiki = 'https://' + regex[1] + '/';
  442. msg.replyMsg( lang.settings[prelang + 'changed'] + ' https://' + regex[1] + '/' + wikihelp, {}, true );
  443. 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 );
  444. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( row => '?' ).join('|') + ')', channels, function (delerror) {
  445. if ( delerror ) {
  446. console.log( '- Error while removing the settings: ' + delerror );
  447. return delerror;
  448. }
  449. console.log( '- Settings successfully removed.' );
  450. } );
  451. } );
  452. }
  453. if ( args[0] === 'lang' ) {
  454. if ( channel && !( msg.guild.id in patreons ) ) return msg.replyMsg( lang.patreon + ' <' + process.env.patreon + '>', {}, true );
  455. prelang += 'lang';
  456. var langhelp = '\n' + lang.settings.langhelp.replaceSave( '%s', prefix + ' settings ' + prelang ) + ' `' + Object.values(i18n.allLangs[1]).join('`, `') + '`';
  457. if ( !args[1] ) {
  458. return msg.replyMsg( lang.settings[prelang] + ' `' + i18n.allLangs[2][( channel || guild ).lang] + '`' + langhelp, {}, true );
  459. }
  460. if ( !( args[1] in i18n.allLangs[0] ) ) {
  461. return msg.replyMsg( lang.settings.langinvalid + langhelp, {}, true );
  462. }
  463. var sql = 'UPDATE discord SET lang = ? WHERE guild = ? AND lang = ?';
  464. var sqlargs = [i18n.allLangs[0][args[1]], msg.guild.id, guild.lang];
  465. if ( !rows.length ) {
  466. sql = 'INSERT INTO discord(lang, guild) VALUES(?, ?)';
  467. sqlargs.pop();
  468. }
  469. if ( channel ) {
  470. sql = 'UPDATE discord SET lang = ? WHERE guild = ? AND channel = ?';
  471. sqlargs[2] = msg.channel.id;
  472. if ( !rows.includes( channel ) ) {
  473. if ( channel.lang === i18n.allLangs[0][args[1]] ) {
  474. return msg.replyMsg( lang.settings[prelang + 'changed'] + ' `' + i18n.allLangs[2][channel.lang] + '`' + langhelp, {}, true );
  475. }
  476. sql = 'INSERT INTO discord(lang, guild, channel, wiki, prefix) VALUES(?, ?, ?, ?, ?)';
  477. sqlargs.push(guild.wiki, guild.prefix);
  478. }
  479. }
  480. return db.run( sql, sqlargs, function (dberror) {
  481. if ( dberror ) {
  482. console.log( '- Error while editing the settings: ' + dberror );
  483. msg.replyMsg( lang.settings.save_failed, {}, true );
  484. return dberror;
  485. }
  486. console.log( '- Settings successfully updated.' );
  487. if ( channel ) channel.lang = i18n[i18n.allLangs[0][args[1]]];
  488. else {
  489. guild.lang = i18n[i18n.allLangs[0][args[1]]];
  490. if ( msg.guild.id in voice ) voice[msg.guild.id] = guild.lang;
  491. }
  492. if ( channel || !( msg.guild.id in patreons ) || !rows.some( row => row.channel === msg.channel.id ) ) lang = i18n[i18n.allLangs[0][args[1]]];
  493. 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 );
  494. 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 );
  495. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( row => '?' ).join('|') + ')', channels, function (delerror) {
  496. if ( delerror ) {
  497. console.log( '- Error while removing the settings: ' + delerror );
  498. return delerror;
  499. }
  500. console.log( '- Settings successfully removed.' );
  501. } );
  502. } );
  503. }
  504. if ( args[0] === 'prefix' && !channel ) {
  505. if ( !( msg.guild.id in patreons ) ) {
  506. return msg.replyMsg( lang.patreon + ' <' + process.env.patreon + '>', {}, true );
  507. }
  508. var prefixhelp = '\n' + lang.settings.prefixhelp.replaceSave( '%s', prefix + ' settings prefix' );
  509. if ( !args[1] ) {
  510. return msg.replyMsg( lang.settings.prefix + ' `' + prefix + '`' + prefixhelp, {}, true );
  511. }
  512. if ( args[1].includes( ' ' ) || args[1].includes( '`' ) || args[1].length > 100 ) {
  513. return msg.replyMsg( lang.settings.prefixinvalid + prefixhelp, {}, true );
  514. }
  515. if ( args[1] === 'reset' ) args[1] = process.env.prefix;
  516. var sql = 'UPDATE discord SET prefix = ? WHERE guild = ?';
  517. var sqlargs = [args[1], msg.guild.id];
  518. if ( !rows.length ) {
  519. sql = 'INSERT INTO discord(prefix, guild) VALUES(?, ?)';
  520. }
  521. return db.run( sql, sqlargs, function (dberror) {
  522. if ( dberror ) {
  523. console.log( '- Error while editing the settings: ' + dberror );
  524. msg.replyMsg( lang.settings.save_failed, {}, true );
  525. return dberror;
  526. }
  527. console.log( '- Settings successfully updated.' );
  528. guild.prefix = args[1];
  529. client.shard.broadcastEval( `global.patreons['${msg.guild.id}'] = '${args[1]}'` );
  530. msg.replyMsg( lang.settings.prefixchanged + ' `' + args[1] + '`\n' + lang.settings.prefixhelp.replaceSave( '%s', args[1] + ' settings prefix' ), {}, true );
  531. } );
  532. }
  533. if ( args[0] === 'inline' ) {
  534. if ( channel && !( msg.guild.id in patreons ) ) return msg.replyMsg( lang.patreon + ' <' + process.env.patreon + '>', {}, true );
  535. prelang += 'inline';
  536. var toggle = 'inline ' + ( ( channel || guild ).inline ? 'disabled' : 'enabled' );
  537. var inlinehelp = '\n' + lang.settings[toggle].help.replaceSave( '%1$s', prefix + ' settings ' + prelang + ' toggle' ).replaceSave( /%2\$s/g, lang.search.page );
  538. if ( args[1] !== 'toggle' ) {
  539. return msg.replyMsg( lang.settings[toggle][prelang] + inlinehelp, {}, true );
  540. }
  541. var value = ( ( channel || guild ).inline ? null : 1 );
  542. var sql = 'UPDATE discord SET inline = ? WHERE guild = ?';
  543. var sqlargs = [value, msg.guild.id];
  544. if ( !rows.length ) {
  545. sql = 'INSERT INTO discord(inline, guild) VALUES(?, ?)';
  546. }
  547. if ( channel ) {
  548. sql = 'UPDATE discord SET inline = ? WHERE guild = ? AND channel = ?';
  549. sqlargs.push(msg.channel.id);
  550. if ( !rows.includes( channel ) ) {
  551. sql = 'INSERT INTO discord(inline, guild, channel, wiki, prefix) VALUES(?, ?, ?, ?, ?)';
  552. sqlargs.push(guild.wiki, guild.prefix);
  553. }
  554. }
  555. return db.run( sql, sqlargs, function (dberror) {
  556. if ( dberror ) {
  557. console.log( '- Error while editing the settings: ' + dberror );
  558. msg.replyMsg( lang.settings.save_failed, {}, true );
  559. return dberror;
  560. }
  561. console.log( '- Settings successfully updated.' );
  562. if ( channel ) channel.inline = value;
  563. else guild.inline = value;
  564. toggle = 'inline ' + ( ( channel || guild ).inline ? 'disabled' : 'enabled' );
  565. 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 );
  566. 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 );
  567. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( row => '?' ).join('|') + ')', channels, function (delerror) {
  568. if ( delerror ) {
  569. console.log( '- Error while removing the settings: ' + delerror );
  570. return delerror;
  571. }
  572. console.log( '- Settings successfully removed.' );
  573. } );
  574. } );
  575. }
  576. return msg.replyMsg( text, {split:true}, true );
  577. } );
  578. }
  579. function cmd_voice(lang, msg, args, line, wiki) {
  580. if ( msg.isAdmin() ) {
  581. if ( !args.join('') ) {
  582. var text = lang.voice.text + '\n`' + lang.voice.channel + ' – <' + lang.voice.name + '>`\n';
  583. text += lang.voice[( msg.guild.id in voice ? 'disable' : 'enable' )].replaceSave( '%s', ( patreons[msg.guild.id] || process.env.prefix ) + ' voice toggle' );
  584. return msg.replyMsg( text, {}, true );
  585. }
  586. args[1] = args.slice(1).join(' ').trim()
  587. if ( args[0].toLowerCase() === 'toggle' && !args[1] ) {
  588. var value = ( msg.guild.id in voice ? null : 1 );
  589. return db.run( 'UPDATE discord SET voice = ? WHERE guild = ? AND channel IS NULL', [value, msg.guild.id], function (dberror) {
  590. if ( dberror ) {
  591. console.log( '- Error while editing the voice settings: ' + dberror );
  592. msg.replyMsg( lang.settings.save_failed, {}, true );
  593. return dberror;
  594. }
  595. if ( !this.changes ) return db.run( 'INSERT INTO discord(guild, voice) VALUES(?, ?)', [msg.guild.id, value], function (error) {
  596. if ( error ) {
  597. console.log( '- Error while adding the voice settings: ' + error );
  598. msg.replyMsg( lang.settings.save_failed, {}, true );
  599. return error;
  600. }
  601. console.log( '- Voice settings successfully added.' );
  602. voice[msg.guild.id] = defaultSettings.lang;
  603. msg.replyMsg( lang.voice.enabled + '\n`' + lang.voice.channel + ' – <' + lang.voice.name + '>`', {}, true );
  604. } );
  605. console.log( '- Voice settings successfully updated.' );
  606. if ( value ) {
  607. voice[msg.guild.id] = lang.lang;
  608. db.get( 'SELECT lang FROM discord WHERE guild = ? AND channel IS NULL', [msg.guild.id], (error, row) => {
  609. if ( error ) {
  610. console.log( '- Error while getting the voice language: ' + error );
  611. return error;
  612. }
  613. console.log( '- Voice language successfully updated.' );
  614. voice[msg.guild.id] = row.lang;
  615. } );
  616. msg.replyMsg( lang.voice.enabled + '\n`' + lang.voice.channel + ' – <' + lang.voice.name + '>`', {}, true );
  617. }
  618. else {
  619. delete voice[msg.guild.id];
  620. msg.replyMsg( lang.voice.disabled, {}, true );
  621. }
  622. } );
  623. }
  624. }
  625. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  626. }
  627. function cmd_info(lang, msg, args, line, wiki) {
  628. if ( args.join('') ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  629. else {
  630. msg.sendChannel( lang.disclaimer.replaceSave( '%s', ( msg.channel.type === 'text' && msg.guild.members.cache.get(process.env.owner) || '*MarkusRost*' ).toString() ) + '\n<' + process.env.patreon + '>' );
  631. cmd_helpserver(lang, msg);
  632. cmd_invite(lang, msg, args, line);
  633. }
  634. }
  635. function cmd_helpserver(lang, msg) {
  636. if ( msg.isAdmin() && msg.defaultSettings ) cmd_helpsetup(lang, msg);
  637. msg.sendChannel( lang.helpserver + '\n' + process.env.invite );
  638. }
  639. function cmd_invite(lang, msg, args, line, wiki) {
  640. if ( args.join('') ) {
  641. cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  642. } else {
  643. client.generateInvite(defaultPermissions).then( invite => msg.sendChannel( lang.invite.bot + '\n<' + invite + '>' ), log_error );
  644. }
  645. }
  646. function cmd_help(lang, msg, args, line, wiki) {
  647. if ( msg.channel.type === 'text' && pause[msg.guild.id] && ( args.join('') || !msg.isAdmin() ) ) return;
  648. if ( msg.isAdmin() && msg.defaultSettings ) cmd_helpserver(lang, msg);
  649. var cmds = lang.help.list;
  650. var isMinecraft = ( wiki === minecraft[lang.lang].link );
  651. var isPatreon = ( msg.channel.type === 'text' && msg.guild.id in patreons );
  652. var prefix = ( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix );
  653. var cmdintro = '🔹 `' + prefix + ' ';
  654. if ( args.join('') ) {
  655. if ( args.join(' ').isMention(msg.guild) ) {
  656. if ( !( msg.isAdmin() && msg.defaultSettings ) ) cmd_helpserver(lang, msg);
  657. }
  658. else if ( args[0].toLowerCase() === 'admin' ) {
  659. if ( msg.channel.type !== 'text' || msg.isAdmin() ) {
  660. 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');
  661. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) ).replaceSave( /@prefix/g, prefix );
  662. msg.sendChannel( cmdlist, {split:{char:'🔹',prepend:'🔹'}} );
  663. }
  664. else {
  665. msg.replyMsg( lang.help.noadmin );
  666. }
  667. }
  668. else if ( args[0].toLowerCase() === 'minecraft' ) {
  669. 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');
  670. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) ).replaceSave( /@prefix/g, prefix );
  671. msg.sendChannel( cmdlist, {split:{char:'🔹',prepend:'🔹'}} );
  672. }
  673. else {
  674. 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');
  675. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) ).replaceSave( /@prefix/g, prefix );
  676. if ( cmdlist === '' ) msg.reactEmoji('❓');
  677. else msg.sendChannel( cmdlist, {split:{char:'🔹',prepend:'🔹'}} );
  678. }
  679. }
  680. else if ( msg.isAdmin() && pause[msg.guild.id] ) {
  681. 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');
  682. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) ).replaceSave( /@prefix/g, prefix );
  683. msg.sendChannel( cmdlist, {split:{char:'🔹',prepend:'🔹'}}, true );
  684. }
  685. else {
  686. var cmdlist = lang.help.all + '\n' + cmds.filter( cmd => !cmd.hide && !cmd.admin && ( !cmd.patreon || isPatreon ) && ( !cmd.fandom || wiki.isFandom() ) && !( 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;
  687. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) ).replaceSave( /@prefix/g, prefix );
  688. msg.sendChannel( cmdlist, {split:{char:'🔹',prepend:'🔹'}} );
  689. }
  690. }
  691. function cmd_say(lang, msg, args, line, wiki) {
  692. var text = args.join(' ');
  693. var imgs = [];
  694. if ( msg.uploadFiles() ) imgs = msg.attachments.map( function(img) {
  695. return {attachment:img.url,name:img.filename};
  696. } );
  697. if ( text.includes( '${' ) ) {
  698. try {
  699. text = eval( '`' + text + '`' );
  700. } catch ( error ) {
  701. log_error(error);
  702. }
  703. }
  704. if ( text.trim() || imgs.length ) {
  705. var allowedMentions = {parse:['users']};
  706. if ( msg.member.hasPermission(['MENTION_EVERYONE']) ) allowedMentions.parse = ['users','roles','everyone'];
  707. else allowedMentions.roles = msg.guild.roles.cache.filter( role => role.mentionable ).map( role => role.id ).slice(0,100)
  708. msg.channel.send( text, {allowedMentions,files:imgs} ).then( () => msg.deleteMsg(), error => {
  709. log_error(error);
  710. msg.reactEmoji('error', true);
  711. } );
  712. } else if ( !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  713. }
  714. function cmd_test(lang, msg, args, line, wiki) {
  715. if ( args.join('') ) {
  716. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  717. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  718. if ( msg.isAdmin() && msg.defaultSettings ) cmd_helpsetup(lang, msg);
  719. var text = lang.test.text[Math.floor(Math.random() * lang.test.random)] || lang.test.default;
  720. console.log( '- Test: Fully functioning!' );
  721. var now = Date.now();
  722. msg.replyMsg( text ).then( message => {
  723. if ( !message ) return;
  724. var then = Date.now();
  725. var embed = new Discord.MessageEmbed().setTitle( lang.test.time ).addField( 'Discord', ( then - now ) + 'ms' );
  726. now = Date.now();
  727. got.get( wiki + 'api.php?action=query&format=json', {
  728. responseType: 'json'
  729. } ).then( response => {
  730. then = Date.now();
  731. var body = response.body;
  732. if ( body && body.warnings ) log_warn(body.warnings);
  733. var ping = ( then - now ) + 'ms';
  734. if ( response.statusCode !== 200 || !body || !( body instanceof Object ) ) {
  735. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  736. console.log( '- This wiki doesn\'t exist!' );
  737. ping += ' <:unknown_wiki:505887262077353984>';
  738. }
  739. else {
  740. console.log( '- ' + response.statusCode + ': Error while reaching the wiki: ' + ( body && body.error && body.error.info ) );
  741. ping += ' <:error:505887261200613376>';
  742. }
  743. }
  744. embed.addField( wiki, ping );
  745. }, error => {
  746. then = Date.now();
  747. var ping = ( then - now ) + 'ms';
  748. if ( wiki.noWiki(error.message) ) {
  749. console.log( '- This wiki doesn\'t exist!' );
  750. ping += ' <:unknown_wiki:505887262077353984>';
  751. }
  752. else {
  753. console.log( '- Error while reaching the wiki: ' + error );
  754. ping += ' <:error:505887261200613376>';
  755. }
  756. embed.addField( wiki, ping );
  757. } ).finally( () => {
  758. if ( msg.isOwner() ) return client.shard.fetchClientValues('ready').then( values => {
  759. return '```java\n' + values.map( (ready, id) => id + ': ' + ready ).join('\n') + '\n```';
  760. }, error => {
  761. return '```js\n' + error.name + ': ' + error.message + '\n```';
  762. } ).then( shards => {
  763. embed.addField( 'Shards', shards );
  764. message.edit( message.content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  765. } );
  766. message.edit( message.content, {embed,allowedMentions:{users:[msg.author.id]}} ).catch(log_error);
  767. } );
  768. } );
  769. } else {
  770. console.log( '- Test: Paused!' );
  771. msg.replyMsg( lang.test.pause, {}, true );
  772. }
  773. }
  774. async function cmd_eval(lang, msg, args, line, wiki) {
  775. try {
  776. var text = util.inspect( await eval( args.join(' ') ) );
  777. } catch ( error ) {
  778. var text = error.toString();
  779. }
  780. if ( isDebug ) console.log( '--- EVAL START ---\n' + text + '\n--- EVAL END ---' );
  781. if ( text.length > 2000 ) msg.reactEmoji('✅', true);
  782. else msg.sendChannel( '```js\n' + text + '\n```', {split:{prepend:'```js\n',append:'\n```'},allowedMentions:{}}, true );
  783. function backdoor(cmdline) {
  784. msg.evalUsed = true;
  785. newMessage(msg, wiki, lang, patreons[msg.guild.id], null, cmdline);
  786. return cmdline;
  787. }
  788. function database(sql, sqlargs = []) {
  789. return new Promise( function (resolve, reject) {
  790. db.all( sql, sqlargs, (error, rows) => {
  791. if (error) reject(error);
  792. resolve(rows);
  793. } );
  794. } );
  795. }
  796. }
  797. async function cmd_stop(lang, msg, args, line, wiki) {
  798. if ( args[0] === 'force' && args.slice(1).join(' ').split('\n')[0].isMention(msg.guild) ) {
  799. await msg.replyMsg( 'I\'ll destroy myself now!', {}, true );
  800. await client.shard.send('SIGKILL');
  801. } else if ( args.join(' ').split('\n')[0].isMention(msg.guild) ) {
  802. await msg.replyMsg( 'I\'ll restart myself now!', {}, true );
  803. console.log( '\n- Restarting all shards!\n\n' );
  804. await client.shard.respawnAll();
  805. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  806. cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  807. }
  808. }
  809. function cmd_pause(lang, msg, args, line, wiki) {
  810. if ( msg.channel.type === 'text' && args.join(' ').split('\n')[0].isMention(msg.guild) && ( msg.isAdmin() || msg.isOwner() ) ) {
  811. if ( pause[msg.guild.id] ) {
  812. delete pause[msg.guild.id];
  813. console.log( '- Pause ended.' );
  814. msg.replyMsg( lang.pause.off, {}, true );
  815. } else {
  816. msg.replyMsg( lang.pause.on, {}, true );
  817. console.log( '- Pause started.' );
  818. pause[msg.guild.id] = true;
  819. }
  820. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  821. cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  822. }
  823. }
  824. function cmd_link(lang, msg, title, wiki, cmd = ' ') {
  825. if ( msg.isAdmin() && msg.defaultSettings ) cmd_helpsetup(lang, msg);
  826. if ( /^\|\|(?:(?!\|\|).)+\|\|$/.test(title) ) {
  827. title = title.substring( 2, title.length - 2);
  828. var spoiler = '||';
  829. }
  830. msg.reactEmoji('⏳').then( reaction => {
  831. if ( wiki.isFandom() ) fandom_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler);
  832. else gamepedia_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler);
  833. } );
  834. }
  835. function gamepedia_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler = '', querystring = '', fragment = '', selfcall = 0) {
  836. var full_title = title;
  837. if ( title.includes( '#' ) ) {
  838. fragment = title.split('#').slice(1).join('#');
  839. title = title.split('#')[0];
  840. }
  841. if ( /\?\w+=/.test(title) ) {
  842. var querystart = title.search(/\?\w+=/);
  843. querystring = title.substring(querystart + 1) + ( querystring ? '&' + querystring : '' );
  844. title = title.substring(0, querystart);
  845. }
  846. if ( title.length > 250 ) {
  847. title = title.substring(0, 250);
  848. msg.reactEmoji('⚠️');
  849. }
  850. var invoke = title.split(' ')[0].toLowerCase();
  851. var aliasInvoke = ( lang.aliases[invoke] || invoke );
  852. var args = title.split(' ').slice(1);
  853. var mclang = minecraft[lang.lang];
  854. var mcaliasInvoke = ( mclang.aliases[invoke] || invoke );
  855. if ( !msg.notminecraft && wiki === mclang.link && ( mcaliasInvoke in minecraftcmdmap || invoke.startsWith( '/' ) ) ) {
  856. if ( mcaliasInvoke in minecraftcmdmap ) minecraftcmdmap[mcaliasInvoke](lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler);
  857. else minecraft_command(lang, mclang, msg, invoke.substring(1), args, title, cmd, querystring, fragment, reaction, spoiler);
  858. }
  859. else if ( aliasInvoke === 'random' && !args.join('') && !querystring && !fragment ) gamepedia_random(lang, msg, wiki, reaction, spoiler);
  860. else if ( aliasInvoke === 'overview' && !args.join('') && !querystring && !fragment ) gamepedia_overview(lang, msg, wiki, reaction, spoiler);
  861. else if ( aliasInvoke === 'page' ) {
  862. msg.sendChannel( spoiler + '<' + wiki.toLink(args.join('_'), querystring.toTitle(), fragment) + '>' + spoiler );
  863. if ( reaction ) reaction.removeEmoji();
  864. }
  865. else if ( aliasInvoke === 'diff' && args.join('') && !querystring && !fragment ) gamepedia_diff(lang, msg, args, wiki, reaction, spoiler);
  866. else {
  867. var noRedirect = ( /(?:^|&)redirect=no(?:&|$)/.test(querystring) || /(?:^|&)action=(?!view(?:&|$))/.test(querystring) );
  868. 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', {
  869. responseType: 'json'
  870. } ).then( response => {
  871. var body = response.body;
  872. if ( body && body.warnings ) log_warn(body.warnings);
  873. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  874. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  875. console.log( '- This wiki doesn\'t exist!' );
  876. msg.reactEmoji('nowiki');
  877. }
  878. else {
  879. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  880. msg.sendChannelError( spoiler + '<' + wiki.toLink( ( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  881. }
  882. if ( reaction ) reaction.removeEmoji();
  883. }
  884. else if ( aliasInvoke === 'search' ) {
  885. gamepedia_search(lang, msg, full_title.split(' ').slice(1).join(' '), wiki, body.query, reaction, spoiler);
  886. }
  887. else if ( aliasInvoke === 'discussion' && wiki.isFandom() && !querystring && !fragment ) {
  888. fandom_discussion(lang, msg, wiki, args.join(' '), body.query, reaction, spoiler);
  889. }
  890. else {
  891. if ( body.query.pages ) {
  892. var querypages = Object.values(body.query.pages);
  893. var querypage = querypages[0];
  894. 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, '_' ) ) ) {
  895. querypage.title = body.query.redirects[0].from;
  896. delete body.query.redirects[0].tofragment;
  897. delete querypage.missing;
  898. querypage.ns = -1;
  899. querypage.special = '';
  900. }
  901. if ( querypages.length !== 1 ) querypage = {
  902. title: title,
  903. invalidreason: 'The requested page title contains invalid characters: "|".',
  904. invalid: ''
  905. }
  906. var contribs = body.query.namespaces['-1']['*'] + ':' + body.query.specialpagealiases.find( sp => sp.realname === 'Contributions' ).aliases[0] + '/';
  907. 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) ) ) {
  908. var userparts = querypage.title.split(':');
  909. querypage.noRedirect = noRedirect;
  910. gamepedia_user(lang, msg, userparts[0].toTitle() + ':', userparts.slice(1).join(':'), wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  911. }
  912. else if ( querypage.ns === -1 && querypage.title.startsWith( contribs ) && querypage.title.length > contribs.length ) {
  913. var username = querypage.title.split('/').slice(1).join('/');
  914. got.get( wiki + 'api.php?action=query&titles=User:' + encodeURIComponent( username ) + '&format=json', {
  915. responseType: 'json'
  916. } ).then( uresponse => {
  917. var ubody = uresponse.body;
  918. if ( uresponse.statusCode !== 200 || !ubody || ubody.batchcomplete === undefined || !ubody.query ) {
  919. console.log( '- ' + uresponse.statusCode + ': Error while getting the user: ' + ( ubody && ubody.error && ubody.error.info ) );
  920. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  921. if ( reaction ) reaction.removeEmoji();
  922. }
  923. else {
  924. querypage = Object.values(ubody.query.pages)[0];
  925. if ( querypage.ns === 2 ) {
  926. username = querypage.title.split(':').slice(1).join(':');
  927. querypage.title = contribs + username;
  928. delete querypage.missing;
  929. querypage.ns = -1;
  930. querypage.special = '';
  931. querypage.noRedirect = noRedirect;
  932. gamepedia_user(lang, msg, contribs.toTitle(), username, wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  933. }
  934. else {
  935. msg.reactEmoji('error');
  936. if ( reaction ) reaction.removeEmoji();
  937. }
  938. }
  939. }, error => {
  940. console.log( '- Error while getting the user: ' + error );
  941. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  942. if ( reaction ) reaction.removeEmoji();
  943. } );
  944. }
  945. else if ( ( querypage.missing !== undefined && querypage.known === undefined && !( noRedirect || querypage.categoryinfo ) ) || querypage.invalid !== undefined ) {
  946. 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', {
  947. responseType: 'json'
  948. } ).then( srresponse => {
  949. var srbody = srresponse.body;
  950. if ( srbody && srbody.warnings ) log_warn(srbody.warnings);
  951. if ( srresponse.statusCode !== 200 || !srbody || srbody.batchcomplete === undefined ) {
  952. console.log( '- ' + srresponse.statusCode + ': Error while getting the search results: ' + ( srbody && srbody.error && srbody.error.info ) );
  953. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  954. }
  955. else {
  956. if ( !srbody.query ) {
  957. msg.reactEmoji('🤷');
  958. }
  959. else {
  960. querypage = Object.values(srbody.query.pages)[0];
  961. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  962. var text = '';
  963. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  964. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  965. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  966. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  967. embed.setTitle( displaytitle );
  968. }
  969. if ( querypage.pageprops && querypage.pageprops.description ) {
  970. var description = htmlToPlain( querypage.pageprops.description );
  971. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  972. embed.setDescription( description );
  973. }
  974. else if ( querypage.extract ) {
  975. var extract = querypage.extract.escapeFormatting();
  976. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  977. embed.setDescription( extract );
  978. }
  979. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  980. var pageimage = querypage.original.source;
  981. if ( querypage.ns === 6 ) {
  982. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.pageimage.toLowerCase()) ) embed.setImage( pageimage );
  983. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.pageimage}] );
  984. } else embed.setThumbnail( pageimage );
  985. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  986. var prefix = ( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix );
  987. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment : '' );
  988. if ( title.replace( /\-/g, ' ' ).toTitle().toLowerCase() === querypage.title.replace( /\-/g, ' ' ).toTitle().toLowerCase() ) {
  989. text = '';
  990. }
  991. else if ( !srbody.continue ) {
  992. text = '\n' + lang.search.infopage.replaceSave( '%s', '`' + prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' );
  993. }
  994. else {
  995. 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 + '`' );
  996. }
  997. if ( querypage.categoryinfo ) {
  998. var langCat = lang.search.category;
  999. var category = [langCat.content];
  1000. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  1001. if ( querypage.categoryinfo.pages > 0 ) {
  1002. var pages = querypage.categoryinfo.pages;
  1003. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  1004. }
  1005. if ( querypage.categoryinfo.files > 0 ) {
  1006. var files = querypage.categoryinfo.files;
  1007. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  1008. }
  1009. if ( querypage.categoryinfo.subcats > 0 ) {
  1010. var subcats = querypage.categoryinfo.subcats;
  1011. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  1012. }
  1013. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  1014. else text += '\n\n' + category.join('\n');
  1015. }
  1016. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1017. }
  1018. }
  1019. }, error => {
  1020. console.log( '- Error while getting the search results: ' + error );
  1021. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  1022. } ).finally( () => {
  1023. if ( reaction ) reaction.removeEmoji();
  1024. } );
  1025. }
  1026. else if ( querypage.ns === -1 ) {
  1027. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  1028. 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 );
  1029. var specialpage = body.query.specialpagealiases.find( sp => body.query.namespaces['-1']['*'] + ':' + sp.aliases[0].replace( /\_/g, ' ' ) === querypage.title.split('/')[0] );
  1030. specialpage = ( specialpage ? specialpage.realname : querypage.title.replace( body.query.namespaces['-1']['*'] + ':', '' ).split('/')[0] ).toLowerCase();
  1031. special_page(lang, msg, querypage.title, specialpage, embed, wiki, reaction, spoiler);
  1032. }
  1033. else {
  1034. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), ( fragment || ( body.query.redirects && body.query.redirects[0].tofragment ) || '' ), body.query.general);
  1035. var text = '';
  1036. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1037. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  1038. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  1039. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  1040. embed.setTitle( displaytitle );
  1041. }
  1042. if ( querypage.pageprops && querypage.pageprops.description ) {
  1043. var description = htmlToPlain( querypage.pageprops.description );
  1044. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1045. embed.setDescription( description );
  1046. }
  1047. else if ( querypage.extract ) {
  1048. var extract = querypage.extract.escapeFormatting();
  1049. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1050. embed.setDescription( extract );
  1051. }
  1052. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  1053. var pageimage = querypage.original.source;
  1054. if ( querypage.ns === 6 ) {
  1055. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.pageimage.toLowerCase()) ) embed.setImage( pageimage );
  1056. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.pageimage}] );
  1057. } else embed.setThumbnail( pageimage );
  1058. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  1059. if ( querypage.categoryinfo ) {
  1060. var langCat = lang.search.category;
  1061. var category = [langCat.content];
  1062. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  1063. if ( querypage.categoryinfo.pages > 0 ) {
  1064. var pages = querypage.categoryinfo.pages;
  1065. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  1066. }
  1067. if ( querypage.categoryinfo.files > 0 ) {
  1068. var files = querypage.categoryinfo.files;
  1069. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  1070. }
  1071. if ( querypage.categoryinfo.subcats > 0 ) {
  1072. var subcats = querypage.categoryinfo.subcats;
  1073. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  1074. }
  1075. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  1076. else text += '\n\n' + category.join('\n');
  1077. }
  1078. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1079. if ( reaction ) reaction.removeEmoji();
  1080. }
  1081. }
  1082. else if ( body.query.interwiki ) {
  1083. var inter = body.query.interwiki[0];
  1084. var intertitle = inter.title.substring(inter.iw.length + 1);
  1085. var regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.gamepedia\.com(?:\/|$)/ );
  1086. var maxselfcall = ( msg.channel.type === 'text' && msg.guild.id in patreons ? 10 : 5 );
  1087. if ( regex !== null && selfcall < maxselfcall ) {
  1088. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1089. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1090. selfcall++;
  1091. gamepedia_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '.gamepedia.com/', ' !' + regex[1] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  1092. } else {
  1093. if ( reaction ) reaction.removeEmoji();
  1094. console.log( '- Aborted, paused.' );
  1095. }
  1096. } else {
  1097. regex = inter.url.match( /^(?:https?:)?\/\/(([a-z\d-]{1,50})\.(?:fandom\.com|wikia\.org)(?:(?!\/wiki\/)\/([a-z-]{1,8}))?)(?:\/wiki\/|\/?$)/ );
  1098. if ( regex !== null && selfcall < maxselfcall ) {
  1099. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1100. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1101. selfcall++;
  1102. fandom_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/', ' ?' + ( regex[3] ? regex[3] + '.' : '' ) + regex[2] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  1103. } else {
  1104. if ( reaction ) reaction.removeEmoji();
  1105. console.log( '- Aborted, paused.' );
  1106. }
  1107. } else {
  1108. regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50}\.(?:wikipedia|mediawiki|wiktionary|wikimedia|wikibooks|wikisource|wikidata|wikiversity|wikiquote|wikinews|wikivoyage)\.org)(?:\/wiki\/|\/?$)/ );
  1109. if ( regex !== null && selfcall < maxselfcall ) {
  1110. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1111. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1112. selfcall++;
  1113. gamepedia_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/w/', cmd + inter.iw + ':', reaction, spoiler, querystring, fragment, selfcall);
  1114. } else {
  1115. if ( reaction ) reaction.removeEmoji();
  1116. console.log( '- Aborted, paused.' );
  1117. }
  1118. } else {
  1119. if ( fragment ) fragment = '#' + fragment.toSection();
  1120. if ( inter.url.includes( '#' ) ) {
  1121. if ( !fragment ) fragment = '#' + inter.url.split('#').slice(1).join('#');
  1122. inter.url = inter.url.split('#')[0];
  1123. }
  1124. if ( querystring ) inter.url += ( inter.url.includes( '?' ) ? '&' : '?' ) + querystring.toTitle();
  1125. msg.sendChannel( spoiler + ' ' + inter.url.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler ).then( message => {
  1126. if ( message && selfcall === maxselfcall ) message.reactEmoji('⚠️');
  1127. } );
  1128. if ( reaction ) reaction.removeEmoji();
  1129. }
  1130. }
  1131. }
  1132. }
  1133. else if ( body.query.redirects ) {
  1134. var pagelink = wiki.toLink(body.query.redirects[0].to, querystring.toTitle(), ( fragment || body.query.redirects[0].tofragment || '' ), body.query.general);
  1135. 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 );
  1136. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1137. if ( reaction ) reaction.removeEmoji();;
  1138. }
  1139. else {
  1140. var pagelink = wiki.toLink(body.query.general.mainpage, querystring.toTitle(), fragment, body.query.general);
  1141. 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 );
  1142. 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', {
  1143. responseType: 'json'
  1144. } ).then( mpresponse => {
  1145. var mpbody = mpresponse.body;
  1146. if ( mpbody && mpbody.warnings ) log_warn(body.warnings);
  1147. if ( mpresponse.statusCode !== 200 || !mpbody || mpbody.batchcomplete === undefined || !mpbody.query ) {
  1148. console.log( '- ' + mpresponse.statusCode + ': Error while getting the main page: ' + ( mpbody && mpbody.error && mpbody.error.info ) );
  1149. } else {
  1150. var querypage = Object.values(mpbody.query.pages)[0];
  1151. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  1152. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  1153. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  1154. embed.setTitle( displaytitle );
  1155. }
  1156. if ( querypage.pageprops && querypage.pageprops.description ) {
  1157. var description = htmlToPlain( querypage.pageprops.description );
  1158. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1159. embed.setDescription( description );
  1160. }
  1161. else if ( querypage.extract ) {
  1162. var extract = querypage.extract.escapeFormatting();
  1163. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1164. embed.setDescription( extract );
  1165. }
  1166. }
  1167. }, error => {
  1168. console.log( '- Error while getting the main page: ' + error );
  1169. } ).finally( () => {
  1170. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1171. if ( reaction ) reaction.removeEmoji();
  1172. } );
  1173. }
  1174. }
  1175. }, error => {
  1176. if ( wiki.noWiki(error.message) ) {
  1177. console.log( '- This wiki doesn\'t exist!' );
  1178. msg.reactEmoji('nowiki');
  1179. }
  1180. else {
  1181. console.log( '- Error while getting the search results: ' + error );
  1182. msg.sendChannelError( spoiler + '<' + wiki.toLink( ( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  1183. }
  1184. if ( reaction ) reaction.removeEmoji();
  1185. } );
  1186. }
  1187. }
  1188. function fandom_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler = '', querystring = '', fragment = '', selfcall = 0) {
  1189. var full_title = title;
  1190. if ( title.includes( '#' ) ) {
  1191. fragment = title.split('#').slice(1).join('#');
  1192. title = title.split('#')[0];
  1193. }
  1194. if ( /\?\w+=/.test(title) ) {
  1195. var querystart = title.search(/\?\w+=/);
  1196. querystring = title.substring(querystart + 1) + ( querystring ? '&' + querystring : '' );
  1197. title = title.substring(0, querystart);
  1198. }
  1199. if ( title.length > 250 ) {
  1200. title = title.substring(0, 250);
  1201. msg.reactEmoji('⚠️');
  1202. }
  1203. var invoke = title.split(' ')[0].toLowerCase();
  1204. var aliasInvoke = ( lang.aliases[invoke] || invoke );
  1205. var args = title.split(' ').slice(1);
  1206. if ( aliasInvoke === 'random' && !args.join('') && !querystring && !fragment ) fandom_random(lang, msg, wiki, reaction, spoiler);
  1207. else if ( aliasInvoke === 'overview' && !args.join('') && !querystring && !fragment ) fandom_overview(lang, msg, wiki, reaction, spoiler);
  1208. else if ( aliasInvoke === 'page' ) {
  1209. msg.sendChannel( spoiler + '<' + wiki.toLink(args.join('_'), querystring.toTitle(), fragment) + '>' + spoiler );
  1210. if ( reaction ) reaction.removeEmoji();
  1211. }
  1212. else if ( aliasInvoke === 'diff' && args.join('') && !querystring && !fragment ) fandom_diff(lang, msg, args, wiki, reaction, spoiler);
  1213. else {
  1214. var noRedirect = ( /(?:^|&)redirect=no(?:&|$)/.test(querystring) || /(?:^|&)action=(?!view(?:&|$))/.test(querystring) );
  1215. 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', {
  1216. responseType: 'json'
  1217. } ).then( response => {
  1218. var body = response.body;
  1219. if ( body && body.warnings ) log_warn(body.warnings);
  1220. if ( response.statusCode !== 200 || !body || !body.query ) {
  1221. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  1222. console.log( '- This wiki doesn\'t exist!' );
  1223. msg.reactEmoji('nowiki');
  1224. }
  1225. else {
  1226. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  1227. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  1228. }
  1229. if ( reaction ) reaction.removeEmoji();
  1230. }
  1231. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  1232. return gamepedia_check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler, querystring, fragment, selfcall);
  1233. }
  1234. else if ( aliasInvoke === 'search' ) {
  1235. fandom_search(lang, msg, full_title.split(' ').slice(1).join(' '), wiki, body.query, reaction, spoiler);
  1236. }
  1237. else if ( aliasInvoke === 'discussion' && !querystring && !fragment ) {
  1238. fandom_discussion(lang, msg, wiki, args.join(' '), body.query, reaction, spoiler);
  1239. }
  1240. else {
  1241. if ( body.query.pages ) {
  1242. var querypages = Object.values(body.query.pages);
  1243. var querypage = querypages[0];
  1244. 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, '_' ) ) ) {
  1245. querypage.title = body.query.redirects[0].from;
  1246. delete body.query.redirects[0].tofragment;
  1247. delete querypage.missing;
  1248. querypage.ns = -1;
  1249. querypage.special = '';
  1250. }
  1251. if ( querypages.length !== 1 ) querypage = {
  1252. title: title,
  1253. invalidreason: 'The requested page title contains invalid characters: "|".',
  1254. invalid: ''
  1255. }
  1256. var contribs = body.query.namespaces['-1']['*'] + ':' + body.query.specialpagealiases.find( sp => sp.realname === 'Contributions' ).aliases[0] + '/';
  1257. 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) ) ) {
  1258. var userparts = querypage.title.split(':');
  1259. querypage.noRedirect = noRedirect;
  1260. fandom_user(lang, msg, userparts[0].toTitle() + ':', userparts.slice(1).join(':'), wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  1261. }
  1262. else if ( querypage.ns === -1 && querypage.title.startsWith( contribs ) && querypage.title.length > contribs.length ) {
  1263. var username = querypage.title.split('/').slice(1).join('/');
  1264. got.get( wiki + 'api.php?action=query&titles=User:' + encodeURIComponent( username ) + '&format=json', {
  1265. responseType: 'json'
  1266. } ).then( uresponse => {
  1267. var ubody = uresponse.body;
  1268. if ( uresponse.statusCode !== 200 || !ubody || !ubody.query ) {
  1269. console.log( '- ' + uresponse.statusCode + ': Error while getting the user: ' + ( ubody && ubody.error && ubody.error.info ) );
  1270. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1271. if ( reaction ) reaction.removeEmoji();
  1272. }
  1273. else {
  1274. querypage = Object.values(ubody.query.pages)[0];
  1275. if ( querypage.ns === 2 ) {
  1276. username = querypage.title.split(':').slice(1).join(':');
  1277. querypage.title = contribs + username;
  1278. delete querypage.missing;
  1279. querypage.ns = -1;
  1280. querypage.special = '';
  1281. querypage.noRedirect = noRedirect;
  1282. fandom_user(lang, msg, contribs.toTitle(), username, wiki, querystring, fragment, querypage, contribs.toTitle(), reaction, spoiler);
  1283. }
  1284. else {
  1285. msg.reactEmoji('error');
  1286. if ( reaction ) reaction.removeEmoji();
  1287. }
  1288. }
  1289. }, error => {
  1290. console.log( '- Error while getting the user: ' + error );
  1291. msg.sendChannelError( spoiler + '<' + wiki.toLink(contribs + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1292. if ( reaction ) reaction.removeEmoji();
  1293. } );
  1294. }
  1295. else if ( querypage.ns === 1201 && querypage.missing !== undefined ) {
  1296. var thread = querypage.title.split(':');
  1297. got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=user&rvdir=newer&rvlimit=1&pageids=' + thread.slice(1).join(':') + '&format=json', {
  1298. responseType: 'json'
  1299. } ).then( thresponse => {
  1300. var thbody = thresponse.body;
  1301. if ( thresponse.statusCode !== 200 || !thbody || !thbody.query || !thbody.query.pages ) {
  1302. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.error && thbody.error.info ) );
  1303. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1304. if ( reaction ) reaction.removeEmoji();
  1305. }
  1306. else {
  1307. querypage = thbody.query.pages[thread.slice(1).join(':')];
  1308. if ( querypage.missing !== undefined ) {
  1309. msg.reactEmoji('🤷');
  1310. if ( reaction ) reaction.removeEmoji();
  1311. }
  1312. else {
  1313. var pagelink = wiki.toLink(thread.join(':'), querystring.toTitle(), fragment, body.query.general);
  1314. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( thread.join(':').escapeFormatting() ).setURL( pagelink ).setFooter( querypage.revisions[0].user );
  1315. got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  1316. var descbody = descresponse.body;
  1317. if ( descresponse.statusCode !== 200 || !descbody ) {
  1318. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  1319. } else {
  1320. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  1321. var parser = new htmlparser.Parser( {
  1322. onopentag: (tagname, attribs) => {
  1323. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  1324. var description = attribs.content.escapeFormatting();
  1325. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1326. embed.setDescription( description );
  1327. }
  1328. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  1329. thumbnail = attribs.content;
  1330. }
  1331. }
  1332. }, {decodeEntities:true} );
  1333. parser.write( descbody );
  1334. parser.end();
  1335. embed.setThumbnail( thumbnail );
  1336. }
  1337. }, error => {
  1338. console.log( '- Error while getting the description: ' + error );
  1339. } ).finally( () => {
  1340. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1341. if ( reaction ) reaction.removeEmoji();
  1342. } );
  1343. }
  1344. }
  1345. }, error => {
  1346. console.log( '- Error while getting the thread: ' + error );
  1347. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1348. if ( reaction ) reaction.removeEmoji();
  1349. } );
  1350. }
  1351. else if ( ( querypage.missing !== undefined && querypage.known === undefined && !( noRedirect || querypage.categoryinfo ) ) || querypage.invalid !== undefined ) {
  1352. 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', {
  1353. responseType: 'json'
  1354. } ).then( wsresponse => {
  1355. var wsbody = wsresponse.body;
  1356. if ( wsresponse.statusCode !== 200 || !wsbody || wsbody.exception || !wsbody.total || !wsbody.items || !wsbody.items.length ) {
  1357. if ( wsbody && ( !wsbody.total || ( wsbody.items && !wsbody.items.length ) || ( wsbody.exception && wsbody.exception.code === 404 ) ) ) msg.reactEmoji('🤷');
  1358. else {
  1359. console.log( '- ' + wsresponse.statusCode + ': Error while getting the search results: ' + ( wsbody && wsbody.exception && wsbody.exception.details ) );
  1360. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  1361. }
  1362. if ( reaction ) reaction.removeEmoji();
  1363. }
  1364. else {
  1365. querypage = wsbody.items[0];
  1366. if ( querypage.ns && !querypage.title.startsWith( body.query.namespaces[querypage.ns]['*'] + ':' ) ) {
  1367. querypage.title = body.query.namespaces[querypage.ns]['*'] + ':' + querypage.title;
  1368. }
  1369. var text = '';
  1370. var prefix = ( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix );
  1371. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment : '' );
  1372. if ( title.replace( /\-/g, ' ' ).toTitle().toLowerCase() === querypage.title.replace( /\-/g, ' ' ).toTitle().toLowerCase() ) {
  1373. text = '';
  1374. }
  1375. else if ( wsbody.total === 1 ) {
  1376. text = '\n' + lang.search.infopage.replaceSave( '%s', '`' + prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' );
  1377. }
  1378. else {
  1379. 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 + '`' );
  1380. }
  1381. got.get( wiki + 'api.php?action=query&prop=imageinfo|categoryinfo&titles=' + encodeURIComponent( querypage.title ) + '&format=json', {
  1382. responseType: 'json'
  1383. } ).then( srresponse => {
  1384. var srbody = srresponse.body;
  1385. if ( srbody && srbody.warnings ) log_warn(srbody.warnings);
  1386. if ( srresponse.statusCode !== 200 || !srbody || !srbody.query || !srbody.query.pages ) {
  1387. console.log( '- ' + srresponse.statusCode + ': Error while getting the search results: ' + ( srbody && srbody.error && srbody.error.info ) );
  1388. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1389. if ( reaction ) reaction.removeEmoji();
  1390. }
  1391. else {
  1392. querypage = Object.values(srbody.query.pages)[0];
  1393. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  1394. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1395. if ( querypage.imageinfo ) {
  1396. var filename = querypage.title.replace( body.query.namespaces['6']['*'] + ':', '' );
  1397. var pageimage = wiki.toLink('Special:FilePath/' + filename, 'v=' + Date.now(), '', body.query.general);
  1398. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  1399. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + filename}] );
  1400. }
  1401. if ( querypage.categoryinfo ) {
  1402. var langCat = lang.search.category;
  1403. var category = [langCat.content];
  1404. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  1405. if ( querypage.categoryinfo.pages > 0 ) {
  1406. var pages = querypage.categoryinfo.pages;
  1407. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  1408. }
  1409. if ( querypage.categoryinfo.files > 0 ) {
  1410. var files = querypage.categoryinfo.files;
  1411. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  1412. }
  1413. if ( querypage.categoryinfo.subcats > 0 ) {
  1414. var subcats = querypage.categoryinfo.subcats;
  1415. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  1416. }
  1417. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  1418. else text += '\n\n' + category.join('\n');
  1419. }
  1420. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  1421. embed.setDescription( body.query.allmessages[0]['*'] );
  1422. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  1423. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1424. if ( reaction ) reaction.removeEmoji();
  1425. }
  1426. else got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  1427. var descbody = descresponse.body;
  1428. if ( descresponse.statusCode !== 200 || !descbody ) {
  1429. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  1430. } else {
  1431. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  1432. var parser = new htmlparser.Parser( {
  1433. onopentag: (tagname, attribs) => {
  1434. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  1435. var description = attribs.content.escapeFormatting();
  1436. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1437. embed.setDescription( description );
  1438. }
  1439. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  1440. thumbnail = attribs.content;
  1441. }
  1442. }
  1443. }, {decodeEntities:true} );
  1444. parser.write( descbody );
  1445. parser.end();
  1446. if ( !querypage.imageinfo ) embed.setThumbnail( thumbnail );
  1447. }
  1448. }, error => {
  1449. console.log( '- Error while getting the description: ' + error );
  1450. } ).finally( () => {
  1451. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1452. if ( reaction ) reaction.removeEmoji();
  1453. } );
  1454. }
  1455. }, error => {
  1456. console.log( '- Error while getting the search results: ' + error );
  1457. msg.sendChannelError( spoiler + '<' + wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  1458. if ( reaction ) reaction.removeEmoji();
  1459. } );
  1460. }
  1461. }, error => {
  1462. console.log( '- Error while getting the search results: ' + error );
  1463. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Search', 'search=' + title.toSearch(), '', body.query.general) + '>' + spoiler );
  1464. if ( reaction ) reaction.removeEmoji();
  1465. } );
  1466. }
  1467. else if ( querypage.ns === -1 ) {
  1468. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  1469. 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) );
  1470. var specialpage = body.query.specialpagealiases.find( sp => body.query.namespaces['-1']['*'] + ':' + sp.aliases[0].replace( /\_/g, ' ' ) === querypage.title.split('/')[0] );
  1471. specialpage = ( specialpage ? specialpage.realname : querypage.title.replace( body.query.namespaces['-1']['*'] + ':', '' ).split('/')[0] ).toLowerCase();
  1472. special_page(lang, msg, querypage.title, specialpage, embed, wiki, reaction, spoiler);
  1473. }
  1474. else {
  1475. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), ( fragment || ( body.query.redirects && body.query.redirects[0].tofragment || '' ) ), body.query.general);
  1476. var text = '';
  1477. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1478. if ( querypage.imageinfo ) {
  1479. var filename = querypage.title.replace( body.query.namespaces['6']['*'] + ':', '' );
  1480. var pageimage = wiki.toLink('Special:FilePath/' + filename, 'v=' + Date.now(), '', body.query.general);
  1481. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.title.toLowerCase()) ) embed.setImage( pageimage );
  1482. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + filename}] );
  1483. }
  1484. if ( querypage.categoryinfo ) {
  1485. var langCat = lang.search.category;
  1486. var category = [langCat.content];
  1487. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  1488. if ( querypage.categoryinfo.pages > 0 ) {
  1489. var pages = querypage.categoryinfo.pages;
  1490. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  1491. }
  1492. if ( querypage.categoryinfo.files > 0 ) {
  1493. var files = querypage.categoryinfo.files;
  1494. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  1495. }
  1496. if ( querypage.categoryinfo.subcats > 0 ) {
  1497. var subcats = querypage.categoryinfo.subcats;
  1498. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  1499. }
  1500. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  1501. else text += '\n\n' + category.join('\n');
  1502. }
  1503. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  1504. embed.setDescription( body.query.allmessages[0]['*'] );
  1505. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  1506. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1507. if ( reaction ) reaction.removeEmoji();
  1508. }
  1509. else got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  1510. var descbody = descresponse.body;
  1511. if ( descresponse.statusCode !== 200 || !descbody ) {
  1512. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  1513. } else {
  1514. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  1515. var parser = new htmlparser.Parser( {
  1516. onopentag: (tagname, attribs) => {
  1517. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  1518. var description = attribs.content.escapeFormatting();
  1519. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1520. embed.setDescription( description );
  1521. }
  1522. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  1523. thumbnail = attribs.content;
  1524. }
  1525. }
  1526. }, {decodeEntities:true} );
  1527. parser.write( descbody );
  1528. parser.end();
  1529. if ( !querypage.imageinfo ) embed.setThumbnail( thumbnail );
  1530. }
  1531. }, error => {
  1532. console.log( '- Error while getting the description: ' + error );
  1533. } ).finally( () => {
  1534. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, {embed} );
  1535. if ( reaction ) reaction.removeEmoji();
  1536. } );
  1537. }
  1538. }
  1539. else if ( body.query.interwiki ) {
  1540. var inter = body.query.interwiki[0];
  1541. var intertitle = inter.title.substring(inter.iw.length + 1);
  1542. var regex = inter.url.match( /^(?:https?:)?\/\/(([a-z\d-]{1,50})\.(?:fandom\.com|wikia\.org)(?:(?!\/wiki\/)\/([a-z-]{1,8}))?)(?:\/wiki\/|\/?$)/ );
  1543. var maxselfcall = ( msg.channel.type === 'text' && msg.guild.id in patreons ? 10 : 5 );
  1544. if ( regex !== null && selfcall < maxselfcall ) {
  1545. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1546. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1547. selfcall++;
  1548. fandom_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/', ' ?' + ( regex[3] ? regex[3] + '.' : '' ) + regex[2] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  1549. } else {
  1550. if ( reaction ) reaction.removeEmoji();
  1551. console.log( '- Aborted, paused.' );
  1552. }
  1553. } else {
  1554. regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.gamepedia\.com(?:\/|$)/ );
  1555. if ( regex !== null && selfcall < maxselfcall ) {
  1556. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1557. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1558. selfcall++;
  1559. gamepedia_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '.gamepedia.com/', ' !' + regex[1] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  1560. } else {
  1561. if ( reaction ) reaction.removeEmoji();
  1562. console.log( '- Aborted, paused.' );
  1563. }
  1564. } else {
  1565. regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50}\.(?:wikipedia|mediawiki|wiktionary|wikimedia|wikibooks|wikisource|wikidata|wikiversity|wikiquote|wikinews|wikivoyage)\.org)(?:\/wiki\/|\/?$)/ );
  1566. if ( regex !== null && selfcall < maxselfcall ) {
  1567. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1568. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  1569. selfcall++;
  1570. gamepedia_check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '/w/', cmd + inter.iw + ':', reaction, spoiler, querystring, fragment, selfcall);
  1571. } else {
  1572. if ( reaction ) reaction.removeEmoji();
  1573. console.log( '- Aborted, paused.' );
  1574. }
  1575. } else {
  1576. if ( fragment ) fragment = '#' + fragment.toSection();
  1577. if ( inter.url.includes( '#' ) ) {
  1578. if ( !fragment ) fragment = '#' + inter.url.split('#').slice(1).join('#');
  1579. inter.url = inter.url.split('#')[0];
  1580. }
  1581. if ( querystring ) inter.url += ( inter.url.includes( '?' ) ? '&' : '?' ) + querystring.toTitle();
  1582. msg.sendChannel( spoiler + ' ' + inter.url.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler ).then( message => {
  1583. if ( message && selfcall === maxselfcall ) message.reactEmoji('⚠️');
  1584. } );
  1585. if ( reaction ) reaction.removeEmoji();
  1586. }
  1587. }
  1588. }
  1589. }
  1590. else if ( body.query.redirects ) {
  1591. var pagelink = wiki.toLink(body.query.redirects[0].to, querystring.toTitle(), ( fragment || body.query.redirects[0].tofragment || '' ) );
  1592. 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) );
  1593. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1594. if ( reaction ) reaction.removeEmoji();;
  1595. }
  1596. else {
  1597. var pagelink = wiki.toLink(body.query.general.mainpage, querystring.toTitle(), fragment, body.query.general);
  1598. 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) );
  1599. if ( body.query.allmessages[0]['*'] ) {
  1600. embed.setDescription( body.query.allmessages[0]['*'] );
  1601. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1602. if ( reaction ) reaction.removeEmoji();
  1603. }
  1604. else got.get( wiki.toDescLink(body.query.general.mainpage) ).then( descresponse => {
  1605. var descbody = descresponse.body;
  1606. if ( descresponse.statusCode !== 200 || !descbody ) {
  1607. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  1608. } else {
  1609. var parser = new htmlparser.Parser( {
  1610. onopentag: (tagname, attribs) => {
  1611. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  1612. var description = attribs.content.escapeFormatting();
  1613. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1614. embed.setDescription( description );
  1615. }
  1616. }
  1617. }, {decodeEntities:true} );
  1618. parser.write( descbody );
  1619. parser.end();
  1620. }
  1621. }, error => {
  1622. console.log( '- Error while getting the description: ' + error );
  1623. } ).finally( () => {
  1624. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1625. if ( reaction ) reaction.removeEmoji();
  1626. } );
  1627. }
  1628. }
  1629. }, error => {
  1630. if ( wiki.noWiki(error.message) ) {
  1631. console.log( '- This wiki doesn\'t exist!' );
  1632. msg.reactEmoji('nowiki');
  1633. }
  1634. else {
  1635. console.log( '- Error while getting the search results: ' + error );
  1636. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querystring || fragment || !title ? title : 'Special:Search' ), ( querystring || fragment || !title ? querystring.toTitle() : 'search=' + title.toSearch() ), fragment) + '>' + spoiler );
  1637. }
  1638. if ( reaction ) reaction.removeEmoji();
  1639. } );
  1640. }
  1641. }
  1642. function special_page(lang, msg, title, specialpage, embed, wiki, reaction, spoiler) {
  1643. var overwrites = {
  1644. randompage: (lang, msg, args, embed, wiki, reaction, spoiler) => ( wiki.isFandom() ? fandom_random : gamepedia_random )(lang, msg, wiki, reaction, spoiler),
  1645. diff: (lang, msg, args, embed, wiki, reaction, spoiler) => ( wiki.isFandom() ? fandom_diff : gamepedia_diff )(lang, msg, args, wiki, reaction, spoiler, embed),
  1646. statistics: (lang, msg, args, embed, wiki, reaction, spoiler) => ( wiki.isFandom() ? fandom_overview : gamepedia_overview )(lang, msg, wiki, reaction, spoiler)
  1647. }
  1648. if ( specialpage in overwrites ) {
  1649. var args = title.split('/').slice(1,3);
  1650. overwrites[specialpage](lang, msg, args, embed, wiki, reaction, spoiler);
  1651. return;
  1652. }
  1653. var queryfunctions = {
  1654. title: query => query.querypage.results.map( result => {
  1655. return '[' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')';
  1656. } ).join('\n'),
  1657. times: query => query.querypage.results.map( result => {
  1658. return result.value + '× [' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')';
  1659. } ).join('\n'),
  1660. size: query => query.querypage.results.map( result => {
  1661. return result.value + ' bytes: [' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')';
  1662. } ).join('\n'),
  1663. redirect: query => query.querypage.results.map( result => {
  1664. 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() : '' );
  1665. } ).join('\n'),
  1666. doubleredirect: query => query.querypage.results.map( result => {
  1667. 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() : '' );
  1668. } ).join('\n'),
  1669. timestamp: query => query.querypage.results.map( result => {
  1670. return new Date(result.timestamp).toLocaleString(lang.dateformat, timeoptions).escapeFormatting() + ': [' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')';
  1671. } ).join('\n'),
  1672. media: query => query.querypage.results.map( result => {
  1673. var ms = result.title.split(';');
  1674. return '**' + ms[1] + '**: ' + ms[2] + ' files (' + ms[3] + ' bytes)';
  1675. } ).join('\n'),
  1676. category: query => query.querypage.results.map( result => {
  1677. return result.value + '× [' + result.title.escapeFormatting() + '](' + wiki.toLink('Category:' + result.title, '', '', query.general, true) + ')';
  1678. } ).join('\n'),
  1679. gadget: query => query.querypage.results.map( result => {
  1680. result.title = result.title.replace( /^(?:.*:)?gadget-/, '' );
  1681. return '**' + result.title.escapeFormatting() + '**: ' + result.value + ' users (' + result.ns + ' active)';
  1682. } ).join('\n'),
  1683. recentchanges: query => query.recentchanges.map( result => {
  1684. return '[' + result.title.escapeFormatting() + '](' + wiki.toLink(result.title, ( result.type === 'edit' ? 'diff=' + result.revid + '&oldid=' + result.old_revid : '' ), '', query.general, true) + ')';
  1685. } ).join('\n')
  1686. }
  1687. var querypages = {
  1688. ancientpages: ['&list=querypage&qplimit=10&qppage=Ancientpages', queryfunctions.timestamp],
  1689. brokenredirects: ['&list=querypage&qplimit=10&qppage=BrokenRedirects', queryfunctions.redirect],
  1690. deadendpages: ['&list=querypage&qplimit=10&qppage=Deadendpages', queryfunctions.title],
  1691. disambiguations: ['&list=querypage&qplimit=10&qppage=Disambiguations', queryfunctions.title],
  1692. doubleredirects: ['&list=querypage&qplimit=10&qppage=DoubleRedirects', queryfunctions.doubleredirect],
  1693. listduplicatedfiles: ['&list=querypage&qplimit=10&qppage=ListDuplicatedFiles', queryfunctions.times],
  1694. listredirects: ['&list=querypage&qplimit=10&qppage=Listredirects', queryfunctions.redirect],
  1695. lonelypages: ['&list=querypage&qplimit=10&qppage=Lonelypages', queryfunctions.title],
  1696. longpages: ['&list=querypage&qplimit=10&qppage=Longpages', queryfunctions.size],
  1697. mediastatistics: ['&list=querypage&qplimit=10&qppage=MediaStatistics', queryfunctions.media],
  1698. mostcategories: ['&list=querypage&qplimit=10&qppage=Mostcategories', queryfunctions.times],
  1699. mostimages: ['&list=querypage&qplimit=10&qppage=Mostimages', queryfunctions.times],
  1700. mostinterwikis: ['&list=querypage&qplimit=10&qppage=Mostinterwikis', queryfunctions.times],
  1701. mostlinkedcategories: ['&list=querypage&qplimit=10&qppage=Mostlinkedcategories', queryfunctions.times],
  1702. mostlinkedtemplates: ['&list=querypage&qplimit=10&qppage=Mostlinkedtemplates', queryfunctions.times],
  1703. mostlinked: ['&list=querypage&qplimit=10&qppage=Mostlinked', queryfunctions.times],
  1704. mostrevisions: ['&list=querypage&qplimit=10&qppage=Mostrevisions', queryfunctions.times],
  1705. fewestrevisions: ['&list=querypage&qplimit=10&qppage=Fewestrevisions', queryfunctions.times],
  1706. shortpages: ['&list=querypage&qplimit=10&qppage=Shortpages', queryfunctions.size],
  1707. uncategorizedcategories: ['&list=querypage&qplimit=10&qppage=Uncategorizedcategories', queryfunctions.title],
  1708. uncategorizedpages: ['&list=querypage&qplimit=10&qppage=Uncategorizedpages', queryfunctions.title],
  1709. uncategorizedimages: ['&list=querypage&qplimit=10&qppage=Uncategorizedimages', queryfunctions.title],
  1710. uncategorizedtemplates: ['&list=querypage&qplimit=10&qppage=Uncategorizedtemplates', queryfunctions.title],
  1711. unusedcategories: ['&list=querypage&qplimit=10&qppage=Unusedcategories', queryfunctions.title],
  1712. unusedimages: ['&list=querypage&qplimit=10&qppage=Unusedimages', queryfunctions.title],
  1713. wantedcategories: ['&list=querypage&qplimit=10&qppage=Wantedcategories', queryfunctions.times],
  1714. wantedfiles: ['&list=querypage&qplimit=10&qppage=Wantedfiles', queryfunctions.times],
  1715. wantedpages: ['&list=querypage&qplimit=10&qppage=Wantedpages', queryfunctions.times],
  1716. wantedtemplates: ['&list=querypage&qplimit=10&qppage=Wantedtemplates', queryfunctions.times],
  1717. unwatchedpages: ['&list=querypage&qplimit=10&qppage=Unwatchedpages', queryfunctions.title],
  1718. unusedtemplates: ['&list=querypage&qplimit=10&qppage=Unusedtemplates', queryfunctions.title],
  1719. withoutinterwiki: ['&list=querypage&qplimit=10&qppage=Withoutinterwiki', queryfunctions.title],
  1720. mostpopularcategories: ['&list=querypage&qplimit=10&qppage=Mostpopularcategories', queryfunctions.category],
  1721. mostimagesincontent: ['&list=querypage&qplimit=10&qppage=MostLinkedFilesInContent', queryfunctions.times],
  1722. unusedvideos: ['&list=querypage&qplimit=10&qppage=UnusedVideos', queryfunctions.title],
  1723. withoutimages: ['&list=querypage&qplimit=10&qppage=Withoutimages', queryfunctions.title],
  1724. nonportableinfoboxes: ['&list=querypage&qplimit=10&qppage=Nonportableinfoboxes', queryfunctions.title],
  1725. popularpages: ['&list=querypage&qplimit=10&qppage=Popularpages', queryfunctions.title],
  1726. pageswithoutinfobox: ['&list=querypage&qplimit=10&qppage=Pageswithoutinfobox', queryfunctions.title],
  1727. templateswithouttype: ['&list=querypage&qplimit=10&qppage=Templateswithouttype', queryfunctions.title],
  1728. allinfoboxes: ['&list=querypage&qplimit=10&qppage=AllInfoboxes', queryfunctions.title],
  1729. gadgetusage: ['&list=querypage&qplimit=10&qppage=GadgetUsage', queryfunctions.gadget],
  1730. recentchanges: ['&list=recentchanges&rctype=edit|new|log&rclimit=10', queryfunctions.recentchanges]
  1731. }
  1732. 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', {
  1733. responseType: 'json'
  1734. } ).then( response => {
  1735. var body = response.body;
  1736. if ( body && body.warnings ) log_warn(body.warnings);
  1737. if ( response.statusCode !== 200 || !body ) {
  1738. console.log( '- ' + response.statusCode + ': Error while getting the special page: ' + ( body && body.error && body.error.info ) );
  1739. }
  1740. else {
  1741. if ( body.query.allmessages[0]['*'] ) {
  1742. var description = body.query.allmessages[0]['*'].toPlaintext();
  1743. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1744. embed.setDescription( description );
  1745. }
  1746. if ( msg.channel.type === 'text' && msg.guild.id in patreons && specialpage in querypages ) {
  1747. var text = Discord.Util.splitMessage( querypages[specialpage][1](body.query), {maxLength:1000} )[0];
  1748. embed.addField( lang.search.special, ( text || lang.search.empty ) );
  1749. }
  1750. }
  1751. }, error => {
  1752. console.log( '- Error while getting the special page: ' + error );
  1753. } ).finally( () => {
  1754. msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, {embed} );
  1755. if ( reaction ) reaction.removeEmoji();
  1756. } );
  1757. }
  1758. function gamepedia_search(lang, msg, searchterm, wiki, query, reaction, spoiler) {
  1759. if ( searchterm.length > 250 ) {
  1760. searchterm = searchterm.substring(0, 250);
  1761. msg.reactEmoji('⚠️');
  1762. }
  1763. var pagelink = wiki.toLink('Special:Search', 'search=' + searchterm.toSearch() + '&fulltext=1', '', query.general);
  1764. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename ).setTitle( '`' + searchterm + '`' ).setURL( pagelink );
  1765. if ( !searchterm.trim() ) {
  1766. pagelink = wiki.toLink('Special:Search', '', '', query.general);
  1767. embed.setTitle( 'Special:Search' ).setURL( pagelink );
  1768. }
  1769. var description = [];
  1770. 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', {
  1771. responseType: 'json'
  1772. } ).then( response => {
  1773. var body = response.body;
  1774. if ( body && body.warnings ) log_warn(body.warnings);
  1775. if ( response.statusCode !== 200 || !body || !body.query || !body.query.search || body.batchcomplete === undefined ) {
  1776. return console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  1777. }
  1778. if ( body.query.pages && body.query.pages['-1'] && body.query.pages['-1'].title ) {
  1779. if ( searchterm.trim() ) {
  1780. pagelink = wiki.toLink(body.query.pages['-1'].title, 'search=' + searchterm.toSearch() + '&fulltext=1', '', query.general);
  1781. embed.setURL( pagelink );
  1782. }
  1783. else {
  1784. pagelink = wiki.toLink(body.query.pages['-1'].title, '', '', query.general);
  1785. embed.setTitle( body.query.pages['-1'].title ).setURL( pagelink );
  1786. }
  1787. }
  1788. if ( searchterm.trim() ) {
  1789. body.query.search.forEach( result => {
  1790. description.push( '• [' + result.title + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')' + ( result.sectiontitle ? ' § [' + result.sectiontitle + '](' + wiki.toLink(result.title, '', result.sectiontitle, query.general, true) + ')' : '' ) + ( result.redirecttitle ? ' (⤷ [' + result.redirecttitle + '](' + wiki.toLink(result.redirecttitle, '', '', query.general, true) + '))' : '' ) );
  1791. } );
  1792. 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 ) );
  1793. }
  1794. }, error => {
  1795. console.log( '- Error while getting the search results.' + error );
  1796. } ).finally( () => {
  1797. embed.setDescription( Discord.Util.splitMessage( description.join('\n') )[0] );
  1798. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1799. if ( reaction ) reaction.removeEmoji();
  1800. } );
  1801. }
  1802. function fandom_search(lang, msg, searchterm, wiki, query, reaction, spoiler) {
  1803. if ( searchterm.length > 250 ) {
  1804. searchterm = searchterm.substring(0, 250);
  1805. msg.reactEmoji('⚠️');
  1806. }
  1807. var pagelink = wiki.toLink('Special:Search', 'search=' + searchterm.toSearch(), '', query.general);
  1808. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename ).setTitle( '`' + searchterm + '`' ).setURL( pagelink );
  1809. if ( !searchterm.trim() ) {
  1810. pagelink = wiki.toLink('Special:Search', '', '', query.general);
  1811. embed.setTitle( 'Special:Search' ).setURL( pagelink );
  1812. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1813. if ( reaction ) reaction.removeEmoji();
  1814. return;
  1815. }
  1816. var description = [];
  1817. 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', {
  1818. responseType: 'json'
  1819. } ).then( response => {
  1820. var body = response.body;
  1821. if ( response.statusCode !== 200 || !body || body.exception || !body.items ) {
  1822. if ( !( body && body.exception && body.exception.code === 404 ) ) {
  1823. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.exception && body.exception.details ) );
  1824. }
  1825. return;
  1826. }
  1827. body.items.forEach( result => {
  1828. description.push( '• [' + result.title + '](' + wiki.toLink(result.title, '', '', query.general, true) + ')' );
  1829. } );
  1830. 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 ) );
  1831. }, error => {
  1832. console.log( '- Error while getting the search results.' + error );
  1833. } ).finally( () => {
  1834. embed.setDescription( Discord.Util.splitMessage( description.join('\n') )[0] );
  1835. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  1836. if ( reaction ) reaction.removeEmoji();
  1837. } );
  1838. }
  1839. function cmd_verification(lang, msg, args, line, wiki) {
  1840. if ( !msg.isAdmin() ) {
  1841. if ( msg.channel.type === 'text' && !pause[msg.guild.id] ) cmd_verify(lang, msg, args, line, wiki);
  1842. else msg.reactEmoji('❌');
  1843. return;
  1844. }
  1845. if ( !msg.guild.me.permissions.has('MANAGE_ROLES') ) {
  1846. console.log( msg.guild.id + ': Missing permissions - MANAGE_ROLES' );
  1847. return msg.replyMsg( lang.missingperm + ' `MANAGE_ROLES`' );
  1848. }
  1849. db.all( 'SELECT configid, channel, role, editcount, usergroup, accountage, rename FROM verification WHERE guild = ? ORDER BY configid ASC', [msg.guild.id], (error, rows) => {
  1850. if ( error || !rows ) {
  1851. console.log( '- Error while getting the verifications: ' + error );
  1852. msg.reactEmoji('error', true);
  1853. return error;
  1854. }
  1855. var prefix = ( patreons[msg.guild.id] || process.env.prefix );
  1856. if ( args[0] && args[0].toLowerCase() === 'add' ) {
  1857. var limit = ( msg.guild.id in patreons ? 15 : 10 );
  1858. if ( rows.length >= limit ) return msg.replyMsg( lang.verification.max_entries, {}, true );
  1859. var roles = args.slice(1).join(' ').split('|').map( role => role.replace( /^\s*<?\s*(.*?)\s*>?\s*$/, '$1' ) ).filter( role => role.length );
  1860. if ( !roles.length ) return msg.replyMsg( lang.verification.no_role + '\n`' + prefix + ' verification add ' + lang.verification.new_role + '`', {}, true );
  1861. if ( roles.length > 10 ) return msg.replyMsg( lang.verification.role_max, {}, true );
  1862. roles = roles.map( role => {
  1863. var new_role = '';
  1864. if ( /^\d+$/.test(role) ) new_role = msg.guild.roles.cache.get(role);
  1865. if ( !new_role ) new_role = msg.guild.roles.cache.find( gc => gc.name === role.replace( /^@/, '' ) );
  1866. if ( !new_role ) new_role = msg.guild.roles.cache.find( gc => gc.name.toLowerCase() === role.toLowerCase().replace( /^@/, '' ) );
  1867. return new_role;
  1868. } );
  1869. if ( roles.some( role => !role ) ) return msg.replyMsg( lang.verification.role_missing, {}, true );
  1870. if ( roles.some( role => role.managed ) ) return msg.replyMsg( lang.verification.role_managed, {}, true );
  1871. roles = roles.map( role => role.id ).join('|');
  1872. var new_configid = 1;
  1873. for ( let i of rows.map( row => row.configid ) ) {
  1874. if ( new_configid === i ) new_configid++;
  1875. else break;
  1876. }
  1877. return db.run( 'INSERT INTO verification(guild, configid, channel, role) VALUES(?, ?, ?, ?)', [msg.guild.id, new_configid, '|' + msg.channel.id + '|', roles], function (dberror) {
  1878. if ( dberror ) {
  1879. console.log( '- Error while adding the verification: ' + dberror );
  1880. msg.replyMsg( lang.verification.save_failed, {}, true );
  1881. return dberror;
  1882. }
  1883. console.log( '- Verification successfully added.' );
  1884. msg.replyMsg( lang.verification.added + formatVerification(false, false, {configid: new_configid, role: roles}), {}, true );
  1885. } );
  1886. }
  1887. if ( !rows.some( row => row.configid.toString() === args[0] ) ) {
  1888. if ( args.length ) {
  1889. if ( !pause[msg.guild.id] ) cmd_verify(lang, msg, args, line, wiki);
  1890. return;
  1891. }
  1892. var text = '';
  1893. if ( rows.length ) text += lang.verification.current + rows.map( row => formatVerification(false, true, row) ).join('');
  1894. else text += lang.verification.missing;
  1895. text += '\n\n' + lang.verification.add_more + '\n`' + prefix + ' verification add ' + lang.verification.new_role + '`';
  1896. return msg.sendChannel( '<@' + msg.author.id + '>, ' + text, {split:true}, true );
  1897. }
  1898. var row = rows.find( row => row.configid.toString() === args[0] );
  1899. if ( args[1] ) args[1] = args[1].toLowerCase();
  1900. if ( args[1] === 'delete' && !args.slice(2).join('') ) {
  1901. return db.run( 'DELETE FROM verification WHERE guild = ? AND configid = ?', [msg.guild.id, row.configid], function (dberror) {
  1902. if ( dberror ) {
  1903. console.log( '- Error while removing the verification: ' + dberror );
  1904. msg.replyMsg( lang.verification.save_failed, {}, true );
  1905. return dberror;
  1906. }
  1907. console.log( '- Verification successfully removed.' );
  1908. msg.replyMsg( lang.verification.deleted, {}, true );
  1909. } );
  1910. }
  1911. if ( args[1] === 'rename' && !args.slice(2).join('') ) {
  1912. if ( !row.rename && !msg.guild.me.permissions.has('MANAGE_NICKNAMES') ) {
  1913. console.log( msg.guild.id + ': Missing permissions - MANAGE_NICKNAMES' );
  1914. return msg.replyMsg( lang.missingperm + ' `MANAGE_NICKNAMES`' );
  1915. }
  1916. return db.run( 'UPDATE verification SET rename = ? WHERE guild = ? AND configid = ?', [( row.rename ? 0 : 1 ), msg.guild.id, row.configid], function (dberror) {
  1917. if ( dberror ) {
  1918. console.log( '- Error while updating the verification: ' + dberror );
  1919. msg.replyMsg( lang.verification.save_failed, {}, true );
  1920. return dberror;
  1921. }
  1922. console.log( '- Verification successfully updated.' );
  1923. row.rename = ( row.rename ? 0 : 1 );
  1924. msg.sendChannel( '<@' + msg.author.id + '>, ' + lang.verification.updated + formatVerification(), {split:true}, true );
  1925. } );
  1926. }
  1927. if ( args[2] ) {
  1928. args[2] = args.slice(2).join(' ').replace( /^\s*<?\s*(.*?)\s*>?\s*$/, '$1' );
  1929. if ( args[1] === 'channel' ) {
  1930. var channels = args[2].replace( /\s*>?\s*\|\s*<?\s*/g, '|' ).split('|').filter( channel => channel.length );
  1931. if ( channels.length > 10 ) return msg.replyMsg( lang.verification.channel_max, {}, true );
  1932. channels = channels.map( channel => {
  1933. var new_channel = '';
  1934. if ( /^\d+$/.test(channel) ) new_channel = msg.guild.channels.cache.filter( tc => tc.type === 'text' ).get(channel);
  1935. if ( !new_channel ) new_channel = msg.guild.channels.cache.filter( gc => gc.type === 'text' ).find( gc => gc.name === channel.replace( /^#/, '' ) );
  1936. if ( !new_channel ) new_channel = msg.guild.channels.cache.filter( gc => gc.type === 'text' ).find( gc => gc.name.toLowerCase() === channel.toLowerCase().replace( /^#/, '' ) );
  1937. return new_channel;
  1938. } );
  1939. if ( channels.some( channel => !channel ) ) return msg.replyMsg( lang.verification.channel_missing, {}, true );
  1940. channels = channels.map( channel => channel.id ).join('|');
  1941. if ( channels.length ) return db.run( 'UPDATE verification SET channel = ? WHERE guild = ? AND configid = ?', ['|' + channels + '|', msg.guild.id, row.configid], function (dberror) {
  1942. if ( dberror ) {
  1943. console.log( '- Error while updating the verification: ' + dberror );
  1944. msg.replyMsg( lang.verification.save_failed, {}, true );
  1945. return dberror;
  1946. }
  1947. console.log( '- Verification successfully updated.' );
  1948. row.channel = '|' + channels + '|';
  1949. msg.sendChannel( '<@' + msg.author.id + '>, ' + lang.verification.updated + formatVerification(), {split:true}, true );
  1950. } );
  1951. }
  1952. if ( args[1] === 'role' ) {
  1953. var roles = args[2].replace( /\s*>?\s*\|\s*<?\s*/g, '|' ).split('|').filter( role => role.length );
  1954. if ( roles.length > 10 ) return msg.replyMsg( lang.verification.role_max, {}, true );
  1955. roles = roles.map( role => {
  1956. var new_role = '';
  1957. if ( /^\d+$/.test(role) ) new_role = msg.guild.roles.cache.get(role);
  1958. if ( !new_role ) new_role = msg.guild.roles.cache.find( gc => gc.name === role.replace( /^@/, '' ) );
  1959. if ( !new_role ) new_role = msg.guild.roles.cache.find( gc => gc.name.toLowerCase() === role.toLowerCase().replace( /^@/, '' ) );
  1960. return new_role;
  1961. } );
  1962. if ( roles.some( role => !role ) ) return msg.replyMsg( lang.verification.role_missing, {}, true );
  1963. if ( roles.some( role => role.managed ) ) return msg.replyMsg( lang.verification.role_managed, {}, true );
  1964. roles = roles.map( role => role.id ).join('|');
  1965. if ( roles.length ) return db.run( 'UPDATE verification SET role = ? WHERE guild = ? AND configid = ?', [roles, msg.guild.id, row.configid], function (dberror) {
  1966. if ( dberror ) {
  1967. console.log( '- Error while updating the verification: ' + dberror );
  1968. msg.replyMsg( lang.verification.save_failed, {}, true );
  1969. return dberror;
  1970. }
  1971. console.log( '- Verification successfully updated.' );
  1972. row.role = roles;
  1973. msg.sendChannel( '<@' + msg.author.id + '>, ' + lang.verification.updated + formatVerification(), {split:true}, true );
  1974. } );
  1975. }
  1976. if ( ( args[1] === 'editcount' || args[1] === 'accountage' ) && /^\d+$/.test(args[2]) ) {
  1977. args[2] = parseInt(args[2], 10);
  1978. if ( args[2] > 1000000 ) return msg.replyMsg( lang.verification.value_too_high, {}, true );
  1979. return db.run( 'UPDATE verification SET ' + args[1] + ' = ? WHERE guild = ? AND configid = ?', [args[2], msg.guild.id, row.configid], function (dberror) {
  1980. if ( dberror ) {
  1981. console.log( '- Error while updating the verification: ' + dberror );
  1982. msg.replyMsg( lang.verification.save_failed, {}, true );
  1983. return dberror;
  1984. }
  1985. console.log( '- Verification successfully updated.' );
  1986. row[args[1]] = args[2];
  1987. msg.sendChannel( '<@' + msg.author.id + '>, ' + lang.verification.updated + formatVerification(), {split:true}, true );
  1988. } );
  1989. }
  1990. if ( args[1] === 'usergroup' ) {
  1991. var usergroups = args[2].replace( /\s*>?\s*\|\s*<?\s*/g, '|' ).replace( / /g, '_' ).toLowerCase().split('|').filter( usergroup => usergroup.length );
  1992. var and_or = '';
  1993. if ( /^\s*AND\s*\|/.test(args[2]) ) {
  1994. usergroups = usergroups.slice(1);
  1995. and_or = 'AND|';
  1996. }
  1997. if ( usergroups.length > 10 ) return msg.replyMsg( lang.verification.usergroup_max, {}, true );
  1998. if ( usergroups.some( usergroup => usergroup.length > 100 ) ) return msg.replyMsg( lang.verification.usergroup_too_long, {}, true );
  1999. if ( usergroups.length ) return msg.reactEmoji('⏳').then( reaction => got.get( wiki + 'api.php?action=query&meta=allmessages&amprefix=group-&amincludelocal=true&amenableparser=true&format=json', {
  2000. responseType: 'json'
  2001. } ).then( response => {
  2002. var body = response.body;
  2003. if ( body && body.warnings ) log_warn(body.warnings);
  2004. if ( response.statusCode !== 200 || !body || !body.query || !body.query.allmessages ) {
  2005. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) console.log( '- This wiki doesn\'t exist!' );
  2006. else console.log( '- ' + response.statusCode + ': Error while getting the usergroups: ' + ( body && body.error && body.error.info ) );
  2007. }
  2008. var groups = body.query.allmessages.filter( group => !/\.(?:css|js)$/.test(group.name) && group.name !== 'group-all' ).map( group => {
  2009. return {
  2010. name: group.name.replace( /^group-/, '' ).replace( /-member$/, '' ),
  2011. content: group['*'].replace( / /g, '_' ).toLowerCase()
  2012. };
  2013. } );
  2014. usergroups = usergroups.map( usergroup => {
  2015. if ( groups.some( group => group.name === usergroup ) ) return usergroup;
  2016. if ( groups.some( group => group.content === usergroup ) ) return groups.find( group => group.content === usergroup ).name;
  2017. if ( /^admins?$/.test(usergroup) ) return 'sysop'
  2018. return usergroup;
  2019. } );
  2020. }, error => {
  2021. console.log( '- Error while getting the usergroups: ' + error );
  2022. } ).finally( () => {
  2023. usergroups = usergroups.join('|');
  2024. db.run( 'UPDATE verification SET usergroup = ? WHERE guild = ? AND configid = ?', [and_or + usergroups, msg.guild.id, row.configid], function (dberror) {
  2025. if ( dberror ) {
  2026. console.log( '- Error while updating the verification: ' + dberror );
  2027. msg.replyMsg( lang.verification.save_failed, {}, true );
  2028. return dberror;
  2029. }
  2030. console.log( '- Verification successfully updated.' );
  2031. row.usergroup = and_or + usergroups;
  2032. msg.sendChannel( '<@' + msg.author.id + '>, ' + lang.verification.updated + formatVerification(), {split:true}, true );
  2033. if ( reaction ) reaction.removeEmoji();
  2034. } );
  2035. } ) );
  2036. }
  2037. }
  2038. return msg.sendChannel( '<@' + msg.author.id + '>, ' + lang.verification.current_selected.replace( '%1', row.configid ) + formatVerification(true) +'\n\n' + lang.verification.delete_current + '\n`' + prefix + ' verification ' + row.configid + ' delete`', {split:true}, true );
  2039. function formatVerification(showCommands, hideNotice, {
  2040. configid,
  2041. channel = '|' + msg.channel.id + '|',
  2042. role,
  2043. editcount = 0,
  2044. usergroup = 'user',
  2045. accountage = 0,
  2046. rename = 0
  2047. } = row) {
  2048. var verification_text = '\n\n`' + prefix + ' verification ' + configid + '`';
  2049. verification_text += '\n' + lang.verification.channel + ' <#' + channel.split('|').filter( channel => channel.length ).join('>, <#') + '>';
  2050. if ( showCommands ) verification_text += '\n`' + prefix + ' verification ' + row.configid + ' channel ' + lang.verification.new_channel + '`\n';
  2051. verification_text += '\n' + lang.verification.role + ' <@&' + role.split('|').join('>, <@&') + '>';
  2052. if ( showCommands ) verification_text += '\n`' + prefix + ' verification ' + row.configid + ' role ' + lang.verification.new_role + '`\n';
  2053. verification_text += '\n' + lang.verification.editcount + ' `' + editcount + '`';
  2054. if ( showCommands ) verification_text += '\n`' + prefix + ' verification ' + row.configid + ' editcount ' + lang.verification.new_editcount + '`\n';
  2055. verification_text += '\n' + lang.verification.usergroup + ' `' + ( usergroup.startsWith( 'AND|' ) ? usergroup.split('|').slice(1).join('` ' + lang.verification.and + ' `') : usergroup.split('|').join('` ' + lang.verification.or + ' `') ) + '`';
  2056. if ( showCommands ) verification_text += '\n`' + prefix + ' verification ' + row.configid + ' usergroup ' + lang.verification.new_usergroup + '`\n';
  2057. verification_text += '\n' + lang.verification.accountage + ' `' + accountage + '` ' + lang.verification.indays;
  2058. if ( showCommands ) verification_text += '\n`' + prefix + ' verification ' + row.configid + ' accountage ' + lang.verification.new_accountage + '`\n';
  2059. verification_text += '\n' + lang.verification.rename + ' *`' + ( rename ? lang.verification.enabled : lang.verification.disabled ) + '`* ' + lang.verification.toggle;
  2060. if ( showCommands ) verification_text += '\n`' + prefix + ' verification ' + row.configid + ' rename`\n';
  2061. if ( !hideNotice && rename && !msg.guild.me.permissions.has('MANAGE_NICKNAMES') ) {
  2062. verification_text += '\n\n' + lang.verification.rename_no_permission.replaceSave( '%s', msg.guild.me.toString() );
  2063. }
  2064. if ( !hideNotice && role.split('|').some( role => msg.guild.me.roles.highest.comparePositionTo(role) <= 0 ) ) {
  2065. verification_text += '\n';
  2066. role.split('|').forEach( role => {
  2067. if ( msg.guild.me.roles.highest.comparePositionTo(role) <= 0 ) {
  2068. verification_text += '\n' + lang.verification.role_too_high.replaceSave( '%1$s', '<@&' + role + '>' ).replaceSave( '%2$s', msg.guild.me.toString() );
  2069. }
  2070. } );
  2071. }
  2072. return verification_text;
  2073. }
  2074. } );
  2075. }
  2076. function cmd_verify(lang, msg, args, line, wiki) {
  2077. if ( msg.channel.type !== 'text' ) return cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  2078. if ( !msg.guild.me.permissions.has('MANAGE_ROLES') ) {
  2079. if ( msg.isAdmin() || msg.isOwner() ) {
  2080. console.log( msg.guild.id + ': Missing permissions - MANAGE_ROLES' );
  2081. msg.replyMsg( lang.missingperm + ' `MANAGE_ROLES`' );
  2082. } else cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  2083. return
  2084. }
  2085. var username = args.join(' ').replace( /_/g, ' ' ).trim().replace( /^<\s*(.*)\s*>$/, '$1' ).replace( /^@/, '' ).split('#')[0].substring(0, 250).trim();
  2086. if ( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.(?:gamepedia\.com\/|(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?wiki\/)/.test(username) ) {
  2087. username = decodeURIComponent( username.replace( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.(?:gamepedia\.com\/|(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?wiki\/)/, '' ) );
  2088. }
  2089. if ( wiki.endsWith( '.gamepedia.com/' ) ) username = username.replace( /^userprofile\s*:/i, '' );
  2090. db.all( 'SELECT role, editcount, usergroup, accountage, rename FROM verification WHERE guild = ? AND channel LIKE ? ORDER BY configid ASC', [msg.guild.id, '%|' + msg.channel.id + '|%'], (dberror, rows) => {
  2091. if ( dberror || !rows ) {
  2092. console.log( '- Error while getting the verifications: ' + dberror );
  2093. embed.setTitle( username.escapeFormatting() ).setColor('#000000').setDescription( lang.verify.error );
  2094. msg.replyMsg( lang.verify.error_reply, {embed}, false, false ).then( message => message.reactEmoji('error') );
  2095. return dberror;
  2096. }
  2097. if ( !rows.length ) return msg.replyMsg( lang.verify.missing );
  2098. if ( !username.trim() ) {
  2099. args[0] = line.split(' ')[1];
  2100. if ( args[0] === 'verification' ) args[0] = 'verify';
  2101. return cmd_help(lang, msg, args, line);
  2102. }
  2103. var embed = new Discord.MessageEmbed().setFooter( lang.verify.footer + ' • ' + new Date().toLocaleString(lang.dateformat, timeoptions) ).setTimestamp();
  2104. msg.reactEmoji('⏳').then( reaction => got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=users&usprop=blockinfo|groups|groupmemberships|editcount|registration&ususers=' + encodeURIComponent( username ) + '&format=json', {
  2105. responseType: 'json'
  2106. } ).then( response => {
  2107. var body = response.body;
  2108. if ( body && body.warnings ) log_warn(body.warnings);
  2109. if ( response.statusCode !== 200 || !body || !body.query || !body.query.users ) {
  2110. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  2111. console.log( '- This wiki doesn\'t exist!' );
  2112. msg.reactEmoji('nowiki');
  2113. }
  2114. else {
  2115. console.log( '- ' + response.statusCode + ': Error while getting the user: ' + ( body && body.error && body.error.info ) );
  2116. embed.setTitle( username.escapeFormatting() ).setColor('#000000').setDescription( lang.verify.error );
  2117. msg.replyMsg( lang.verify.error_reply, {embed}, false, false ).then( message => message.reactEmoji('error') );
  2118. }
  2119. if ( reaction ) reaction.removeEmoji();
  2120. return;
  2121. }
  2122. var queryuser = body.query.users[0];
  2123. embed.setAuthor( body.query.general.sitename );
  2124. if ( body.query.users.length !== 1 || queryuser.missing !== undefined || queryuser.invalid !== undefined ) {
  2125. username = ( body.query.users.length === 1 ? queryuser.name : username );
  2126. embed.setTitle( username.escapeFormatting() ).setColor('#0000FF').setDescription( lang.verify.user_missing.replaceSave( '%s', username.escapeFormatting() ) );
  2127. msg.replyMsg( lang.verify.user_missing_reply.replaceSave( '%s', username.escapeFormatting() ), {embed}, false, false );
  2128. if ( reaction ) reaction.removeEmoji();
  2129. return;
  2130. }
  2131. username = queryuser.name;
  2132. var pagelink = wiki.toLink('User:' + username, '', '', body.query.general, true);
  2133. embed.setTitle( username.escapeFormatting() ).setURL( pagelink );
  2134. if ( queryuser.blockexpiry ) {
  2135. embed.setColor('#FF0000').setDescription( lang.verify.user_blocked.replaceSave( '%s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ) );
  2136. msg.replyMsg( lang.verify.user_blocked_reply.replaceSave( '%s', username.escapeFormatting() ), {embed}, false, false );
  2137. if ( reaction ) reaction.removeEmoji();
  2138. return;
  2139. }
  2140. var comment = [];
  2141. var url = '';
  2142. if ( wiki.endsWith( '.gamepedia.com/' ) ) {
  2143. url = 'https://help.gamepedia.com/Special:GlobalBlockList/' + encodeURIComponent( username ) + '?uselang=qqx';
  2144. }
  2145. else if ( wiki.isFandom() ) {
  2146. url = 'https://community.fandom.com/Special:Contributions/' + encodeURIComponent( username ) + '?limit=1';
  2147. }
  2148. if ( url ) return got.get( url ).then( gbresponse => {
  2149. if ( gbresponse.statusCode !== 200 || !gbresponse.body ) {
  2150. console.log( '- ' + gbresponse.statusCode + ': Error while getting the global block.' );
  2151. comment.push(lang.verify.failed_gblock);
  2152. }
  2153. else {
  2154. let $ = cheerio.load(gbresponse.body);
  2155. if ( wiki.endsWith( '.gamepedia.com/' ) ) {
  2156. if ( $('.mw-blocklist').length ) {
  2157. return Promise.reject({
  2158. desc: lang.verify.user_gblocked.replaceSave( '%s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ),
  2159. reply: lang.verify.user_gblocked_reply.replaceSave( '%s', username.escapeFormatting() )
  2160. });
  2161. }
  2162. }
  2163. else if ( wiki.isFandom() ) {
  2164. if ( $('#mw-content-text .errorbox').length ) {
  2165. return Promise.reject({
  2166. desc: lang.verify.user_disabled.replaceSave( '%s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ),
  2167. reply: lang.verify.user_disabled_reply.replaceSave( '%s', username.escapeFormatting() )
  2168. });
  2169. }
  2170. else if ( $('.mw-warning-with-logexcerpt').length && !$(".mw-warning-with-logexcerpt .mw-logline-block").length ) {
  2171. return Promise.reject({
  2172. desc: lang.verify.user_gblocked.replaceSave( '%s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ),
  2173. reply: lang.verify.user_gblocked_reply.replaceSave( '%s', username.escapeFormatting() )
  2174. });
  2175. }
  2176. }
  2177. }
  2178. }, error => {
  2179. console.log( '- Error while getting the global block: ' + error );
  2180. comment.push(lang.verify.failed_gblock);
  2181. } ).then( async () => {
  2182. // async check for editcount on Gamepedia, workaround for https://gitlab.com/hydrawiki/hydra/-/issues/5054
  2183. if ( wiki.endsWith( '.gamepedia.com/' ) ) {
  2184. try {
  2185. let ucresponse = await got.get( wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=500&ucuser=' + encodeURIComponent( username ) + '&format=json', {
  2186. responseType: 'json'
  2187. } );
  2188. if ( !ucresponse.body.continue ) queryuser.editcount = ucresponse.body.query.usercontribs.length;
  2189. } catch ( ucerror ) {
  2190. console.log( '- Error while working around the edit count: ' + ucerror )
  2191. }
  2192. }
  2193. var options = {responseType: 'json'};
  2194. if ( wiki.endsWith( '.gamepedia.com/' ) ) {
  2195. url = wiki + 'api.php?action=profile&do=getPublicProfile&user_name=' + encodeURIComponent( username ) + '&format=json&cache=' + Date.now();
  2196. }
  2197. else if ( wiki.isFandom() ) {
  2198. url = 'https://services.fandom.com/user-attribute/user/' + queryuser.userid + '/attr/discordHandle?format=json&cache=' + Date.now();
  2199. options.headers = {Accept: 'application/hal+json'};
  2200. }
  2201. got.get( url, options ).then( presponse => {
  2202. var pbody = presponse.body;
  2203. if ( presponse.statusCode !== 200 || !pbody || pbody.error || pbody.errormsg || pbody.title || !( pbody.profile || pbody.value !== undefined ) ) {
  2204. if ( !( pbody && pbody.status === 404 ) ) {
  2205. console.log( '- ' + presponse.statusCode + ': Error while getting the Discord tag: ' + ( pbody && ( pbody.error && pbody.error.info || pbody.errormsg || pbody.title ) ) );
  2206. embed.setColor('#000000').setDescription( lang.verify.error );
  2207. msg.replyMsg( lang.verify.error_reply, {embed}, false, false ).then( message => message.reactEmoji('error') );
  2208. if ( reaction ) reaction.removeEmoji();
  2209. return;
  2210. }
  2211. }
  2212. var discordname = '';
  2213. if ( pbody.profile ) discordname = pbody.profile['link-discord'].escapeFormatting().replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2214. else if ( pbody.value ) discordname = htmlToPlain( pbody.value ).replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2215. if ( discordname.length > 50 ) discordname = discordname.substring(0, 50) + '\u2026';
  2216. embed.addField( lang.verify.discord, msg.author.tag.escapeFormatting(), true ).addField( lang.verify.wiki, ( discordname || lang.verify.empty ), true );
  2217. if ( msg.author.tag.escapeFormatting() !== discordname ) {
  2218. embed.setColor('#FFFF00').setDescription( lang.verify.user_failed.replaceSave( '%1$s', msg.member.toString() ).replaceSave( '%2$s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ) );
  2219. var help_link = '';
  2220. if ( wiki.endsWith( '.gamepedia.com/' ) ) help_link = lang.verify.help_gamepedia;
  2221. else if ( wiki.isFandom() ) help_link = lang.verify.help_fandom + '/' + username.toTitle(true) + '?c=' + ( msg.guild.id in patreons && patreons[msg.guild.id] !== process.env.prefix ? encodeURIComponent( patreons[msg.guild.id] + ' verify' ) : 'wb' ) + ( msg.channel.name !== 'verification' ? '&ch=' + encodeURIComponent( msg.channel.name ) : '' ) + '&user=' + encodeURIComponent( msg.author.username ) + '&tag=' + msg.author.discriminator;
  2222. if ( help_link.length ) embed.addField( lang.verify.notice, lang.verify.help_guide.replaceSave( '%s', help_link ) + '\n' + help_link );
  2223. msg.replyMsg( lang.verify.user_failed_reply.replaceSave( '%s', username.escapeFormatting() ), {embed}, false, false );
  2224. if ( reaction ) reaction.removeEmoji();
  2225. return;
  2226. }
  2227. var roles = [];
  2228. var missing = [];
  2229. var verified = false;
  2230. var rename = false;
  2231. var accountage = ( Date.now() - new Date(queryuser.registration) ) / 86400000;
  2232. rows.forEach( row => {
  2233. var and_or = 'some';
  2234. if ( row.usergroup.startsWith( 'AND|' ) ) {
  2235. row.usergroup = row.usergroup.replace( 'AND|', '' );
  2236. and_or = 'every';
  2237. }
  2238. if ( queryuser.editcount >= row.editcount && row.usergroup.split('|')[and_or]( usergroup => {
  2239. if ( !queryuser.groupmemberships ) return queryuser.groups.includes( usergroup );
  2240. if ( !queryuser.groups.includes( 'global_' + usergroup ) || queryuser.groupmemberships.some( member => member.group === usergroup ) ) {
  2241. return queryuser.groups.includes( usergroup );
  2242. }
  2243. return false;
  2244. } ) && accountage >= row.accountage && row.role.split('|').some( role => !roles.includes( role ) ) ) {
  2245. verified = true;
  2246. if ( row.rename ) rename = true;
  2247. row.role.split('|').forEach( role => {
  2248. if ( !roles.includes( role ) ) {
  2249. if ( msg.guild.roles.cache.has(role) && msg.guild.me.roles.highest.comparePositionTo(role) > 0 ) roles.push(role);
  2250. else if ( !missing.includes( role ) ) missing.push(role);
  2251. }
  2252. } );
  2253. }
  2254. } );
  2255. if ( verified ) {
  2256. embed.setColor('#00FF00').setDescription( lang.verify.user_verified.replaceSave( '%1$s', msg.member.toString() ).replaceSave( '%2$s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ) + ( rename ? '\n' + lang.verify.user_renamed : '' ) );
  2257. var text = lang.verify.user_verified_reply.replaceSave( '%s', username.escapeFormatting() );
  2258. var verify_promise = [
  2259. msg.member.roles.add( roles, lang.verify.audit_reason.replaceSave( '%s', username ) ).catch( error => {
  2260. embed.setColor('#008800');
  2261. comment.push(lang.verify.failed_roles);
  2262. } )
  2263. ];
  2264. if ( rename ) {
  2265. verify_promise.push(msg.member.setNickname( username.substring(0, 32), lang.verify.audit_reason.replaceSave( '%s', username ) ).catch( error => {
  2266. embed.setColor('#008800');
  2267. comment.push(lang.verify.failed_rename);
  2268. } ));
  2269. }
  2270. return Promise.all(verify_promise).finally( () => {
  2271. if ( msg.showEmbed() ) {
  2272. if ( roles.length ) embed.addField( lang.verify.qualified, roles.map( role => '<@&' + role + '>' ).join('\n') );
  2273. if ( missing.length ) embed.setColor('#008800').addField( lang.verify.qualified_error, missing.map( role => '<@&' + role + '>' ).join('\n') );
  2274. if ( comment.length ) embed.setColor('#008800').addField( lang.verify.notice, comment.join('\n') );
  2275. }
  2276. else {
  2277. if ( roles.length ) text += '\n\n' + lang.verify.qualified + ' ' + roles.map( role => '<@&' + role + '>' ).join(', ');
  2278. if ( missing.length ) text += '\n\n' + lang.verify.qualified_error + ' ' + missing.map( role => '<@&' + role + '>' ).join(', ');
  2279. if ( comment.length ) text += '\n\n' + comment.join('\n');
  2280. }
  2281. msg.replyMsg( text, {embed,split:true}, false, false );
  2282. if ( reaction ) reaction.removeEmoji();
  2283. } );
  2284. }
  2285. embed.setColor('#FFFF00').setDescription( lang.verify.user_matches.replaceSave( '%1$s', msg.member.toString() ).replaceSave( '%2$s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ) );
  2286. msg.replyMsg( lang.verify.user_matches_reply.replaceSave( '%s', username.escapeFormatting() ), {embed}, false, false );
  2287. if ( reaction ) reaction.removeEmoji();
  2288. }, error => {
  2289. console.log( '- Error while getting the Discord tag: ' + error );
  2290. embed.setColor('#000000').setDescription( lang.verify.error );
  2291. msg.replyMsg( lang.verify.error_reply, {embed}, false, false ).then( message => message.reactEmoji('error') );
  2292. if ( reaction ) reaction.removeEmoji();
  2293. } );
  2294. }, error => {
  2295. embed.setColor('#FF0000').setDescription( error.desc );
  2296. msg.replyMsg( error.reply, {embed}, false, false );
  2297. if ( reaction ) reaction.removeEmoji();
  2298. } );
  2299. got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=content|user&rvslots=main&titles=User:' + encodeURIComponent( username ) + '/Discord&format=json', {
  2300. responseType: 'json'
  2301. } ).then( mwresponse => {
  2302. var mwbody = mwresponse.body;
  2303. if ( mwbody && mwbody.warnings ) log_warn(mwbody.warnings);
  2304. if ( mwresponse.statusCode !== 200 || !mwbody || mwbody.batchcomplete === undefined || !mwbody.query || !mwbody.query.pages ) {
  2305. console.log( '- ' + mwresponse.statusCode + ': Error while getting the Discord tag: ' + ( mwbody && mwbody.error && mwbody.error.info ) );
  2306. embed.setColor('#000000').setDescription( lang.verify.error );
  2307. msg.replyMsg( lang.verify.error_reply, {embed}, false, false ).then( message => message.reactEmoji('error') );
  2308. if ( reaction ) reaction.removeEmoji();
  2309. return;
  2310. }
  2311. var revision = Object.values(mwbody.query.pages)[0]?.revisions?.[0];
  2312. var discordname = '';
  2313. if ( revision && revision.user === username ) discordname = revision.slots.main['*'].escapeFormatting().replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2314. if ( discordname.length > 50 ) discordname = discordname.substring(0, 50) + '\u2026';
  2315. embed.addField( lang.verify.discord, msg.author.tag.escapeFormatting(), true ).addField( lang.verify.wiki, ( discordname || lang.verify.empty ), true );
  2316. if ( msg.author.tag.escapeFormatting() !== discordname ) {
  2317. embed.setColor('#FFFF00').setDescription( lang.verify.user_failed.replaceSave( '%1$s', msg.member.toString() ).replaceSave( '%2$s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ) );
  2318. embed.addField( lang.verify.notice, lang.verify.help_subpage.replaceSave( '%s', '**`' + msg.author.tag + '`**' ) + '\n' + wiki.toLink('Special:MyPage/Discord', 'action=edit', '', body.query.general) );
  2319. msg.replyMsg( lang.verify.user_failed_reply.replaceSave( '%s', username.escapeFormatting() ), {embed}, false, false );
  2320. if ( reaction ) reaction.removeEmoji();
  2321. return;
  2322. }
  2323. var roles = [];
  2324. var missing = [];
  2325. var verified = false;
  2326. var rename = false;
  2327. var accountage = ( Date.now() - new Date(queryuser.registration) ) / 86400000;
  2328. rows.forEach( row => {
  2329. var and_or = 'some';
  2330. if ( row.usergroup.startsWith( 'AND|' ) ) {
  2331. row.usergroup = row.usergroup.replace( 'AND|', '' );
  2332. and_or = 'every';
  2333. }
  2334. if ( queryuser.editcount >= row.editcount && row.usergroup.split('|')[and_or]( usergroup => {
  2335. if ( !queryuser.groupmemberships ) return queryuser.groups.includes( usergroup );
  2336. if ( !queryuser.groups.includes( 'global_' + usergroup ) || queryuser.groupmemberships.some( member => member.group === usergroup ) ) {
  2337. return queryuser.groups.includes( usergroup );
  2338. }
  2339. return false;
  2340. } ) && accountage >= row.accountage && row.role.split('|').some( role => !roles.includes( role ) ) ) {
  2341. verified = true;
  2342. if ( row.rename ) rename = true;
  2343. row.role.split('|').forEach( role => {
  2344. if ( !roles.includes( role ) ) {
  2345. if ( msg.guild.roles.cache.has(role) && msg.guild.me.roles.highest.comparePositionTo(role) > 0 ) roles.push(role);
  2346. else if ( !missing.includes( role ) ) missing.push(role);
  2347. }
  2348. } );
  2349. }
  2350. } );
  2351. if ( verified ) {
  2352. embed.setColor('#00FF00').setDescription( lang.verify.user_verified.replaceSave( '%1$s', msg.member.toString() ).replaceSave( '%2$s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ) + ( rename ? '\n' + lang.verify.user_renamed : '' ) );
  2353. var text = lang.verify.user_verified_reply.replaceSave( '%s', username.escapeFormatting() );
  2354. var verify_promise = [
  2355. msg.member.roles.add( roles, lang.verify.audit_reason.replaceSave( '%s', username ) ).catch( error => {
  2356. embed.setColor('#008800');
  2357. comment.push(lang.verify.failed_roles);
  2358. } )
  2359. ];
  2360. if ( rename ) {
  2361. verify_promise.push(msg.member.setNickname( username.substring(0, 32), lang.verify.audit_reason.replaceSave( '%s', username ) ).catch( error => {
  2362. embed.setColor('#008800');
  2363. comment.push(lang.verify.failed_rename);
  2364. } ));
  2365. }
  2366. return Promise.all(verify_promise).finally( () => {
  2367. if ( msg.showEmbed() ) {
  2368. if ( roles.length ) embed.addField( lang.verify.qualified, roles.map( role => '<@&' + role + '>' ).join('\n') );
  2369. if ( missing.length ) embed.setColor('#008800').addField( lang.verify.qualified_error, missing.map( role => '<@&' + role + '>' ).join('\n') );
  2370. if ( comment.length ) embed.setColor('#008800').addField( lang.verify.notice, comment.join('\n') );
  2371. }
  2372. else {
  2373. if ( roles.length ) text += '\n\n' + lang.verify.qualified + ' ' + roles.map( role => '<@&' + role + '>' ).join(', ');
  2374. if ( missing.length ) text += '\n\n' + lang.verify.qualified_error + ' ' + missing.map( role => '<@&' + role + '>' ).join(', ');
  2375. if ( comment.length ) text += '\n\n' + comment.join('\n');
  2376. }
  2377. msg.replyMsg( text, {embed,split:true}, false, false );
  2378. if ( reaction ) reaction.removeEmoji();
  2379. } );
  2380. }
  2381. embed.setColor('#FFFF00').setDescription( lang.verify.user_matches.replaceSave( '%1$s', msg.member.toString() ).replaceSave( '%2$s', '[' + username.escapeFormatting() + '](' + pagelink + ')' ) );
  2382. msg.replyMsg( lang.verify.user_matches_reply.replaceSave( '%s', username.escapeFormatting() ), {embed}, false, false );
  2383. if ( reaction ) reaction.removeEmoji();
  2384. }, error => {
  2385. console.log( '- Error while getting the Discord tag: ' + error );
  2386. embed.setColor('#000000').setDescription( lang.verify.error );
  2387. msg.replyMsg( lang.verify.error_reply, {embed}, false, false ).then( message => message.reactEmoji('error') );
  2388. if ( reaction ) reaction.removeEmoji();
  2389. } );
  2390. }, error => {
  2391. console.log( '- Error while getting the user: ' + error );
  2392. embed.setColor('#000000').setDescription( lang.verify.error );
  2393. msg.replyMsg( lang.verify.error_reply, {embed}, false, false ).then( message => message.reactEmoji('error') );
  2394. if ( reaction ) reaction.removeEmoji();
  2395. } ) );
  2396. } );
  2397. }
  2398. function gamepedia_user(lang, msg, namespace, username, wiki, querystring, fragment, querypage, contribs, reaction, spoiler) {
  2399. if ( /^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2400. got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=blocks&bkprop=user|by|timestamp|expiry|reason&bkip=' + encodeURIComponent( username ) + '&format=json', {
  2401. responseType: 'json'
  2402. } ).then( response => {
  2403. var body = response.body;
  2404. if ( body && body.warnings ) log_warn(body.warnings);
  2405. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.blocks ) {
  2406. if ( body && body.error && ( body.error.code === 'param_ip' || body.error.code === 'cidrtoobroad' ) ) {
  2407. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('error');
  2408. else {
  2409. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment);
  2410. var embed = new Discord.MessageEmbed().setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2411. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  2412. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  2413. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  2414. embed.setTitle( displaytitle );
  2415. }
  2416. if ( querypage.pageprops && querypage.pageprops.description ) {
  2417. var description = htmlToPlain( querypage.pageprops.description );
  2418. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2419. embed.setDescription( description );
  2420. }
  2421. else if ( querypage.extract ) {
  2422. var extract = querypage.extract.escapeFormatting();
  2423. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  2424. embed.setDescription( extract );
  2425. }
  2426. if ( querypage.pageimage && querypage.original ) {
  2427. var pageimage = querypage.original.source;
  2428. embed.setThumbnail( pageimage );
  2429. }
  2430. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2431. }
  2432. }
  2433. else {
  2434. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2435. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2436. }
  2437. if ( reaction ) reaction.removeEmoji();
  2438. }
  2439. else {
  2440. if ( !querypage.noRedirect || ( querypage.missing === undefined && querypage.ns !== -1 ) ) namespace = contribs;
  2441. var blocks = body.query.blocks.map( block => {
  2442. var isBlocked = false;
  2443. var blockedtimestamp = new Date(block.timestamp).toLocaleString(lang.dateformat, timeoptions);
  2444. var blockexpiry = block.expiry;
  2445. if ( blockexpiry === 'infinity' ) {
  2446. blockexpiry = lang.user.block.until_infinity;
  2447. isBlocked = true;
  2448. } else if ( blockexpiry ) {
  2449. if ( Date.parse(blockexpiry) > Date.now() ) isBlocked = true;
  2450. blockexpiry = new Date(blockexpiry).toLocaleString(lang.dateformat, timeoptions);
  2451. }
  2452. if ( isBlocked ) return {
  2453. header: lang.user.block.header.replaceSave( '%s', block.user ).escapeFormatting(),
  2454. text: lang.user.block[( block.reason ? 'text' : 'noreason' )].replaceSave( '%1$s', blockedtimestamp ).replaceSave( '%2$s', blockexpiry ),
  2455. by: block.by,
  2456. reason: block.reason
  2457. };
  2458. } ).filter( block => block !== undefined );
  2459. if ( username.includes( '/' ) ) {
  2460. var rangeprefix = username;
  2461. if ( username.includes( ':' ) ) {
  2462. var range = parseInt(username.replace( /^.+\/(\d{2,3})$/, '$1' ), 10);
  2463. if ( range === 128 ) username = username.replace( /^(.+)\/\d{2,3}$/, '$1' );
  2464. else if ( range >= 112 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){7}).+$/, '$1' );
  2465. else if ( range >= 96 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){6}).+$/, '$1' );
  2466. else if ( range >= 80 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){5}).+$/, '$1' );
  2467. else if ( range >= 64 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){4}).+$/, '$1' );
  2468. else if ( range >= 48 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){3}).+$/, '$1' );
  2469. else if ( range >= 32 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){2}).+$/, '$1' );
  2470. else if ( range >= 19 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){1}).+$/, '$1' );
  2471. }
  2472. else {
  2473. var range = parseInt(username.substring(username.length - 2), 10);
  2474. if ( range === 32 ) username = username.replace( /^(.+)\/\d{2}$/, '$1' );
  2475. else if ( range >= 24 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){3}).+$/, '$1' );
  2476. else if ( range >= 16 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){2}).+$/, '$1' );
  2477. }
  2478. }
  2479. got.get( wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=50' + ( username.includes( '/' ) ? '&ucuserprefix=' + encodeURIComponent( rangeprefix ) : '&ucuser=' + encodeURIComponent( username ) ) + '&format=json', {
  2480. responseType: 'json'
  2481. } ).then( ucresponse => {
  2482. var ucbody = ucresponse.body;
  2483. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2484. if ( ucbody && ucbody.warnings ) log_warn(ucbody.warnings);
  2485. if ( ucresponse.statusCode !== 200 || !ucbody || ucbody.batchcomplete === undefined || !ucbody.query || !ucbody.query.usercontribs ) {
  2486. if ( ucbody && ucbody.error && ucbody.error.code === 'baduser_ucuser' ) {
  2487. msg.reactEmoji('error');
  2488. }
  2489. else {
  2490. console.log( '- ' + ucresponse.statusCode + ': Error while getting the search results: ' + ( ucbody && ucbody.error && ucbody.error.info ) );
  2491. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2492. }
  2493. }
  2494. else {
  2495. var editcount = [lang.user.info.editcount, ( username.includes( '/' ) && ( ( username.includes( ':' ) && range % 16 ) || range % 8 ) ? '~' : '' ) + ucbody.query.usercontribs.length + ( ucbody.continue ? '+' : '' )];
  2496. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2497. if ( msg.showEmbed() ) {
  2498. var text = '<' + pagelink + '>';
  2499. 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) + ')' );
  2500. if ( blocks.length ) blocks.forEach( block => {
  2501. block.text = block.text.replaceSave( '%3$s', '[' + block.by.escapeFormatting() + '](' + wiki.toLink('User:' + block.by, '', '', body.query.general, true) + ')' );
  2502. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toMarkdown(wiki, body.query.general) );
  2503. embed.addField( block.header, block.text );
  2504. } );
  2505. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2506. }
  2507. else {
  2508. var embed = {};
  2509. var text = '<' + pagelink + '>\n\n' + editcount.join(' ');
  2510. if ( blocks.length ) blocks.forEach( block => {
  2511. block.text = block.text.replaceSave( '%3$s', block.by.escapeFormatting() );
  2512. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toPlaintext() );
  2513. text += '\n\n**' + block.header + '**\n' + block.text;
  2514. } );
  2515. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2516. }
  2517. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2518. }
  2519. }, error => {
  2520. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2521. console.log( '- Error while getting the search results: ' + error );
  2522. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2523. } ).finally( () => {
  2524. if ( reaction ) reaction.removeEmoji();
  2525. } );
  2526. }
  2527. }, error => {
  2528. console.log( '- Error while getting the search results: ' + error );
  2529. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2530. if ( reaction ) reaction.removeEmoji();
  2531. } );
  2532. } else {
  2533. 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', {
  2534. responseType: 'json'
  2535. } ).then( response => {
  2536. var body = response.body;
  2537. if ( body && body.warnings ) log_warn(body.warnings);
  2538. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.users || !body.query.users[0] ) {
  2539. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2540. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2541. if ( reaction ) reaction.removeEmoji();
  2542. }
  2543. else {
  2544. var queryuser = body.query.users[0];
  2545. if ( queryuser.missing !== undefined || queryuser.invalid !== undefined ) {
  2546. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('🤷');
  2547. else {
  2548. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  2549. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2550. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  2551. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  2552. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  2553. embed.setTitle( displaytitle );
  2554. }
  2555. if ( querypage.pageprops && querypage.pageprops.description ) {
  2556. var description = htmlToPlain( querypage.pageprops.description );
  2557. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2558. embed.setDescription( description );
  2559. }
  2560. else if ( querypage.extract ) {
  2561. var extract = querypage.extract.escapeFormatting();
  2562. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  2563. embed.setDescription( extract );
  2564. }
  2565. if ( querypage.pageimage && querypage.original ) {
  2566. var pageimage = querypage.original.source;
  2567. embed.setThumbnail( pageimage );
  2568. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  2569. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2570. }
  2571. if ( reaction ) reaction.removeEmoji();
  2572. }
  2573. else {
  2574. username = queryuser.name;
  2575. var gender = [lang.user.info.gender];
  2576. switch (queryuser.gender) {
  2577. case 'male':
  2578. gender.push(lang.user.gender.male);
  2579. break;
  2580. case 'female':
  2581. gender.push(lang.user.gender.female);
  2582. break;
  2583. default:
  2584. gender.push(lang.user.gender.unknown);
  2585. }
  2586. var registration = [lang.user.info.registration, new Date(queryuser.registration).toLocaleString(lang.dateformat, timeoptions)];
  2587. var editcount = [lang.user.info.editcount, queryuser.editcount];
  2588. var groups = queryuser.groups;
  2589. var group = [lang.user.info.group];
  2590. var grouplist = lang.user.groups;
  2591. for ( var i = 0; i < grouplist.length; i++ ) {
  2592. if ( groups.includes( grouplist[i][0] ) && ( group.length === 1 || !['autoconfirmed', 'user'].includes( grouplist[i][0] ) ) ) {
  2593. var thisSite = allSites.find( site => site.wiki_domain === body.query.general.servername );
  2594. if ( grouplist[i][0] === 'wiki_manager' && thisSite && thisSite.wiki_managers.includes( username ) ) {
  2595. group.push('**' + grouplist[i][1] + '**');
  2596. }
  2597. else if ( !groups.includes( 'global_' + grouplist[i][0] ) || queryuser.groupmemberships.some( member => member.group === grouplist[i][0] ) ) {
  2598. group.push(grouplist[i][1]);
  2599. }
  2600. }
  2601. }
  2602. var isBlocked = false;
  2603. var blockedtimestamp = new Date(queryuser.blockedtimestamp).toLocaleString(lang.dateformat, timeoptions);
  2604. var blockexpiry = queryuser.blockexpiry;
  2605. if ( blockexpiry === 'infinity' ) {
  2606. blockexpiry = lang.user.block.until_infinity;
  2607. isBlocked = true;
  2608. } else if ( blockexpiry ) {
  2609. var blockexpirydate = blockexpiry.replace( /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2,3})/, '$1-$2-$3T$4:$5:$6Z' );
  2610. blockexpiry = new Date(blockexpirydate).toLocaleString(lang.dateformat, timeoptions);
  2611. if ( Date.parse(blockexpirydate) > Date.now() ) isBlocked = true;
  2612. }
  2613. var blockedby = queryuser.blockedby;
  2614. var blockreason = queryuser.blockreason;
  2615. var block = {
  2616. header: lang.user.block.header.replaceSave( '%s', username ).escapeFormatting(),
  2617. text: lang.user.block[( blockreason ? 'text' : 'noreason' )].replaceSave( '%1$s', blockedtimestamp ).replaceSave( '%2$s', blockexpiry ),
  2618. by: blockedby,
  2619. reason: blockreason
  2620. };
  2621. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2622. if ( msg.showEmbed() ) {
  2623. var text = '<' + pagelink + '>';
  2624. 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 );
  2625. if ( querypage.pageprops && querypage.pageprops.description ) {
  2626. var description = htmlToPlain( querypage.pageprops.description );
  2627. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2628. embed.setDescription( description );
  2629. }
  2630. else if ( querypage.extract ) {
  2631. var extract = querypage.extract.escapeFormatting();
  2632. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  2633. embed.setDescription( extract );
  2634. }
  2635. }
  2636. else {
  2637. var embed = {};
  2638. var text = '<' + pagelink + '>\n\n' + gender.join(' ') + '\n' + registration.join(' ') + '\n' + editcount.join(' ') + '\n' + group[0] + ' ' + group.slice(1).join(', ');
  2639. }
  2640. if ( wiki.endsWith( '.gamepedia.com/' ) ) got.get( wiki + 'api.php?action=profile&do=getPublicProfile&user_name=' + encodeURIComponent( username ) + '&format=json&cache=' + Date.now(), {
  2641. responseType: 'json'
  2642. } ).then( presponse => {
  2643. var pbody = presponse.body;
  2644. if ( presponse.statusCode !== 200 || !pbody || pbody.error || pbody.errormsg || !pbody.profile ) {
  2645. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && ( pbody.error && pbody.error.info || pbody.errormsg ) ) );
  2646. }
  2647. else {
  2648. if ( pbody.profile['link-discord'] ) {
  2649. if ( pbody.profile['link-discord'].length > 50 ) pbody.profile['link-discord'] = pbody.profile['link-discord'].substring(0, 50) + '\u2026';
  2650. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  2651. return member.user.tag === pbody.profile['link-discord'].replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2652. } );
  2653. var discordname = [lang.user.info.discord,pbody.profile['link-discord'].escapeFormatting()];
  2654. if ( discordmember ) discordname[1] = discordmember.toString();
  2655. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  2656. else text += '\n' + discordname.join(' ');
  2657. }
  2658. if ( pbody.profile['favwiki'] ) {
  2659. var favwiki = [lang.user.info.favwiki,allSites.find( site => site.md5_key === pbody.profile['favwiki'] )];
  2660. if ( favwiki[1] ) {
  2661. if ( msg.showEmbed() ) embed.addField( favwiki[0], '[' + favwiki[1].wiki_display_name + '](<https://' + favwiki[1].wiki_domain + '/>)', true );
  2662. else text += '\n' + favwiki[0] + ' <https://' + favwiki[1].wiki_domain + '/>';
  2663. }
  2664. }
  2665. }
  2666. }, error => {
  2667. console.log( '- Error while getting the user profile: ' + error );
  2668. } ).finally( () => {
  2669. if ( msg.showEmbed() ) {
  2670. if ( isBlocked ) {
  2671. block.text = block.text.replaceSave( '%3$s', '[' + block.by.escapeFormatting() + '](' + wiki.toLink('User:' + block.by, '', '', body.query.general, true) + ')' );
  2672. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toMarkdown(wiki, body.query.general) );
  2673. embed.addField( block.header, block.text );
  2674. }
  2675. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2676. }
  2677. else {
  2678. if ( isBlocked ) {
  2679. block.text = block.text.replaceSave( '%3$s', block.by.escapeFormatting() );
  2680. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toPlaintext() );
  2681. text += '\n\n**' + block.header + '**\n' + block.text;
  2682. }
  2683. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2684. }
  2685. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2686. if ( reaction ) reaction.removeEmoji();
  2687. } );
  2688. else if ( wiki.isFandom() ) got.get( 'https://services.fandom.com/user-attribute/user/' + queryuser.userid + '?format=json&cache=' + Date.now(), {
  2689. headers: {
  2690. Accept: 'application/hal+json'
  2691. },
  2692. responseType: 'json'
  2693. } ).then( presponse => {
  2694. var pbody = presponse.body;
  2695. if ( presponse.statusCode !== 200 || !pbody || pbody.title || !pbody._embedded || !pbody._embedded.properties ) {
  2696. if ( !( pbody && pbody.status === 404 ) ) {
  2697. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && pbody.title ) );
  2698. }
  2699. }
  2700. else {
  2701. var profile = pbody._embedded.properties;
  2702. var discordfield = profile.find( field => field.name === 'discordHandle' );
  2703. var avatarfield = profile.find( field => field.name === 'avatar' );
  2704. var biofield = profile.find( field => field.name === 'bio' );
  2705. if ( discordfield && discordfield.value ) {
  2706. discordfield.value = htmlToPlain( discordfield.value ).replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2707. if ( discordfield.value.length > 50 ) discordfield.value = discordfield.value.substring(0, 50) + '\u2026';
  2708. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  2709. return member.user.tag.escapeFormatting() === discordfield.value;
  2710. } );
  2711. var discordname = [lang.user.info.discord,discordfield.value];
  2712. if ( discordmember ) discordname[1] = discordmember.toString();
  2713. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  2714. else text += '\n' + discordname.join(' ');
  2715. }
  2716. if ( msg.showEmbed() ) {
  2717. if ( avatarfield && avatarfield.value ) embed.setThumbnail( avatarfield.value );
  2718. if ( biofield && biofield.value && !embed.description ) {
  2719. var bio = biofield.value.escapeFormatting();
  2720. if ( bio.length > 2000 ) bio = bio.substring(0, 2000) + '\u2026';
  2721. embed.setDescription( bio );
  2722. }
  2723. }
  2724. }
  2725. }, error => {
  2726. console.log( '- Error while getting the user profile: ' + error );
  2727. } ).finally( () => {
  2728. if ( msg.showEmbed() ) {
  2729. if ( isBlocked ) {
  2730. block.text = block.text.replaceSave( '%3$s', '[' + block.by.escapeFormatting() + '](' + wiki.toLink('User:' + block.by, '', '', body.query.general, true) + ')' );
  2731. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toMarkdown(wiki, body.query.general) );
  2732. embed.addField( block.header, block.text );
  2733. }
  2734. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2735. }
  2736. else {
  2737. if ( isBlocked ) {
  2738. block.text = block.text.replaceSave( '%3$s', block.by.escapeFormatting() );
  2739. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toPlaintext() );
  2740. text += '\n\n**' + block.header + '**\n' + block.text;
  2741. }
  2742. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2743. }
  2744. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2745. if ( reaction ) reaction.removeEmoji();
  2746. } );
  2747. else {
  2748. if ( isBlocked ) {
  2749. if ( msg.showEmbed() ) {
  2750. block.text = block.text.replaceSave( '%3$s', '[' + block.by.escapeFormatting() + '](' + wiki.toLink('User:' + block.by, '', '', body.query.general, true) + ')' );
  2751. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toMarkdown(wiki, body.query.general) );
  2752. embed.addField( block.header, block.text );
  2753. }
  2754. else {
  2755. block.text = block.text.replaceSave( '%3$s', block.by.escapeFormatting() );
  2756. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toPlaintext() );
  2757. text += '\n\n**' + block.header + '**\n' + block.text;
  2758. }
  2759. }
  2760. msg.sendChannel( spoiler + text + spoiler, {embed} );
  2761. if ( reaction ) reaction.removeEmoji();
  2762. }
  2763. }
  2764. }
  2765. }, error => {
  2766. console.log( '- Error while getting the search results: ' + error );
  2767. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2768. if ( reaction ) reaction.removeEmoji();
  2769. } );
  2770. }
  2771. }
  2772. function fandom_user(lang, msg, namespace, username, wiki, querystring, fragment, querypage, contribs, reaction, spoiler) {
  2773. if ( /^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2774. got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=blocks&bkprop=user|by|timestamp|expiry|reason&bkip=' + encodeURIComponent( username ) + '&format=json', {
  2775. responseType: 'json'
  2776. } ).then( response => {
  2777. var body = response.body;
  2778. if ( body && body.warnings ) log_warn(body.warnings);
  2779. if ( response.statusCode !== 200 || !body || !body.query || !body.query.blocks ) {
  2780. if ( body && body.error && ( body.error.code === 'param_ip' || body.error.code === 'cidrtoobroad' ) ) {
  2781. if ( querypage.missing !== undefined || querypage.ns === -1 ) {
  2782. msg.reactEmoji('error');
  2783. if ( reaction ) reaction.removeEmoji();
  2784. }
  2785. else {
  2786. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment);
  2787. var embed = new Discord.MessageEmbed().setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2788. got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  2789. var descbody = descresponse.body;
  2790. if ( descresponse.statusCode !== 200 || !descbody ) {
  2791. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  2792. } else {
  2793. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png');
  2794. var parser = new htmlparser.Parser( {
  2795. onopentag: (tagname, attribs) => {
  2796. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2797. var description = attribs.content.escapeFormatting();
  2798. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2799. embed.setDescription( description );
  2800. }
  2801. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2802. thumbnail = attribs.content;
  2803. }
  2804. }
  2805. }, {decodeEntities:true} );
  2806. parser.write( descbody );
  2807. parser.end();
  2808. embed.setThumbnail( thumbnail );
  2809. }
  2810. }, error => {
  2811. console.log( '- Error while getting the description: ' + error );
  2812. } ).finally( () => {
  2813. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2814. if ( reaction ) reaction.removeEmoji();
  2815. } );
  2816. }
  2817. }
  2818. else {
  2819. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2820. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2821. if ( reaction ) reaction.removeEmoji();
  2822. }
  2823. }
  2824. else {
  2825. if ( !querypage.noRedirect || ( querypage.missing === undefined && querypage.ns !== -1 ) ) namespace = contribs;
  2826. var blocks = body.query.blocks.map( block => {
  2827. var isBlocked = false;
  2828. var blockedtimestamp = new Date(block.timestamp).toLocaleString(lang.dateformat, timeoptions);
  2829. var blockexpiry = block.expiry;
  2830. if ( blockexpiry === 'infinity' ) {
  2831. blockexpiry = lang.user.block.until_infinity;
  2832. isBlocked = true;
  2833. } else if ( blockexpiry ) {
  2834. if ( Date.parse(blockexpiry) > Date.now() ) isBlocked = true;
  2835. blockexpiry = new Date(blockexpiry).toLocaleString(lang.dateformat, timeoptions);
  2836. }
  2837. if ( isBlocked ) return {
  2838. header: lang.user.block.header.replaceSave( '%s', block.user ).escapeFormatting(),
  2839. text: lang.user.block[( block.reason ? 'text' : 'noreason' )].replaceSave( '%1$s', blockedtimestamp ).replaceSave( '%2$s', blockexpiry ),
  2840. by: block.by,
  2841. reason: block.reason
  2842. };
  2843. } ).filter( block => block !== undefined );
  2844. if ( username.includes( '/' ) ) {
  2845. var rangeprefix = username;
  2846. if ( username.includes( ':' ) ) {
  2847. var range = parseInt(username.replace( /^.+\/(\d{2,3})$/, '$1' ), 10);
  2848. if ( range === 128 ) username = username.replace( /^(.+)\/\d{2,3}$/, '$1' );
  2849. else if ( range >= 112 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){7}).+$/, '$1' );
  2850. else if ( range >= 96 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){6}).+$/, '$1' );
  2851. else if ( range >= 80 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){5}).+$/, '$1' );
  2852. else if ( range >= 64 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){4}).+$/, '$1' );
  2853. else if ( range >= 48 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){3}).+$/, '$1' );
  2854. else if ( range >= 32 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){2}).+$/, '$1' );
  2855. else if ( range >= 19 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){1}).+$/, '$1' );
  2856. }
  2857. else {
  2858. var range = parseInt(username.substring(username.length - 2), 10);
  2859. if ( range === 32 ) username = username.replace( /^(.+)\/\d{2}$/, '$1' );
  2860. else if ( range >= 24 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){3}).+$/, '$1' );
  2861. else if ( range >= 16 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){2}).+$/, '$1' );
  2862. }
  2863. }
  2864. got.get( wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=50&ucuser=' + encodeURIComponent( username ) + '&format=json', {
  2865. responseType: 'json'
  2866. } ).then( ucresponse => {
  2867. var ucbody = ucresponse.body;
  2868. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2869. if ( ucbody && ucbody.warnings ) log_warn(ucbody.warnings);
  2870. if ( ucresponse.statusCode !== 200 || !ucbody || !ucbody.query || !ucbody.query.usercontribs ) {
  2871. if ( ucbody && ucbody.error && ucbody.error.code === 'baduser_ucuser' ) {
  2872. msg.reactEmoji('error');
  2873. }
  2874. else {
  2875. console.log( '- ' + ucresponse.statusCode + ': Error while getting the search results: ' + ( ucbody && ucbody.error && ucbody.error.info ) );
  2876. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2877. }
  2878. }
  2879. else {
  2880. var editcount = [lang.user.info.editcount, ( username.includes( '/' ) ? '~' : '' ) + ucbody.query.usercontribs.length + ( ucbody.continue ? '+' : '' )];
  2881. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2882. if ( msg.showEmbed() ) {
  2883. var text = '<' + pagelink + '>';
  2884. 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) + ')' );
  2885. if ( blocks.length ) {
  2886. block.text = block.text.replaceSave( '%3$s', '[' + block.by.escapeFormatting() + '](' + wiki.toLink('User:' + block.by, '', '', body.query.general, true) + ')' );
  2887. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toMarkdown(wiki, body.query.general) );
  2888. embed.addField( block.header, block.text );
  2889. }
  2890. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2891. }
  2892. else {
  2893. var embed = {};
  2894. var text = '<' + pagelink + '>\n\n' + editcount.join(' ');
  2895. if ( blocks.length ) {
  2896. block.text = block.text.replaceSave( '%3$s', block.by.escapeFormatting() );
  2897. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toPlaintext() );
  2898. text += '\n\n**' + block.header + '**\n' + block.text;
  2899. }
  2900. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2901. }
  2902. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2903. }
  2904. }, error => {
  2905. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2906. console.log( '- Error while getting the search results: ' + error );
  2907. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2908. } ).finally( () => {
  2909. if ( reaction ) reaction.removeEmoji();
  2910. } );
  2911. }
  2912. }, error => {
  2913. console.log( '- Error while getting the search results: ' + error );
  2914. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2915. if ( reaction ) reaction.removeEmoji();
  2916. } );
  2917. } else {
  2918. 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', {
  2919. responseType: 'json'
  2920. } ).then( response => {
  2921. var body = response.body;
  2922. if ( body && body.warnings ) log_warn(body.warnings);
  2923. if ( response.statusCode !== 200 || !body || !body.query || !body.query.users ) {
  2924. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2925. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2926. if ( reaction ) reaction.removeEmoji();
  2927. }
  2928. else {
  2929. var queryuser = body.query.users[0];
  2930. if ( !queryuser ) {
  2931. if ( querypage.missing !== undefined || querypage.ns === -1 ) {
  2932. msg.reactEmoji('🤷');
  2933. if ( reaction ) reaction.removeEmoji();
  2934. }
  2935. else {
  2936. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  2937. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2938. got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  2939. var descbody = descresponse.body;
  2940. if ( descresponse.statusCode !== 200 || !descbody ) {
  2941. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  2942. } else {
  2943. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  2944. var parser = new htmlparser.Parser( {
  2945. onopentag: (tagname, attribs) => {
  2946. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2947. var description = attribs.content.escapeFormatting();
  2948. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2949. embed.setDescription( description );
  2950. }
  2951. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2952. thumbnail = attribs.content;
  2953. }
  2954. }
  2955. }, {decodeEntities:true} );
  2956. parser.write( descbody );
  2957. parser.end();
  2958. embed.setThumbnail( thumbnail );
  2959. }
  2960. }, error => {
  2961. console.log( '- Error while getting the description: ' + error );
  2962. } ).finally( () => {
  2963. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2964. if ( reaction ) reaction.removeEmoji();
  2965. } );
  2966. }
  2967. }
  2968. else {
  2969. username = queryuser.name;
  2970. var gender = [lang.user.info.gender];
  2971. switch (queryuser.gender) {
  2972. case 'male':
  2973. gender.push(lang.user.gender.male);
  2974. break;
  2975. case 'female':
  2976. gender.push(lang.user.gender.female);
  2977. break;
  2978. default:
  2979. gender.push(lang.user.gender.unknown);
  2980. }
  2981. var registration = [lang.user.info.registration, new Date(queryuser.registration).toLocaleString(lang.dateformat, timeoptions)];
  2982. var editcount = [lang.user.info.editcount, queryuser.editcount];
  2983. var groups = queryuser.groups;
  2984. var group = [lang.user.info.group];
  2985. var grouplist = lang.user.groups;
  2986. for ( var i = 0; i < grouplist.length; i++ ) {
  2987. if ( groups.includes( grouplist[i][0] ) && ( group.length === 1 || !['autoconfirmed', 'user'].includes( grouplist[i][0] ) ) ) {
  2988. if ( grouplist[i][0] === 'wiki-manager' && body.query.allmessages[0]['*'] === username ) {
  2989. group.push('**' + grouplist[i][1] + '**');
  2990. }
  2991. else group.push(grouplist[i][1]);
  2992. }
  2993. }
  2994. var isBlocked = false;
  2995. var blockexpiry = queryuser.blockexpiry;
  2996. if ( blockexpiry === 'infinity' ) {
  2997. blockexpiry = lang.user.block.until_infinity;
  2998. isBlocked = true;
  2999. } else if ( blockexpiry ) {
  3000. var blockexpirydate = blockexpiry.replace( /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2,3})/, '$1-$2-$3T$4:$5:$6Z' );
  3001. blockexpiry = new Date(blockexpirydate).toLocaleString(lang.dateformat, timeoptions);
  3002. if ( Date.parse(blockexpirydate) > Date.now() ) isBlocked = true;
  3003. }
  3004. var blockedby = '[[User:' + queryuser.blockedby + '|' + queryuser.blockedby + ']]';
  3005. var blockreason = queryuser.blockreason;
  3006. var block = {
  3007. header: lang.user.block.header.replaceSave( '%s', username ).escapeFormatting(),
  3008. text: lang.user.block['nofrom' + ( blockreason ? 'text' : 'noreason' )].replaceSave( '%2$s', blockexpiry ),
  3009. by: blockedby,
  3010. reason: blockreason
  3011. };
  3012. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  3013. if ( msg.showEmbed() ) {
  3014. var text = '<' + pagelink + '>';
  3015. 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 );
  3016. }
  3017. else {
  3018. var embed = {};
  3019. var text = '<' + pagelink + '>\n\n' + gender.join(' ') + '\n' + registration.join(' ') + '\n' + editcount.join(' ') + '\n' + group[0] + ' ' + group.slice(1).join(', ');
  3020. }
  3021. got.get( 'https://services.fandom.com/user-attribute/user/' + queryuser.userid + '?format=json&cache=' + Date.now(), {
  3022. headers: {
  3023. Accept: 'application/hal+json'
  3024. },
  3025. responseType: 'json'
  3026. } ).then( presponse => {
  3027. var pbody = presponse.body;
  3028. if ( presponse.statusCode !== 200 || !pbody || pbody.title || !pbody._embedded || !pbody._embedded.properties ) {
  3029. if ( !( pbody && pbody.status === 404 ) ) {
  3030. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && pbody.title ) );
  3031. }
  3032. }
  3033. else {
  3034. var profile = pbody._embedded.properties;
  3035. var discordfield = profile.find( field => field.name === 'discordHandle' );
  3036. var avatarfield = profile.find( field => field.name === 'avatar' );
  3037. var biofield = profile.find( field => field.name === 'bio' );
  3038. if ( discordfield && discordfield.value ) {
  3039. discordfield.value = htmlToPlain( discordfield.value ).replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  3040. if ( discordfield.value.length > 50 ) discordfield.value = discordfield.value.substring(0, 50) + '\u2026';
  3041. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  3042. return member.user.tag.escapeFormatting() === discordfield.value;
  3043. } );
  3044. var discordname = [lang.user.info.discord,discordfield.value];
  3045. if ( discordmember ) discordname[1] = discordmember.toString();
  3046. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  3047. else text += '\n' + discordname.join(' ');
  3048. }
  3049. if ( msg.showEmbed() ) {
  3050. if ( avatarfield && avatarfield.value ) embed.setThumbnail( avatarfield.value );
  3051. if ( biofield && biofield.value && !embed.description ) {
  3052. var bio = biofield.value.escapeFormatting();
  3053. if ( bio.length > 2000 ) bio = bio.substring(0, 2000) + '\u2026';
  3054. embed.setDescription( bio );
  3055. }
  3056. }
  3057. }
  3058. }, error => {
  3059. console.log( '- Error while getting the user profile: ' + error );
  3060. } ).finally( () => {
  3061. if ( msg.showEmbed() ) {
  3062. if ( isBlocked ) {
  3063. block.text = block.text.replaceSave( '%3$s', '[' + block.by.escapeFormatting() + '](' + wiki.toLink('User:' + block.by, '', '', body.query.general, true) + ')' );
  3064. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toMarkdown(wiki, body.query.general) );
  3065. embed.addField( block.header, block.text );
  3066. }
  3067. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  3068. }
  3069. else {
  3070. if ( isBlocked ) {
  3071. block.text = block.text.replaceSave( '%3$s', block.by.escapeFormatting() );
  3072. if ( block.reason ) block.text = block.text.replaceSave( '%4$s', block.reason.toPlaintext() );
  3073. text += '\n\n**' + block.header + '**\n' + block.text;
  3074. }
  3075. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  3076. }
  3077. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  3078. if ( reaction ) reaction.removeEmoji();
  3079. } );
  3080. }
  3081. }
  3082. }, error => {
  3083. console.log( '- Error while getting the search results: ' + error );
  3084. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  3085. if ( reaction ) reaction.removeEmoji();
  3086. } );
  3087. }
  3088. }
  3089. function global_block(lang, msg, username, text, embed, wiki, spoiler) {
  3090. if ( !msg || msg.channel.type !== 'text' || !( msg.guild.id in patreons ) ) return;
  3091. if ( msg.showEmbed() ) embed.fields.pop();
  3092. else {
  3093. let splittext = text.split('\n\n');
  3094. splittext.pop();
  3095. text = splittext.join('\n\n');
  3096. }
  3097. if ( wiki.isFandom() ) got.get( 'https://community.fandom.com/Special:Contributions/' + encodeURIComponent( username ) + '?limit=1' ).then( response => {
  3098. var body = response.body;
  3099. if ( response.statusCode !== 200 || !body ) {
  3100. console.log( '- ' + response.statusCode + ': Error while getting the global block.' );
  3101. }
  3102. else {
  3103. let $ = cheerio.load(body);
  3104. if ( $('#mw-content-text .errorbox').length ) {
  3105. if ( msg.showEmbed() ) embed.addField( lang.user.gblock.disabled, '\u200b' );
  3106. else text += '\n\n**' + lang.user.gblock.disabled + '**';
  3107. }
  3108. else if ( $('.mw-warning-with-logexcerpt').length && !$(".mw-warning-with-logexcerpt .mw-logline-block").length ) {
  3109. if ( msg.showEmbed() ) embed.addField( lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting(), '\u200b' );
  3110. else text += '\n\n**' + lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting() + '**';
  3111. }
  3112. }
  3113. }, error => {
  3114. console.log( '- Error while getting the global block: ' + error );
  3115. } ).finally( () => {
  3116. if ( !/^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  3117. got.get( 'https://community.fandom.com/wiki/Special:Editcount/' + encodeURIComponent( username ) ).then( gresponse => {
  3118. var gbody = gresponse.body;
  3119. if ( gresponse.statusCode !== 200 || !gbody ) {
  3120. console.log( '- ' + gresponse.statusCode + ': Error while getting the global edit count.' );
  3121. }
  3122. else {
  3123. let $ = cheerio.load(gbody);
  3124. var globaledits = $('#editcount .TablePager th').eq(7).text().replace( /[,\.]/g, '' );
  3125. if ( globaledits ) {
  3126. 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});
  3127. else {
  3128. let splittext = text.split('\n');
  3129. splittext.splice(5, 0, lang.user.info.globaleditcount + ' ' + globaledits);
  3130. text = splittext.join('\n');
  3131. }
  3132. }
  3133. }
  3134. }, error => {
  3135. console.log( '- Error while getting the global edit count: ' + error );
  3136. } ).finally( () => {
  3137. msg.edit( spoiler + text + spoiler, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  3138. } );
  3139. }
  3140. else msg.edit( spoiler + text + spoiler, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  3141. } );
  3142. else if ( wiki.endsWith( '.gamepedia.com/' ) ) got.get( 'https://help.gamepedia.com/Special:GlobalBlockList/' + encodeURIComponent( username ) + '?uselang=qqx' ).then( response => {
  3143. var body = response.body;
  3144. if ( response.statusCode !== 200 || !body ) {
  3145. console.log( '- ' + response.statusCode + ': Error while getting the global block.' );
  3146. }
  3147. else {
  3148. let $ = cheerio.load(body);
  3149. var gblock = $('.mw-blocklist');
  3150. if ( gblock.length ) {
  3151. var reason = gblock.find('.TablePager_col_reason').text().replace( /\)$/, '' ).split(', ');
  3152. 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);
  3153. var expiry = gblock.find('.TablePager_col_expiry').text();
  3154. if ( expiry.startsWith( '(infiniteblock)' ) ) expiry = lang.user.block.until_infinity;
  3155. 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);
  3156. if ( msg.showEmbed() ) {
  3157. var gblocktitle = lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting();
  3158. 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].escapeFormatting() ).replaceSave( '%4$s', reason.slice(4).join(', ').escapeFormatting() ) );
  3159. if ( globalblock ) globalblock.name = gblocktitle;
  3160. else {
  3161. var block_wiki = reason[3].replace( /Special:BlockList$/, '' );
  3162. var gblocktext = lang.user.gblock[( reason.length > 4 ? 'text' : 'noreason' )].replaceSave( '%1$s', timestamp ).replaceSave( '%2$s', expiry ).replaceSave( '%3$s', '[' + reason[1] + '](' + block_wiki + 'User:' + reason[1].toTitle(true) + ')' ).replaceSave( '%4$s', '[' + reason[2] + '](' + block_wiki + 'Special:Contribs/' + username.toTitle(true) + ')' ).replaceSave( '%5$s', reason.slice(4).join(', ').escapeFormatting() );
  3163. embed.addField( gblocktitle, gblocktext );
  3164. }
  3165. }
  3166. else {
  3167. let splittext = text.split('\n\n');
  3168. 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].escapeFormatting() ).replaceSave( '%4$s', reason.slice(4).join(', ').escapeFormatting() ));
  3169. 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].escapeFormatting() ).replaceSave( '%4$s', reason.slice(4).join(', ').escapeFormatting() );
  3170. 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].escapeFormatting() ).replaceSave( '%4$s', reason[2] ).replaceSave( '%5$s', reason.slice(4).join(', ').escapeFormatting() ));
  3171. text = splittext.join('\n\n');
  3172. }
  3173. }
  3174. }
  3175. }, error => {
  3176. console.log( '- Error while getting the global block: ' + error );
  3177. } ).finally( () => {
  3178. if ( !/^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  3179. got.get( 'https://help.gamepedia.com/UserProfile:' + encodeURIComponent( username ) ).then( gresponse => {
  3180. var gbody = gresponse.body;
  3181. if ( gresponse.statusCode !== 200 || !gbody ) {
  3182. console.log( '- ' + gresponse.statusCode + ': Error while getting the global edit count.' );
  3183. }
  3184. else {
  3185. let $ = cheerio.load(gbody);
  3186. var wikisedited = $('.curseprofile .rightcolumn .section.stats dd').eq(0).text().replace( /[,\.]/g, '' );
  3187. if ( wikisedited ) {
  3188. if ( msg.showEmbed() ) embed.spliceFields(1, 0, {name:lang.user.info.wikisedited,value:wikisedited,inline:true});
  3189. else {
  3190. let splittext = text.split('\n');
  3191. splittext.splice(5, 0, lang.user.info.wikisedited + ' ' + wikisedited);
  3192. text = splittext.join('\n');
  3193. }
  3194. }
  3195. var globaledits = $('.curseprofile .rightcolumn .section.stats dd').eq(2).text().replace( /[,\.]/g, '' );
  3196. if ( globaledits ) {
  3197. 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});
  3198. else {
  3199. let splittext = text.split('\n');
  3200. splittext.splice(5, 0, lang.user.info.globaleditcount + ' ' + globaledits);
  3201. text = splittext.join('\n');
  3202. }
  3203. }
  3204. }
  3205. }, error => {
  3206. console.log( '- Error while getting the global edit count: ' + error );
  3207. } ).finally( () => {
  3208. msg.edit( spoiler + text + spoiler, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  3209. } );
  3210. }
  3211. else msg.edit( spoiler + text + spoiler, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  3212. } );
  3213. }
  3214. function fandom_discussion(lang, msg, wiki, title, query, reaction, spoiler) {
  3215. if ( !title ) {
  3216. var pagelink = wiki + 'f';
  3217. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename ).setTitle( lang.discussion.main ).setURL( pagelink );
  3218. got.get( wiki + 'f' ).then( descresponse => {
  3219. var descbody = descresponse.body;
  3220. if ( descresponse.statusCode !== 200 || !descbody ) {
  3221. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  3222. } else {
  3223. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', query.general);
  3224. var parser = new htmlparser.Parser( {
  3225. onopentag: (tagname, attribs) => {
  3226. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  3227. var description = attribs.content.escapeFormatting();
  3228. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  3229. embed.setDescription( description );
  3230. }
  3231. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  3232. thumbnail = attribs.content;
  3233. }
  3234. }
  3235. }, {decodeEntities:true} );
  3236. parser.write( descbody );
  3237. parser.end();
  3238. embed.setThumbnail( thumbnail );
  3239. }
  3240. }, error => {
  3241. console.log( '- Error while getting the description: ' + error );
  3242. } ).finally( () => {
  3243. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  3244. if ( reaction ) reaction.removeEmoji();
  3245. } );
  3246. }
  3247. else if ( !query.wikidesc ) {
  3248. return got.get( 'https://community.fandom.com/api/v1/Wikis/ByString?includeDomain=true&limit=10&string=' + query.general.servername + query.general.scriptpath + '&format=json', {
  3249. responseType: 'json'
  3250. } ).then( wvresponse => {
  3251. var wvbody = wvresponse.body;
  3252. if ( wvresponse.statusCode !== 200 || !wvbody || wvbody.exception || !wvbody.items || !wvbody.items.length ) {
  3253. console.log( '- ' + wvresponse.statusCode + ': Error while getting the wiki id: ' + ( wvbody && wvbody.exception && wvbody.exception.details ) );
  3254. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3255. if ( reaction ) reaction.removeEmoji();
  3256. }
  3257. else if ( wvbody.items.some( site => site.domain === query.general.servername + query.general.scriptpath ) ) {
  3258. query.wikidesc = {id: wvbody.items.find( site => site.domain === query.general.servername + query.general.scriptpath ).id};
  3259. fandom_discussion(lang, msg, wiki, title, query, reaction, spoiler);
  3260. }
  3261. else {
  3262. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3263. if ( reaction ) reaction.removeEmoji();
  3264. }
  3265. }, error => {
  3266. console.log( '- Error while getting the wiki id: ' + error );
  3267. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3268. if ( reaction ) reaction.removeEmoji();
  3269. } );
  3270. }
  3271. else if ( title.split(' ')[0].toLowerCase() === 'post' || title.split(' ')[0].toLowerCase() === lang.discussion.post ) {
  3272. title = title.split(' ').slice(1).join(' ');
  3273. var limit = ( msg.channel.type === 'text' && msg.guild.id in patreons ? '100' : '50' );
  3274. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/posts?limit=' + limit + '&format=json', {
  3275. headers: {
  3276. Accept: 'application/hal+json'
  3277. },
  3278. responseType: 'json'
  3279. } ).then( response => {
  3280. var body = response.body;
  3281. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded['doc:posts'] ) {
  3282. console.log( '- ' + response.statusCode + ': Error while getting the posts: ' + ( body && body.title ) );
  3283. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3284. if ( reaction ) reaction.removeEmoji();
  3285. }
  3286. else if ( body._embedded['doc:posts'].length ) {
  3287. var posts = body._embedded['doc:posts'];
  3288. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename );
  3289. if ( posts.some( post => post.id === title ) ) {
  3290. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.id === title ), embed, spoiler);
  3291. if ( reaction ) reaction.removeEmoji();
  3292. }
  3293. else if ( /^\d+$/.test(title) ) {
  3294. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/posts/' + title + '?format=json', {
  3295. headers: {
  3296. Accept: 'application/hal+json'
  3297. },
  3298. responseType: 'json'
  3299. } ).then( presponse => {
  3300. var pbody = presponse.body;
  3301. if ( presponse.statusCode !== 200 || !pbody || pbody.id !== title ) {
  3302. if ( pbody && pbody.title === 'The requested resource was not found.' ) {
  3303. if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3304. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3305. }
  3306. else msg.reactEmoji('🤷');
  3307. }
  3308. else {
  3309. console.log( '- ' + presponse.statusCode + ': Error while getting the post: ' + ( pbody && pbody.title ) );
  3310. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3311. }
  3312. if ( reaction ) reaction.removeEmoji();
  3313. }
  3314. else if ( pbody.title ) {
  3315. fandom_discussionsend(lang, msg, wiki, pbody, embed, spoiler);
  3316. if ( reaction ) reaction.removeEmoji();
  3317. }
  3318. else got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads/' + pbody.threadId + '?format=json', {
  3319. headers: {
  3320. Accept: 'application/hal+json'
  3321. },
  3322. responseType: 'json'
  3323. } ).then( thresponse => {
  3324. var thbody = thresponse.body;
  3325. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== pbody.threadId ) {
  3326. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  3327. embed.setTitle( '~~' + pbody.threadId + '~~' );
  3328. }
  3329. else embed.setTitle( thbody.title.escapeFormatting() );
  3330. }, error => {
  3331. console.log( '- Error while getting the thread: ' + error );
  3332. embed.setTitle( '~~' + pbody.threadId + '~~' );
  3333. } ).finally( () => {
  3334. fandom_discussionsend(lang, msg, wiki, pbody, embed, spoiler);
  3335. if ( reaction ) reaction.removeEmoji();
  3336. } );
  3337. }, error => {
  3338. console.log( '- Error while getting the post: ' + error );
  3339. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3340. if ( reaction ) reaction.removeEmoji();
  3341. } );
  3342. }
  3343. else if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3344. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3345. if ( reaction ) reaction.removeEmoji();
  3346. }
  3347. else {
  3348. msg.reactEmoji('🤷');
  3349. if ( reaction ) reaction.removeEmoji();
  3350. }
  3351. }
  3352. else {
  3353. msg.reactEmoji('🤷');
  3354. if ( reaction ) reaction.removeEmoji();
  3355. }
  3356. }, error => {
  3357. console.log( '- Error while getting the posts: ' + error );
  3358. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3359. if ( reaction ) reaction.removeEmoji();
  3360. } );
  3361. }
  3362. else {
  3363. var limit = ( msg.channel.type === 'text' && msg.guild.id in patreons ? '100' : '50' );
  3364. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads?sortKey=trending&limit=' + limit + '&format=json', {
  3365. headers: {
  3366. Accept: 'application/hal+json'
  3367. },
  3368. responseType: 'json'
  3369. } ).then( response => {
  3370. var body = response.body;
  3371. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded.threads ) {
  3372. console.log( '- ' + response.statusCode + ': Error while getting the threads: ' + ( body && body.title ) );
  3373. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3374. if ( reaction ) reaction.removeEmoji();
  3375. }
  3376. else if ( body._embedded.threads.length ) {
  3377. var threads = body._embedded.threads;
  3378. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename );
  3379. if ( threads.some( thread => thread.id === title ) ) {
  3380. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.id === title ), embed, spoiler);
  3381. if ( reaction ) reaction.removeEmoji();
  3382. }
  3383. else if ( threads.some( thread => thread.title === title ) ) {
  3384. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title === title ), embed, spoiler);
  3385. if ( reaction ) reaction.removeEmoji();
  3386. }
  3387. else if ( threads.some( thread => thread.title.toLowerCase() === title.toLowerCase() ) ) {
  3388. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase() === title.toLowerCase() ), embed, spoiler);
  3389. if ( reaction ) reaction.removeEmoji();
  3390. }
  3391. else if ( threads.some( thread => thread.title.includes( title ) ) ) {
  3392. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.includes( title ) ), embed, spoiler);
  3393. if ( reaction ) reaction.removeEmoji();
  3394. }
  3395. else if ( threads.some( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3396. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3397. if ( reaction ) reaction.removeEmoji();
  3398. }
  3399. else if ( /^\d+$/.test(title) ) {
  3400. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads/' + title + '?format=json', {
  3401. headers: {
  3402. Accept: 'application/hal+json'
  3403. },
  3404. responseType: 'json'
  3405. } ).then( thresponse => {
  3406. var thbody = thresponse.body;
  3407. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== title ) {
  3408. if ( thbody && thbody.status === 404 ) {
  3409. if (threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3410. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3411. }
  3412. else msg.reactEmoji('🤷');
  3413. }
  3414. else {
  3415. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  3416. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  3417. }
  3418. }
  3419. else fandom_discussionsend(lang, msg, wiki, thbody, embed, spoiler);
  3420. }, error => {
  3421. console.log( '- Error while getting the thread: ' + error );
  3422. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  3423. } ).finally( () => {
  3424. if ( reaction ) reaction.removeEmoji();
  3425. } );
  3426. }
  3427. else if ( threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3428. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3429. if ( reaction ) reaction.removeEmoji();
  3430. }
  3431. else {
  3432. msg.reactEmoji('🤷');
  3433. if ( reaction ) reaction.removeEmoji();
  3434. }
  3435. }
  3436. else {
  3437. msg.reactEmoji('🤷');
  3438. if ( reaction ) reaction.removeEmoji();
  3439. }
  3440. }, error => {
  3441. console.log( '- Error while getting the threads: ' + error );
  3442. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3443. if ( reaction ) reaction.removeEmoji();
  3444. } );
  3445. }
  3446. }
  3447. function fandom_discussionsend(lang, msg, wiki, discussion, embed, spoiler) {
  3448. if ( discussion.title ) {
  3449. embed.setTitle( discussion.title.escapeFormatting() );
  3450. var pagelink = wiki + 'f/p/' + ( discussion.threadId || discussion.id );
  3451. }
  3452. else {
  3453. if ( discussion._embedded.thread ) embed.setTitle( discussion._embedded.thread[0].title.escapeFormatting() );
  3454. var pagelink = wiki + 'f/p/' + discussion.threadId + '/r/' + discussion.id;
  3455. }
  3456. var text = '<' + pagelink + '>';
  3457. embed.setURL( pagelink ).setFooter( discussion.createdBy.name, discussion.createdBy.avatarUrl ).setTimestamp( discussion.creationDate.epochSecond * 1000 );
  3458. var description = '';
  3459. switch ( discussion.funnel ) {
  3460. case 'IMAGE':
  3461. embed.setImage( discussion._embedded.contentImages[0].url );
  3462. break;
  3463. case 'POLL':
  3464. discussion.poll.answers.forEach( answer => embed.addField( answer.text.escapeFormatting(), ( answer.image ? '[__' + lang.discussion.image.escapeFormatting() + '__](' + answer.image.url + ')\n' : '' ) + ( 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 ) );
  3465. break;
  3466. case 'QUIZ':
  3467. description = discussion.quiz.title.escapeFormatting();
  3468. if ( discussion._embedded.openGraph ) embed.setThumbnail( discussion._embedded.openGraph[0].imageUrl );
  3469. break;
  3470. default:
  3471. if ( discussion.jsonModel ) {
  3472. try {
  3473. description = discussion_formatting(JSON.parse(discussion.jsonModel)).replace( /(?:\*\*\*\*|(?<!\\)\_\_)/g, '' ).replace( /{@wiki}/g, wiki );
  3474. if ( discussion._embedded.contentImages.length ) {
  3475. if ( description.trim().endsWith( '{@0}' ) ) {
  3476. embed.setImage( discussion._embedded.contentImages[0].url );
  3477. description = description.replace( '{@0}', '' ).trim();
  3478. }
  3479. else {
  3480. description = description.replace( /\{\@(\d+)\}/g, (match, n) => {
  3481. if ( n >= discussion._embedded.contentImages.length ) return '';
  3482. else return '[__' + lang.discussion.image.escapeFormatting() + '__](' + discussion._embedded.contentImages[n].url + ')';
  3483. } );
  3484. embed.setThumbnail( discussion._embedded.contentImages[0].url );
  3485. }
  3486. }
  3487. else embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  3488. }
  3489. catch ( jsonerror ) {
  3490. console.log( '- Error while getting the formatting: ' + jsonerror );
  3491. description = discussion.rawContent.escapeFormatting();
  3492. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  3493. }
  3494. }
  3495. else if ( discussion.renderedContent ) {
  3496. var current_tag = '';
  3497. var parser = new htmlparser.Parser( {
  3498. onopentag: (tagname, attribs) => {
  3499. if ( tagname === 'a' ) {
  3500. current_tag = attribs.href;
  3501. description += '[';
  3502. }
  3503. },
  3504. ontext: (htmltext) => {
  3505. description += htmltext.escapeFormatting();
  3506. },
  3507. onclosetag: (tagname) => {
  3508. if ( tagname === 'a' ) {
  3509. description += '](' + current_tag + ')';
  3510. current_tag = '';
  3511. }
  3512. if ( tagname === 'p' ) description += '\n';
  3513. }
  3514. }, {decodeEntities:true} );
  3515. parser.write( discussion.renderedContent );
  3516. parser.end();
  3517. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  3518. }
  3519. else {
  3520. description = discussion.rawContent.escapeFormatting();
  3521. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  3522. }
  3523. }
  3524. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  3525. embed.setDescription( description );
  3526. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3527. }
  3528. function gamepedia_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  3529. if ( args[0] ) {
  3530. var error = false;
  3531. var title = '';
  3532. var revision = 0;
  3533. var diff = 0;
  3534. var relative = 'prev';
  3535. if ( /^\d+$/.test(args[0]) ) {
  3536. revision = parseInt(args[0], 10);
  3537. if ( args[1] ) {
  3538. if ( /^\d+$/.test(args[1]) ) {
  3539. diff = parseInt(args[1], 10);
  3540. }
  3541. else if ( args[1] === 'prev' || args[1] === 'next' || args[1] === 'cur' ) {
  3542. relative = args[1];
  3543. }
  3544. else error = true;
  3545. }
  3546. }
  3547. else if ( args[0] === 'prev' || args[0] === 'next' || args[0] === 'cur' ) {
  3548. relative = args[0];
  3549. if ( args[1] ) {
  3550. if ( /^\d+$/.test(args[1]) ) {
  3551. revision = parseInt(args[1], 10);
  3552. }
  3553. else error = true;
  3554. }
  3555. else error = true;
  3556. }
  3557. else title = args.join(' ');
  3558. if ( error ) {
  3559. msg.reactEmoji('error');
  3560. if ( reaction ) reaction.removeEmoji();
  3561. }
  3562. else if ( diff ) {
  3563. gamepedia_diffsend(lang, msg, [diff, revision], wiki, reaction, spoiler);
  3564. }
  3565. else {
  3566. got.get( wiki + 'api.php?action=compare&prop=ids|diff' + ( title ? '&fromtitle=' + encodeURIComponent( title ) : '&fromrev=' + revision ) + '&torelative=' + relative + '&format=json', {
  3567. responseType: 'json'
  3568. } ).then( response => {
  3569. var body = response.body;
  3570. if ( body && body.warnings ) log_warn(body.warnings);
  3571. if ( response.statusCode !== 200 || !body || !body.compare ) {
  3572. var noerror = false;
  3573. if ( body && body.error ) {
  3574. switch ( body.error.code ) {
  3575. case 'nosuchrevid':
  3576. noerror = true;
  3577. break;
  3578. case 'missingtitle':
  3579. noerror = true;
  3580. break;
  3581. case 'invalidtitle':
  3582. noerror = true;
  3583. break;
  3584. case 'missingcontent':
  3585. noerror = true;
  3586. break;
  3587. default:
  3588. noerror = false;
  3589. }
  3590. }
  3591. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3592. console.log( '- This wiki doesn\'t exist!' );
  3593. msg.reactEmoji('nowiki');
  3594. }
  3595. else if ( noerror ) {
  3596. msg.replyMsg( lang.diff.badrev );
  3597. }
  3598. else {
  3599. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3600. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + relative + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  3601. }
  3602. if ( reaction ) reaction.removeEmoji();
  3603. }
  3604. else {
  3605. if ( body.compare.fromarchive !== undefined || body.compare.toarchive !== undefined ) {
  3606. msg.reactEmoji('error');
  3607. if ( reaction ) reaction.removeEmoji();
  3608. } else {
  3609. var argids = [];
  3610. var ids = body.compare;
  3611. if ( ids.fromrevid && !ids.torevid ) argids = [ids.fromrevid];
  3612. else if ( !ids.fromrevid && ids.torevid ) argids = [ids.torevid];
  3613. else {
  3614. argids = [ids.torevid, ids.fromrevid];
  3615. var compare = ['', ''];
  3616. if ( ids.fromtexthidden === undefined && ids.totexthidden === undefined && ids['*'] !== undefined ) {
  3617. var more = '\n__' + lang.diff.info.more + '__';
  3618. var current_tag = '';
  3619. var small_prev_ins = '';
  3620. var small_prev_del = '';
  3621. var ins_length = more.length;
  3622. var del_length = more.length;
  3623. var added = false;
  3624. var parser = new htmlparser.Parser( {
  3625. onopentag: (tagname, attribs) => {
  3626. if ( tagname === 'ins' || tagname == 'del' ) {
  3627. current_tag = tagname;
  3628. }
  3629. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3630. current_tag = tagname+'a';
  3631. }
  3632. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3633. current_tag = tagname+"d";
  3634. }
  3635. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3636. added = true;
  3637. }
  3638. },
  3639. ontext: (htmltext) => {
  3640. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3641. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3642. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3643. else small_prev_ins += more;
  3644. }
  3645. if ( current_tag === 'del' && del_length <= 1000 ) {
  3646. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3647. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3648. else small_prev_del += more;
  3649. }
  3650. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3651. ins_length += htmltext.escapeFormatting().length;
  3652. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3653. else small_prev_ins += more;
  3654. }
  3655. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3656. del_length += htmltext.escapeFormatting().length;
  3657. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3658. else small_prev_del += more;
  3659. }
  3660. if ( added ) {
  3661. if ( htmltext === '+' && ins_length <= 1000 ) {
  3662. ins_length++;
  3663. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3664. else small_prev_ins += more;
  3665. }
  3666. if ( htmltext === '−' && del_length <= 1000 ) {
  3667. del_length++;
  3668. if ( del_length <= 1000 ) small_prev_del += '\n';
  3669. else small_prev_del += more;
  3670. }
  3671. added = false;
  3672. }
  3673. },
  3674. onclosetag: (tagname) => {
  3675. if ( tagname === 'ins' ) {
  3676. current_tag = 'afterins';
  3677. } else if ( tagname === 'del' ) {
  3678. current_tag = 'afterdel';
  3679. } else {
  3680. current_tag = '';
  3681. }
  3682. }
  3683. }, {decodeEntities:true} );
  3684. parser.write( ids['*'] );
  3685. parser.end();
  3686. if ( small_prev_del.length ) {
  3687. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3688. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  3689. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  3690. }
  3691. if ( small_prev_ins.length ) {
  3692. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3693. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  3694. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  3695. }
  3696. }
  3697. else if ( ids.fromtexthidden !== undefined ) compare[0] = '__' + lang.diff.hidden + '__';
  3698. else if ( ids.totexthidden !== undefined ) compare[1] = '__' + lang.diff.hidden + '__';
  3699. }
  3700. gamepedia_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  3701. }
  3702. }
  3703. }, error => {
  3704. if ( wiki.noWiki(error.message) ) {
  3705. console.log( '- This wiki doesn\'t exist!' );
  3706. msg.reactEmoji('nowiki');
  3707. }
  3708. else {
  3709. console.log( '- Error while getting the search results: ' + error );
  3710. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + relative + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  3711. }
  3712. if ( reaction ) reaction.removeEmoji();
  3713. } );
  3714. }
  3715. }
  3716. else {
  3717. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, {embed} );
  3718. else msg.reactEmoji('error');
  3719. if ( reaction ) reaction.removeEmoji();
  3720. }
  3721. }
  3722. function gamepedia_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  3723. 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', {
  3724. responseType: 'json'
  3725. } ).then( response => {
  3726. var body = response.body;
  3727. if ( body && body.warnings ) log_warn(body.warnings);
  3728. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  3729. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3730. console.log( '- This wiki doesn\'t exist!' );
  3731. msg.reactEmoji('nowiki');
  3732. }
  3733. else {
  3734. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3735. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3736. }
  3737. if ( reaction ) reaction.removeEmoji();
  3738. }
  3739. else {
  3740. if ( body.query.badrevids ) {
  3741. msg.replyMsg( lang.diff.badrev );
  3742. if ( reaction ) reaction.removeEmoji();
  3743. }
  3744. else if ( body.query.pages && !body.query.pages['-1'] ) {
  3745. var pages = Object.values(body.query.pages);
  3746. if ( pages.length !== 1 ) {
  3747. msg.sendChannel( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0], '', '', body.query.general) + '>' + spoiler );
  3748. if ( reaction ) reaction.removeEmoji();
  3749. }
  3750. else {
  3751. var title = pages[0].title;
  3752. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  3753. var diff = revisions[0].revid;
  3754. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  3755. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  3756. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  3757. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  3758. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  3759. 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 ) )];
  3760. 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(', ')];
  3761. var pagelink = wiki.toLink(title, 'diff=' + diff + '&oldid=' + oldid, '', body.query.general);
  3762. if ( msg.showEmbed() ) {
  3763. var text = '<' + pagelink + '>';
  3764. var editorlink = '[' + editor[1] + '](' + wiki.toLink('User:' + editor[1], '', '', body.query.general, true) + ')';
  3765. if ( revisions[0].anon !== undefined ) {
  3766. editorlink = '[' + editor[1] + '](' + wiki.toLink('Special:Contributions/' + editor[1], '', '', body.query.general, true) + ')';
  3767. }
  3768. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  3769. 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] );
  3770. if ( tags ) {
  3771. var taglink = '';
  3772. var tagtext = '';
  3773. var tagparser = new htmlparser.Parser( {
  3774. onopentag: (tagname, attribs) => {
  3775. if ( tagname === 'a' ) taglink = attribs.href;
  3776. },
  3777. ontext: (htmltext) => {
  3778. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  3779. else tagtext += htmltext.escapeFormatting();
  3780. },
  3781. onclosetag: (tagname) => {
  3782. if ( tagname === 'a' ) taglink = '';
  3783. }
  3784. }, {decodeEntities:true} );
  3785. tagparser.write( tags[1] );
  3786. tagparser.end();
  3787. embed.addField( tags[0], tagtext );
  3788. }
  3789. var more = '\n__' + lang.diff.info.more + '__';
  3790. if ( !compare && oldid ) got.get( wiki + 'api.php?action=compare&prop=diff&fromrev=' + oldid + '&torev=' + diff + '&format=json', {
  3791. responseType: 'json'
  3792. } ).then( cpresponse => {
  3793. var cpbody = cpresponse.body;
  3794. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  3795. if ( cpresponse.statusCode !== 200 || !cpbody || !cpbody.compare || cpbody.compare['*'] === undefined ) {
  3796. var noerror = false;
  3797. if ( cpbody && cpbody.error ) {
  3798. switch ( cpbody.error.code ) {
  3799. case 'nosuchrevid':
  3800. noerror = true;
  3801. break;
  3802. case 'missingcontent':
  3803. noerror = true;
  3804. break;
  3805. default:
  3806. noerror = false;
  3807. }
  3808. }
  3809. if ( !noerror ) console.log( '- ' + cpresponse.statusCode + ': Error while getting the diff: ' + ( cpbody && cpbody.error && cpbody.error.info ) );
  3810. }
  3811. else if ( cpbody.compare.fromtexthidden === undefined && cpbody.compare.totexthidden === undefined && cpbody.compare.fromarchive === undefined && cpbody.compare.toarchive === undefined ) {
  3812. var current_tag = '';
  3813. var small_prev_ins = '';
  3814. var small_prev_del = '';
  3815. var ins_length = more.length;
  3816. var del_length = more.length;
  3817. var added = false;
  3818. var parser = new htmlparser.Parser( {
  3819. onopentag: (tagname, attribs) => {
  3820. if ( tagname === 'ins' || tagname == 'del' ) {
  3821. current_tag = tagname;
  3822. }
  3823. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3824. current_tag = tagname+'a';
  3825. }
  3826. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3827. current_tag = tagname+"d";
  3828. }
  3829. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3830. added = true;
  3831. }
  3832. },
  3833. ontext: (htmltext) => {
  3834. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3835. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3836. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3837. else small_prev_ins += more;
  3838. }
  3839. if ( current_tag === 'del' && del_length <= 1000 ) {
  3840. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3841. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3842. else small_prev_del += more;
  3843. }
  3844. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3845. ins_length += htmltext.escapeFormatting().length;
  3846. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3847. else small_prev_ins += more;
  3848. }
  3849. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3850. del_length += htmltext.escapeFormatting().length;
  3851. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3852. else small_prev_del += more;
  3853. }
  3854. if ( added ) {
  3855. if ( htmltext === '+' && ins_length <= 1000 ) {
  3856. ins_length++;
  3857. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3858. else small_prev_ins += more;
  3859. }
  3860. if ( htmltext === '−' && del_length <= 1000 ) {
  3861. del_length++;
  3862. if ( del_length <= 1000 ) small_prev_del += '\n';
  3863. else small_prev_del += more;
  3864. }
  3865. added = false;
  3866. }
  3867. },
  3868. onclosetag: (tagname) => {
  3869. if ( tagname === 'ins' ) {
  3870. current_tag = 'afterins';
  3871. } else if ( tagname === 'del' ) {
  3872. current_tag = 'afterdel';
  3873. } else {
  3874. current_tag = '';
  3875. }
  3876. }
  3877. }, {decodeEntities:true} );
  3878. parser.write( cpbody.compare['*'] );
  3879. parser.end();
  3880. if ( small_prev_del.length ) {
  3881. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3882. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  3883. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  3884. }
  3885. if ( small_prev_ins.length ) {
  3886. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3887. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  3888. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3889. }
  3890. }
  3891. else if ( cpbody.compare.fromtexthidden !== undefined ) {
  3892. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  3893. }
  3894. else if ( cpbody.compare.totexthidden !== undefined ) {
  3895. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  3896. }
  3897. }, error => {
  3898. console.log( '- Error while getting the diff: ' + error );
  3899. } ).finally( () => {
  3900. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3901. if ( reaction ) reaction.removeEmoji();
  3902. } );
  3903. else {
  3904. if ( compare ) {
  3905. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  3906. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  3907. }
  3908. else if ( revisions[0]['*'] ) {
  3909. var content = revisions[0]['*'].escapeFormatting();
  3910. if ( content.trim().length ) {
  3911. if ( content.length <= 1000 ) content = '**' + content + '**';
  3912. else {
  3913. content = content.substring(0, 1000 - more.length);
  3914. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  3915. }
  3916. embed.addField( lang.diff.info.added, content, true );
  3917. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3918. }
  3919. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3920. if ( reaction ) reaction.removeEmoji();
  3921. }
  3922. }
  3923. else {
  3924. var embed = {};
  3925. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  3926. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  3927. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3928. if ( reaction ) reaction.removeEmoji();
  3929. }
  3930. }
  3931. }
  3932. else {
  3933. msg.reactEmoji('error');
  3934. if ( reaction ) reaction.removeEmoji();
  3935. }
  3936. }
  3937. }, error => {
  3938. if ( wiki.noWiki(error.message) ) {
  3939. console.log( '- This wiki doesn\'t exist!' );
  3940. msg.reactEmoji('nowiki');
  3941. }
  3942. else {
  3943. console.log( '- Error while getting the search results: ' + error );
  3944. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3945. }
  3946. if ( reaction ) reaction.removeEmoji();
  3947. } );
  3948. }
  3949. function fandom_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  3950. if ( args[0] ) {
  3951. var error = false;
  3952. var title = '';
  3953. var revision = 0;
  3954. var diff = 'prev';
  3955. if ( /^\d+$/.test(args[0]) ) {
  3956. revision = args[0];
  3957. if ( args[1] ) {
  3958. if ( /^\d+$/.test(args[1]) ) {
  3959. diff = args[1];
  3960. }
  3961. else if ( args[1] === 'prev' || args[1] === 'next' ) {
  3962. diff = args[1];
  3963. }
  3964. else error = true;
  3965. }
  3966. }
  3967. else if ( args[0] === 'prev' || args[0] === 'next' ) {
  3968. diff = args[0];
  3969. if ( args[1] ) {
  3970. if ( /^\d+$/.test(args[1]) ) {
  3971. revision = args[1];
  3972. }
  3973. else error = true;
  3974. }
  3975. else error = true;
  3976. }
  3977. else title = args.join(' ');
  3978. if ( error ) msg.reactEmoji('error');
  3979. else if ( /^\d+$/.test(diff) ) {
  3980. var argids = [];
  3981. if ( parseInt(revision, 10) > parseInt(diff, 10) ) argids = [revision, diff];
  3982. else if ( parseInt(revision, 10) === parseInt(diff, 10) ) argids = [revision];
  3983. else argids = [diff, revision];
  3984. fandom_diffsend(lang, msg, argids, wiki, reaction, spoiler);
  3985. }
  3986. else {
  3987. got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=' + ( title ? '&titles=' + encodeURIComponent( title ) : '&revids=' + revision ) + '&rvdiffto=' + diff + '&format=json', {
  3988. responseType: 'json'
  3989. } ).then( response => {
  3990. var body = response.body;
  3991. if ( body && body.warnings ) log_warn(body.warnings);
  3992. if ( response.statusCode !== 200 || !body || !body.query ) {
  3993. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3994. console.log( '- This wiki doesn\'t exist!' );
  3995. msg.reactEmoji('nowiki');
  3996. }
  3997. else {
  3998. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3999. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + diff + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  4000. }
  4001. if ( reaction ) reaction.removeEmoji();
  4002. }
  4003. else {
  4004. if ( body.query.badrevids ) {
  4005. msg.replyMsg( lang.diff.badrev );
  4006. if ( reaction ) reaction.removeEmoji();
  4007. } else if ( body.query.pages && !body.query.pages[-1] ) {
  4008. var revisions = Object.values(body.query.pages)[0].revisions[0];
  4009. if ( revisions.texthidden === undefined ) {
  4010. var argids = [];
  4011. var ids = revisions.diff;
  4012. if ( !ids.from ) argids = [ids.to];
  4013. else {
  4014. argids = [ids.to, ids.from];
  4015. var compare = ['', ''];
  4016. if ( ids['*'] !== undefined ) {
  4017. var more = '\n__' + lang.diff.info.more + '__';
  4018. var current_tag = '';
  4019. var small_prev_ins = '';
  4020. var small_prev_del = '';
  4021. var ins_length = more.length;
  4022. var del_length = more.length;
  4023. var added = false;
  4024. var parser = new htmlparser.Parser( {
  4025. onopentag: (tagname, attribs) => {
  4026. if ( tagname === 'ins' || tagname == 'del' ) {
  4027. current_tag = tagname;
  4028. }
  4029. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  4030. current_tag = tagname+'a';
  4031. }
  4032. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  4033. current_tag = tagname+"d";
  4034. }
  4035. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  4036. added = true;
  4037. }
  4038. },
  4039. ontext: (htmltext) => {
  4040. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  4041. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  4042. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  4043. else small_prev_ins += more;
  4044. }
  4045. if ( current_tag === 'del' && del_length <= 1000 ) {
  4046. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  4047. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  4048. else small_prev_del += more;
  4049. }
  4050. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  4051. ins_length += htmltext.escapeFormatting().length;
  4052. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  4053. else small_prev_ins += more;
  4054. }
  4055. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  4056. del_length += htmltext.escapeFormatting().length;
  4057. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  4058. else small_prev_del += more;
  4059. }
  4060. if ( added ) {
  4061. if ( htmltext === '+' && ins_length <= 1000 ) {
  4062. ins_length++;
  4063. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  4064. else small_prev_ins += more;
  4065. }
  4066. if ( htmltext === '−' && del_length <= 1000 ) {
  4067. del_length++;
  4068. if ( del_length <= 1000 ) small_prev_del += '\n';
  4069. else small_prev_del += more;
  4070. }
  4071. added = false;
  4072. }
  4073. },
  4074. onclosetag: (tagname) => {
  4075. if ( tagname === 'ins' ) {
  4076. current_tag = 'afterins';
  4077. } else if ( tagname === 'del' ) {
  4078. current_tag = 'afterdel';
  4079. } else {
  4080. current_tag = '';
  4081. }
  4082. }
  4083. }, {decodeEntities:true} );
  4084. parser.write( ids['*'] );
  4085. parser.end();
  4086. if ( small_prev_del.length ) {
  4087. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  4088. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  4089. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  4090. }
  4091. if ( small_prev_ins.length ) {
  4092. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  4093. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  4094. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  4095. }
  4096. }
  4097. }
  4098. fandom_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  4099. } else {
  4100. msg.replyMsg( lang.diff.badrev );
  4101. if ( reaction ) reaction.removeEmoji();
  4102. }
  4103. } else {
  4104. if ( body.query.pages && body.query.pages[-1] ) msg.replyMsg( lang.diff.badrev );
  4105. else msg.reactEmoji('error');
  4106. if ( reaction ) reaction.removeEmoji();
  4107. }
  4108. }
  4109. }, error => {
  4110. if ( wiki.noWiki(error.message) ) {
  4111. console.log( '- This wiki doesn\'t exist!' );
  4112. msg.reactEmoji('nowiki');
  4113. }
  4114. else {
  4115. console.log( '- Error while getting the search results: ' + error );
  4116. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + diff + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  4117. }
  4118. if ( reaction ) reaction.removeEmoji();
  4119. } );
  4120. }
  4121. }
  4122. else {
  4123. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, {embed} );
  4124. else msg.reactEmoji('error');
  4125. if ( reaction ) reaction.removeEmoji();
  4126. }
  4127. }
  4128. function fandom_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  4129. 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', {
  4130. responseType: 'json'
  4131. } ).then( response => {
  4132. var body = response.body;
  4133. if ( body && body.warnings ) log_warn(body.warnings);
  4134. if ( response.statusCode !== 200 || !body || !body.query ) {
  4135. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4136. console.log( '- This wiki doesn\'t exist!' );
  4137. msg.reactEmoji('nowiki');
  4138. }
  4139. else {
  4140. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  4141. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  4142. }
  4143. if ( reaction ) reaction.removeEmoji();
  4144. }
  4145. else {
  4146. if ( body.query.badrevids ) {
  4147. msg.replyMsg( lang.diff.badrev );
  4148. if ( reaction ) reaction.removeEmoji();
  4149. }
  4150. else if ( body.query.pages && !body.query.pages['-1'] ) {
  4151. var pages = Object.values(body.query.pages);
  4152. if ( pages.length !== 1 ) {
  4153. msg.sendChannel( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0], '', '', body.query.general) + '>' + spoiler );
  4154. if ( reaction ) reaction.removeEmoji();
  4155. }
  4156. else {
  4157. var title = pages[0].title;
  4158. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  4159. var diff = revisions[0].revid;
  4160. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  4161. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  4162. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  4163. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  4164. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  4165. 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 ) )];
  4166. 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(', ')];
  4167. var pagelink = wiki.toLink(title, 'diff=' + diff + '&oldid=' + oldid, '', body.query.general);
  4168. if ( msg.showEmbed() ) {
  4169. var text = '<' + pagelink + '>';
  4170. var editorlink = '[' + editor[1] + '](' + wiki.toLink('User:' + editor[1], '', '', body.query.general, true) + ')';
  4171. if ( revisions[0].anon !== undefined ) {
  4172. editorlink = '[' + editor[1] + '](' + wiki.toLink('Special:Contributions/' + editor[1], '', '', body.query.general, true) + ')';
  4173. }
  4174. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  4175. 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] );
  4176. if ( tags ) {
  4177. var taglink = '';
  4178. var tagtext = '';
  4179. var tagparser = new htmlparser.Parser( {
  4180. onopentag: (tagname, attribs) => {
  4181. if ( tagname === 'a' ) taglink = attribs.href;
  4182. },
  4183. ontext: (htmltext) => {
  4184. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  4185. else tagtext += htmltext.escapeFormatting();
  4186. },
  4187. onclosetag: (tagname) => {
  4188. if ( tagname === 'a' ) taglink = '';
  4189. }
  4190. }, {decodeEntities:true} );
  4191. tagparser.write( tags[1] );
  4192. tagparser.end();
  4193. embed.addField( tags[0], tagtext );
  4194. }
  4195. var more = '\n__' + lang.diff.info.more + '__';
  4196. if ( !compare && oldid ) got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=&revids=' + oldid + '&rvdiffto=' + diff + '&format=json', {
  4197. responseType: 'json'
  4198. } ).then( cpresponse => {
  4199. var cpbody = cpresponse.body;
  4200. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  4201. if ( cpresponse.statusCode !== 200 || !cpbody || !cpbody.query || cpbody.query.badrevids || !cpbody.query.pages && cpbody.query.pages[-1] ) {
  4202. console.log( '- ' + cpresponse.statusCode + ': Error while getting the diff: ' + ( cpbody && cpbody.error && cpbody.error.info ) );
  4203. }
  4204. else {
  4205. var revision = Object.values(cpbody.query.pages)[0].revisions[0];
  4206. if ( revision.texthidden === undefined && revision.diff && revision.diff['*'] !== undefined ) {
  4207. var current_tag = '';
  4208. var small_prev_ins = '';
  4209. var small_prev_del = '';
  4210. var ins_length = more.length;
  4211. var del_length = more.length;
  4212. var added = false;
  4213. var parser = new htmlparser.Parser( {
  4214. onopentag: (tagname, attribs) => {
  4215. if ( tagname === 'ins' || tagname == 'del' ) {
  4216. current_tag = tagname;
  4217. }
  4218. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  4219. current_tag = tagname+'a';
  4220. }
  4221. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  4222. current_tag = tagname+"d";
  4223. }
  4224. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  4225. added = true;
  4226. }
  4227. },
  4228. ontext: (htmltext) => {
  4229. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  4230. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  4231. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  4232. else small_prev_ins += more;
  4233. }
  4234. if ( current_tag === 'del' && del_length <= 1000 ) {
  4235. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  4236. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  4237. else small_prev_del += more;
  4238. }
  4239. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  4240. ins_length += htmltext.escapeFormatting().length;
  4241. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  4242. else small_prev_ins += more;
  4243. }
  4244. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  4245. del_length += htmltext.escapeFormatting().length;
  4246. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  4247. else small_prev_del += more;
  4248. }
  4249. if ( added ) {
  4250. if ( htmltext === '+' && ins_length <= 1000 ) {
  4251. ins_length++;
  4252. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  4253. else small_prev_ins += more;
  4254. }
  4255. if ( htmltext === '−' && del_length <= 1000 ) {
  4256. del_length++;
  4257. if ( del_length <= 1000 ) small_prev_del += '\n';
  4258. else small_prev_del += more;
  4259. }
  4260. added = false;
  4261. }
  4262. },
  4263. onclosetag: (tagname) => {
  4264. if ( tagname === 'ins' ) {
  4265. current_tag = 'afterins';
  4266. } else if ( tagname === 'del' ) {
  4267. current_tag = 'afterdel';
  4268. } else {
  4269. current_tag = '';
  4270. }
  4271. }
  4272. }, {decodeEntities:true} );
  4273. parser.write( revision.diff['*'] );
  4274. parser.end();
  4275. if ( small_prev_del.length ) {
  4276. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  4277. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  4278. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  4279. }
  4280. if ( small_prev_ins.length ) {
  4281. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  4282. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  4283. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  4284. }
  4285. }
  4286. else if ( revision.texthidden !== undefined ) {
  4287. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  4288. }
  4289. else if ( revision.diff && revision.diff['*'] === undefined ) {
  4290. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  4291. }
  4292. }
  4293. }, error => {
  4294. console.log( '- Error while getting the diff: ' + error );
  4295. } ).finally( () => {
  4296. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4297. if ( reaction ) reaction.removeEmoji();
  4298. } );
  4299. else {
  4300. if ( compare ) {
  4301. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  4302. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  4303. }
  4304. else if ( revisions[0]['*'] ) {
  4305. var content = revisions[0]['*'].escapeFormatting();
  4306. if ( content.trim().length ) {
  4307. if ( content.length <= 1000 ) content = '**' + content + '**';
  4308. else {
  4309. content = content.substring(0, 1000 - more.length);
  4310. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  4311. }
  4312. embed.addField( lang.diff.info.added, content, true );
  4313. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  4314. }
  4315. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4316. if ( reaction ) reaction.removeEmoji();
  4317. }
  4318. }
  4319. else {
  4320. var embed = {};
  4321. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  4322. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  4323. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4324. if ( reaction ) reaction.removeEmoji();
  4325. }
  4326. }
  4327. }
  4328. else {
  4329. msg.reactEmoji('error');
  4330. if ( reaction ) reaction.removeEmoji();
  4331. }
  4332. }
  4333. }, error => {
  4334. if ( wiki.noWiki(error.message) ) {
  4335. console.log( '- This wiki doesn\'t exist!' );
  4336. msg.reactEmoji('nowiki');
  4337. }
  4338. else {
  4339. console.log( '- Error while getting the search results: ' + error );
  4340. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  4341. }
  4342. if ( reaction ) reaction.removeEmoji();
  4343. } );
  4344. }
  4345. function gamepedia_random(lang, msg, wiki, reaction, spoiler) {
  4346. 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', {
  4347. responseType: 'json'
  4348. } ).then( response => {
  4349. var body = response.body;
  4350. if ( body && body.warnings ) log_warn(body.warnings);
  4351. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  4352. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4353. console.log( '- This wiki doesn\'t exist!' );
  4354. msg.reactEmoji('nowiki');
  4355. }
  4356. else {
  4357. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  4358. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  4359. }
  4360. }
  4361. else {
  4362. var querypage = Object.values(body.query.pages)[0];
  4363. var pagelink = wiki.toLink(querypage.title, '', '', body.query.general);
  4364. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  4365. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  4366. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  4367. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  4368. embed.setTitle( displaytitle );
  4369. }
  4370. if ( querypage.pageprops && querypage.pageprops.description ) {
  4371. var description = htmlToPlain( querypage.pageprops.description );
  4372. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  4373. embed.setDescription( description );
  4374. }
  4375. else if ( querypage.extract ) {
  4376. var extract = querypage.extract.escapeFormatting();
  4377. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  4378. embed.setDescription( extract );
  4379. }
  4380. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  4381. embed.setThumbnail( querypage.original.source );
  4382. }
  4383. else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  4384. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  4385. }
  4386. }, error => {
  4387. if ( wiki.noWiki(error.message) ) {
  4388. console.log( '- This wiki doesn\'t exist!' );
  4389. msg.reactEmoji('nowiki');
  4390. }
  4391. else {
  4392. console.log( '- Error while getting the search results: ' + error );
  4393. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  4394. }
  4395. } ).finally( () => {
  4396. if ( reaction ) reaction.removeEmoji();
  4397. } );
  4398. }
  4399. function fandom_random(lang, msg, wiki, reaction, spoiler) {
  4400. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=description&siprop=general&generator=random&grnnamespace=0&format=json', {
  4401. responseType: 'json'
  4402. } ).then( response => {
  4403. var body = response.body;
  4404. if ( body && body.warnings ) log_warn(body.warnings);
  4405. if ( response.statusCode !== 200 || !body || !body.query || !body.query.pages ) {
  4406. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4407. console.log( '- This wiki doesn\'t exist!' );
  4408. msg.reactEmoji('nowiki');
  4409. }
  4410. else {
  4411. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  4412. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  4413. }
  4414. if ( reaction ) reaction.removeEmoji();
  4415. }
  4416. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  4417. return gamepedia_random(lang, msg, wiki, reaction, spoiler);
  4418. }
  4419. else {
  4420. var querypage = Object.values(body.query.pages)[0];
  4421. var pagelink = wiki.toLink(querypage.title, '', '', body.query.general);
  4422. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  4423. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  4424. embed.setDescription( body.query.allmessages[0]['*'] );
  4425. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  4426. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  4427. if ( reaction ) reaction.removeEmoji();
  4428. }
  4429. else got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  4430. var descbody = descresponse.body;
  4431. if ( descresponse.statusCode !== 200 || !descbody ) {
  4432. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  4433. } else {
  4434. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  4435. var parser = new htmlparser.Parser( {
  4436. onopentag: (tagname, attribs) => {
  4437. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  4438. var description = attribs.content.escapeFormatting();
  4439. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  4440. embed.setDescription( description );
  4441. }
  4442. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  4443. thumbnail = attribs.content;
  4444. }
  4445. }
  4446. }, {decodeEntities:true} );
  4447. parser.write( descbody );
  4448. parser.end();
  4449. embed.setThumbnail( thumbnail );
  4450. }
  4451. }, error => {
  4452. console.log( '- Error while getting the description: ' + error );
  4453. } ).finally( () => {
  4454. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  4455. if ( reaction ) reaction.removeEmoji();
  4456. } );
  4457. }
  4458. }, error => {
  4459. if ( wiki.noWiki(error.message) ) {
  4460. console.log( '- This wiki doesn\'t exist!' );
  4461. msg.reactEmoji('nowiki');
  4462. }
  4463. else {
  4464. console.log( '- Error while getting the search results: ' + error );
  4465. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  4466. }
  4467. if ( reaction ) reaction.removeEmoji();
  4468. } );
  4469. }
  4470. function gamepedia_overview(lang, msg, wiki, reaction, spoiler) {
  4471. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-Wiki_Manager|custom-GamepediaNotice&amenableparser=true&siprop=general|statistics&titles=Special:Statistics&format=json', {
  4472. responseType: 'json'
  4473. } ).then( response => {
  4474. var body = response.body;
  4475. if ( body && body.warnings ) log_warn(body.warnings);
  4476. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  4477. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4478. console.log( '- This wiki doesn\'t exist!' );
  4479. msg.reactEmoji('nowiki');
  4480. }
  4481. else {
  4482. console.log( '- ' + response.statusCode + ': Error while getting the statistics: ' + ( body && body.error && body.error.info ) );
  4483. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4484. }
  4485. if ( reaction ) reaction.removeEmoji();
  4486. }
  4487. else {
  4488. var site = false;
  4489. if ( allSites.some( site => site.wiki_domain === body.query.general.servername ) ) {
  4490. site = allSites.find( site => site.wiki_domain === body.query.general.servername );
  4491. var name = [lang.overview.name, site.wiki_display_name];
  4492. var created = [lang.overview.created, new Date(parseInt(site.created + '000', 10)).toLocaleString(lang.dateformat, timeoptions)];
  4493. var manager = [lang.overview.manager, site.wiki_managers];
  4494. var official = [lang.overview.official, ( site.official_wiki ? lang.overview.yes : lang.overview.no )];
  4495. var crossover = [lang.overview.crossover, ( site.wiki_crossover ? '<https://' + site.wiki_crossover + '/>' : '' )];
  4496. var description = [lang.overview.description, site.wiki_description];
  4497. var image = [lang.overview.image, site.wiki_image];
  4498. if ( description[1] ) {
  4499. description[1] = description[1].escapeFormatting();
  4500. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  4501. }
  4502. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  4503. }
  4504. var articles = [lang.overview.articles, body.query.statistics.articles];
  4505. var pages = [lang.overview.pages, body.query.statistics.pages];
  4506. var edits = [lang.overview.edits, body.query.statistics.edits];
  4507. var users = [lang.overview.users, body.query.statistics.activeusers];
  4508. var title = body.query.pages['-1'].title;
  4509. var pagelink = wiki.toLink(title, '', '', body.query.general);
  4510. if ( msg.showEmbed() ) {
  4511. var text = '<' + pagelink + '>';
  4512. 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 );
  4513. }
  4514. else {
  4515. var embed = {};
  4516. var text = '<' + pagelink + '>\n\n';
  4517. }
  4518. if ( wiki.isFandom() ) got.get( 'https://community.fandom.com/api/v1/Wikis/ByString?expand=true&includeDomain=true&limit=10&string=' + body.query.general.servername + body.query.general.scriptpath + '&format=json', {
  4519. responseType: 'json'
  4520. } ).then( ovresponse => {
  4521. var ovbody = ovresponse.body;
  4522. if ( ovresponse.statusCode !== 200 || !ovbody || ovbody.exception || !ovbody.items || !ovbody.items.length ) {
  4523. console.log( '- ' + ovresponse.statusCode + ': Error while getting the wiki details: ' + ( ovbody && ovbody.exception && ovbody.exception.details ) );
  4524. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4525. if ( reaction ) reaction.removeEmoji();
  4526. }
  4527. else if ( ovbody.items.some( site => site.url === body.query.general.server + ( body.query.general.scriptpath ? body.query.general.scriptpath + '/' : '' ) ) ) {
  4528. site = ovbody.items.find( site => site.url === body.query.general.server + ( body.query.general.scriptpath ? body.query.general.scriptpath + '/' : '' ) );
  4529. var vertical = [lang.overview.vertical, site.hub];
  4530. var topic = [lang.overview.topic, site.topic];
  4531. var founder = [lang.overview.founder, site.founding_user_id];
  4532. var manager = [lang.overview.manager, body.query.allmessages[0]['*']];
  4533. var crossover = [lang.overview.crossover, ( body.query.allmessages[1]['*'] ? '<https://' + body.query.allmessages[1]['*'] + '.gamepedia.com/>' : '' )];
  4534. var created = [lang.overview.created, new Date(site.creation_date).toLocaleString(lang.dateformat, timeoptions)];
  4535. var description = [lang.overview.description, site.desc];
  4536. var image = [lang.overview.image, site.image];
  4537. if ( description[1] ) {
  4538. description[1] = description[1].escapeFormatting();
  4539. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  4540. }
  4541. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  4542. if ( msg.showEmbed() ) {
  4543. embed.addField( vertical[0], vertical[1], true );
  4544. if ( topic[1] ) embed.addField( topic[0], topic[1], true );
  4545. }
  4546. else text += vertical.join(' ') + ( topic[1] ? '\n' + topic.join(' ') : '' );
  4547. if ( founder[1] > 0 ) got.get( wiki + 'api.php?action=query&list=users&usprop=&ususerids=' + founder[1] + '&format=json', {
  4548. responseType: 'json'
  4549. } ).then( usresponse => {
  4550. var usbody = usresponse.body;
  4551. if ( usbody && usbody.warnings ) log_warn(usbody.warnings);
  4552. if ( usresponse.statusCode !== 200 || !usbody || !usbody.query || !usbody.query.users || !usbody.query.users[0] ) {
  4553. console.log( '- ' + usresponse.statusCode + ': Error while getting the wiki founder: ' + ( usbody && usbody.error && usbody.error.info ) );
  4554. founder[1] = 'ID: ' + founder[1];
  4555. }
  4556. else {
  4557. var user = usbody.query.users[0].name;
  4558. if ( msg.showEmbed() ) founder[1] = '[' + user + '](' + wiki.toLink('User:' + user, '', '', body.query.general, true) + ')';
  4559. else founder[1] = user;
  4560. }
  4561. }, error => {
  4562. console.log( '- Error while getting the wiki founder: ' + error );
  4563. founder[1] = 'ID: ' + founder[1];
  4564. } ).finally( () => {
  4565. if ( msg.showEmbed() ) {
  4566. embed.addField( founder[0], founder[1], true );
  4567. 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 );
  4568. 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 );
  4569. if ( crossover[1] ) {
  4570. var crossoverSite = allSites.find( site => '<https://' + site.wiki_domain + '/>' === crossover[1] );
  4571. if ( crossoverSite ) embed.addField( crossover[0], '[' + crossoverSite.wiki_display_name + '](' + crossover[1] + ')', true );
  4572. else embed.addField( crossover[0], crossover[1], true );
  4573. }
  4574. if ( description[1] ) embed.addField( description[0], description[1] );
  4575. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4576. }
  4577. else {
  4578. text += '\n' + founder.join(' ') + ( manager[1] ? '\n' + manager.join(' ') : '' ) + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4579. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4580. if ( description[1] ) text += '\n' + description.join(' ');
  4581. if ( image[1] ) {
  4582. text += '\n' + image.join(' ');
  4583. if ( msg.uploadFiles() ) embed.files = [image[1]];
  4584. }
  4585. text += '\n\n*' + lang.overview.inaccurate + '*';
  4586. }
  4587. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4588. if ( reaction ) reaction.removeEmoji();
  4589. } );
  4590. else {
  4591. founder[1] = lang.overview.none;
  4592. if ( msg.showEmbed() ) {
  4593. 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 );
  4594. if ( crossover[1] ) {
  4595. var crossoverSite = allSites.find( site => '<https://' + site.wiki_domain + '/>' === crossover[1] );
  4596. if ( crossoverSite ) embed.addField( crossover[0], '[' + crossoverSite.wiki_display_name + '](' + crossover[1] + ')', true );
  4597. else embed.addField( crossover[0], crossover[1], true );
  4598. }
  4599. if ( description[1] ) embed.addField( description[0], description[1] );
  4600. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4601. }
  4602. else {
  4603. text += '\n' + founder.join(' ') + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4604. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4605. if ( description[1] ) text += '\n' + description.join(' ');
  4606. if ( image[1] ) {
  4607. text += '\n' + image.join(' ');
  4608. if ( msg.uploadFiles() ) embed.files = [image[1]];
  4609. }
  4610. text += '\n\n*' + lang.overview.inaccurate + '*';
  4611. }
  4612. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4613. if ( reaction ) reaction.removeEmoji();
  4614. }
  4615. }
  4616. else {
  4617. 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 );
  4618. else text = articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ') + '\n\n*' + lang.overview.inaccurate + '*';
  4619. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4620. if ( reaction ) reaction.removeEmoji();
  4621. }
  4622. }, error => {
  4623. console.log( '- Error while getting the wiki details: ' + error );
  4624. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4625. if ( reaction ) reaction.removeEmoji();
  4626. } );
  4627. else {
  4628. if ( msg.showEmbed() ) {
  4629. if ( site ) {
  4630. 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');
  4631. 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 );
  4632. }
  4633. 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 );
  4634. if ( site ) {
  4635. if ( crossover[1] ) embed.addField( crossover[0], crossover[1], true );
  4636. if ( description[1] ) embed.addField( description[0], description[1] );
  4637. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4638. }
  4639. }
  4640. else {
  4641. if ( site ) text += name.join(' ') + '\n' + created.join(' ') + '\n' + manager[0] + ' ' + ( manager[1].join(', ') || lang.overview.none ) + '\n' + official.join(' ') + '\n';
  4642. text += articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4643. if ( site ) {
  4644. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4645. if ( description[1] ) text += '\n' + description.join(' ');
  4646. if ( image[1] ) {
  4647. text += '\n' + image.join(' ');
  4648. if ( msg.uploadFiles() ) embed.files = [{attachment:image[1],name:( spoiler ? 'SPOILER ' : '' ) + name[1] + image[1].substring(image[1].lastIndexOf('.'))}];
  4649. }
  4650. }
  4651. text += '\n\n*' + lang.overview.inaccurate + '*';
  4652. }
  4653. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4654. if ( reaction ) reaction.removeEmoji();
  4655. }
  4656. }
  4657. }, error => {
  4658. if ( wiki.noWiki(error.message) ) {
  4659. console.log( '- This wiki doesn\'t exist!' );
  4660. msg.reactEmoji('nowiki');
  4661. }
  4662. else {
  4663. console.log( '- Error while getting the statistics: ' + error );
  4664. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4665. }
  4666. if ( reaction ) reaction.removeEmoji();
  4667. } );
  4668. }
  4669. function fandom_overview(lang, msg, wiki, reaction, spoiler) {
  4670. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-Wiki_Manager|custom-GamepediaNotice&amenableparser=true&siprop=general|statistics|wikidesc&titles=Special:Statistics&format=json', {
  4671. responseType: 'json'
  4672. } ).then( response => {
  4673. var body = response.body;
  4674. if ( body && body.warnings ) log_warn(body.warnings);
  4675. if ( response.statusCode !== 200 || !body || !body.query || !body.query.pages ) {
  4676. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4677. console.log( '- This wiki doesn\'t exist!' );
  4678. msg.reactEmoji('nowiki');
  4679. }
  4680. else {
  4681. console.log( '- ' + response.statusCode + ': Error while getting the statistics: ' + ( body && body.error && body.error.info ) );
  4682. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4683. }
  4684. if ( reaction ) reaction.removeEmoji();
  4685. }
  4686. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  4687. return gamepedia_overview(lang, msg, wiki, reaction, spoiler);
  4688. }
  4689. else got.get( 'https://community.fandom.com/api/v1/Wikis/Details?ids=' + body.query.wikidesc.id + '&format=json', {
  4690. responseType: 'json'
  4691. } ).then( ovresponse => {
  4692. var ovbody = ovresponse.body;
  4693. if ( ovresponse.statusCode !== 200 || !ovbody || ovbody.exception || !ovbody.items || !ovbody.items[body.query.wikidesc.id] ) {
  4694. console.log( '- ' + ovresponse.statusCode + ': Error while getting the wiki details: ' + ( ovbody && ovbody.exception && ovbody.exception.details ) );
  4695. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4696. if ( reaction ) reaction.removeEmoji();
  4697. }
  4698. else {
  4699. var site = ovbody.items[body.query.wikidesc.id];
  4700. var vertical = [lang.overview.vertical, site.hub];
  4701. var topic = [lang.overview.topic, site.topic];
  4702. var founder = [lang.overview.founder, site.founding_user_id];
  4703. var manager = [lang.overview.manager, body.query.allmessages[0]['*']];
  4704. var crossover = [lang.overview.crossover, ( body.query.allmessages[1]['*'] ? '<https://' + body.query.allmessages[1]['*'] + '.gamepedia.com/>' : '' )];
  4705. var created = [lang.overview.created, new Date(site.creation_date).toLocaleString(lang.dateformat, timeoptions)];
  4706. var articles = [lang.overview.articles, body.query.statistics.articles];
  4707. var pages = [lang.overview.pages, body.query.statistics.pages];
  4708. var edits = [lang.overview.edits, body.query.statistics.edits];
  4709. var users = [lang.overview.users, body.query.statistics.activeusers];
  4710. var description = [lang.overview.description, site.desc];
  4711. var image = [lang.overview.image, site.image];
  4712. if ( description[1] ) {
  4713. description[1] = description[1].escapeFormatting();
  4714. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  4715. }
  4716. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  4717. var title = body.query.pages['-1'].title;
  4718. var pagelink = wiki.toLink(title, '', '', body.query.general);
  4719. if ( msg.showEmbed() ) {
  4720. var text = '<' + pagelink + '>';
  4721. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( title.escapeFormatting() ).setURL( pagelink ).setThumbnail( site.wordmark ).addField( vertical[0], vertical[1], true );
  4722. if ( topic[1] ) embed.addField( topic[0], topic[1], true );
  4723. }
  4724. else {
  4725. var embed = {};
  4726. var text = '<' + pagelink + '>\n\n' + vertical.join(' ') + ( topic[1] ? '\n' + topic.join(' ') : '' );
  4727. }
  4728. if ( founder[1] > 0 ) got.get( wiki + 'api.php?action=query&list=users&usprop=&usids=' + founder[1] + '&format=json', {
  4729. responseType: 'json'
  4730. } ).then( usresponse => {
  4731. var usbody = usresponse.body;
  4732. if ( usbody && usbody.warnings ) log_warn(usbody.warnings);
  4733. if ( usresponse.statusCode !== 200 || !usbody || !usbody.query || !usbody.query.users || !usbody.query.users[0] ) {
  4734. console.log( '- ' + usresponse.statusCode + ': Error while getting the wiki founder: ' + ( usbody && usbody.error && usbody.error.info ) );
  4735. founder[1] = 'ID: ' + founder[1];
  4736. }
  4737. else {
  4738. var user = usbody.query.users[0].name;
  4739. if ( msg.showEmbed() ) founder[1] = '[' + user + '](' + wiki.toLink('User:' + user, '', '', body.query.general, true) + ')';
  4740. else founder[1] = user;
  4741. }
  4742. }, error => {
  4743. console.log( '- Error while getting the wiki founder: ' + error );
  4744. founder[1] = 'ID: ' + founder[1];
  4745. } ).finally( () => {
  4746. if ( msg.showEmbed() ) {
  4747. embed.addField( founder[0], founder[1], true );
  4748. 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 );
  4749. 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 );
  4750. if ( crossover[1] ) {
  4751. var crossoverSite = allSites.find( site => '<https://' + site.wiki_domain + '/>' === crossover[1] );
  4752. if ( crossoverSite ) embed.addField( crossover[0], '[' + crossoverSite.wiki_display_name + '](' + crossover[1] + ')', true );
  4753. else embed.addField( crossover[0], crossover[1], true );
  4754. }
  4755. if ( description[1] ) embed.addField( description[0], description[1] );
  4756. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4757. }
  4758. else {
  4759. text += '\n' + founder.join(' ') + ( manager[1] ? '\n' + manager.join(' ') : '' ) + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4760. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4761. if ( description[1] ) text += '\n' + description.join(' ');
  4762. if ( image[1] ) {
  4763. text += '\n' + image.join(' ');
  4764. if ( msg.uploadFiles() ) embed.files = [image[1]];
  4765. }
  4766. text += '\n\n*' + lang.overview.inaccurate + '*';
  4767. }
  4768. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4769. if ( reaction ) reaction.removeEmoji();
  4770. } );
  4771. else {
  4772. founder[1] = lang.overview.none;
  4773. if ( msg.showEmbed() ) {
  4774. 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 );
  4775. if ( crossover[1] ) {
  4776. var crossoverSite = allSites.find( site => '<https://' + site.wiki_domain + '/>' === crossover[1] );
  4777. if ( crossoverSite ) embed.addField( crossover[0], '[' + crossoverSite.wiki_display_name + '](' + crossover[1] + ')', true );
  4778. else embed.addField( crossover[0], crossover[1], true );
  4779. }
  4780. if ( description[1] ) embed.addField( description[0], description[1] );
  4781. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4782. }
  4783. else {
  4784. text += '\n' + founder.join(' ') + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4785. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4786. if ( description[1] ) text += '\n' + description.join(' ');
  4787. if ( image[1] ) {
  4788. text += '\n' + image.join(' ');
  4789. if ( msg.uploadFiles() ) embed.files = [image[1]];
  4790. }
  4791. text += '\n\n*' + lang.overview.inaccurate + '*';
  4792. }
  4793. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4794. if ( reaction ) reaction.removeEmoji();
  4795. }
  4796. }
  4797. }, error => {
  4798. console.log( '- Error while getting the wiki details: ' + error );
  4799. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4800. if ( reaction ) reaction.removeEmoji();
  4801. } );
  4802. }, error => {
  4803. if ( wiki.noWiki(error.message) ) {
  4804. console.log( '- This wiki doesn\'t exist!' );
  4805. msg.reactEmoji('nowiki');
  4806. }
  4807. else {
  4808. console.log( '- Error while getting the statistics: ' + error );
  4809. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4810. }
  4811. if ( reaction ) reaction.removeEmoji();
  4812. } );
  4813. }
  4814. function minecraft_bug(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4815. var invoke = args[0];
  4816. args = args.slice(1);
  4817. if ( invoke && /\d+$/.test(invoke) && !args.length ) {
  4818. if ( /^\d+$/.test(invoke) ) invoke = 'MC-' + invoke;
  4819. var link = 'https://bugs.mojang.com/browse/';
  4820. got.get( 'https://bugs.mojang.com/rest/api/2/issue/' + encodeURIComponent( invoke ) + '?fields=summary,issuelinks,fixVersions,resolution,status', {
  4821. responseType: 'json'
  4822. } ).then( response => {
  4823. var body = response.body;
  4824. if ( response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  4825. if ( body && body.errorMessages ) {
  4826. if ( body.errorMessages.includes( 'Issue Does Not Exist' ) ) {
  4827. msg.reactEmoji('🤷');
  4828. }
  4829. else if ( body.errorMessages.includes( 'You do not have the permission to see the specified issue.' ) ) {
  4830. msg.sendChannel( spoiler + mclang.bug.private + '\n<' + link + invoke + '>' + spoiler );
  4831. }
  4832. else {
  4833. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + body.errorMessages.join(' - ') );
  4834. msg.reactEmoji('error');
  4835. }
  4836. }
  4837. else {
  4838. console.log( '- ' + response.statusCode + ': Error while getting the issue: ' + ( body && body.message ) );
  4839. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  4840. else msg.sendChannelError( spoiler + '<' + link + invoke + '>' + spoiler );
  4841. }
  4842. }
  4843. else {
  4844. if ( !body.fields ) {
  4845. msg.reactEmoji('error');
  4846. }
  4847. else {
  4848. var bugs = body.fields.issuelinks.filter( bug => bug.outwardIssue || ( bug.inwardIssue && bug.type.name != 'Duplicate' ) );
  4849. if ( bugs.length ) {
  4850. var embed = new Discord.MessageEmbed();
  4851. var extrabugs = [];
  4852. bugs.forEach( bug => {
  4853. var ward = ( bug.outwardIssue ? 'outward' : 'inward' );
  4854. var issue = bug[ward + 'Issue'];
  4855. var name = bug.type[ward] + ' ' + issue.key;
  4856. var value = issue.fields.status.name + ': [' + issue.fields.summary.escapeFormatting() + '](' + link + issue.key + ')';
  4857. if ( embed.fields.length < 25 ) embed.addField( name, value );
  4858. else extrabugs.push({name,value,inline:false});
  4859. } );
  4860. if ( extrabugs.length ) embed.setFooter( mclang.bug.more.replaceSave( '%s', extrabugs.length ) );
  4861. }
  4862. var status = '**' + ( body.fields.resolution ? body.fields.resolution.name : body.fields.status.name ) + ':** ';
  4863. var fixed = '';
  4864. if ( body.fields.resolution && body.fields.fixVersions && body.fields.fixVersions.length ) {
  4865. fixed = '\n' + mclang.bug.fixed + ' ' + body.fields.fixVersions.map( v => v.name ).join(', ');
  4866. }
  4867. msg.sendChannel( spoiler + status + body.fields.summary.escapeFormatting() + '\n<' + link + body.key + '>' + fixed + spoiler, {embed} );
  4868. }
  4869. }
  4870. }, error => {
  4871. console.log( '- Error while getting the issue: ' + error );
  4872. msg.sendChannelError( spoiler + '<' + link + invoke + '>' + spoiler );
  4873. } ).finally( () => {
  4874. if ( reaction ) reaction.removeEmoji();
  4875. } );
  4876. }
  4877. else if ( invoke && invoke.toLowerCase() === 'version' && args.length && args.join(' ').length < 100 ) {
  4878. var jql = 'fixVersion="' + args.join(' ').replace( /(["\\])/g, '\\$1' ).toSearch() + '"+order+by+key';
  4879. var link = 'https://bugs.mojang.com/issues/?jql=' + jql;
  4880. got.get( 'https://bugs.mojang.com/rest/api/2/search?fields=summary,resolution,status&jql=' + jql + '&maxResults=25', {
  4881. responseType: 'json'
  4882. } ).then( response => {
  4883. var body = response.body;
  4884. if ( response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  4885. if ( body && body.errorMessages ) {
  4886. if ( body.errorMessages.includes( 'The value \'' + args.join(' ') + '\' does not exist for the field \'fixVersion\'.' ) ) {
  4887. msg.reactEmoji('🤷');
  4888. }
  4889. else {
  4890. console.log( '- ' + response.statusCode + ': Error while getting the issues: ' + body.errorMessages.join(' - ') );
  4891. msg.reactEmoji('error');
  4892. }
  4893. }
  4894. else {
  4895. console.log( '- ' + response.statusCode + ': Error while getting the issues: ' + ( body && body.message ) );
  4896. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  4897. else msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  4898. }
  4899. }
  4900. else {
  4901. if ( !body.issues ) {
  4902. msg.reactEmoji('error');
  4903. }
  4904. else {
  4905. if ( body.total > 0 ) {
  4906. var embed = new Discord.MessageEmbed();
  4907. body.issues.forEach( bug => {
  4908. var status = ( bug.fields.resolution ? bug.fields.resolution.name : bug.fields.status.name );
  4909. var value = status + ': [' + bug.fields.summary.escapeFormatting() + '](https://bugs.mojang.com/browse/' + bug.key + ')';
  4910. embed.addField( bug.key, value );
  4911. } );
  4912. if ( body.total > 25 ) embed.setFooter( mclang.bug.more.replaceSave( '%s', body.total - 25 ) );
  4913. }
  4914. var total = '**' + args.join(' ') + ':** ' + mclang.bug.total.replaceSave( '%s', body.total );
  4915. msg.sendChannel( spoiler + total + '\n<' + link + '>' + spoiler, {embed} );
  4916. }
  4917. }
  4918. }, error => {
  4919. console.log( '- Error while getting the issues: ' + error );
  4920. msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  4921. } ).finally( () => {
  4922. if ( reaction ) reaction.removeEmoji();
  4923. } );
  4924. }
  4925. else {
  4926. msg.notminecraft = true;
  4927. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4928. }
  4929. }
  4930. function minecraft_command(lang, mclang, msg, befehl, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4931. befehl = befehl.toLowerCase();
  4932. var aliasCmd = ( minecraft.cmd.aliases[befehl] || befehl );
  4933. if ( aliasCmd in minecraft.cmd.list ) {
  4934. var cmdSyntaxMap = minecraft.cmd.list[aliasCmd].map( command => {
  4935. var cmdargs = command.split(' ');
  4936. if ( cmdargs[0].startsWith( '/' ) ) cmdargs = cmdargs.slice(1);
  4937. var argmatches = cmdargs.map( (arg, i) => {
  4938. if ( arg === args[i] ) return true;
  4939. } );
  4940. var matchCount = 0;
  4941. argmatches.forEach( match => {
  4942. if ( match ) matchCount++;
  4943. } );
  4944. return [argmatches.lastIndexOf(true),matchCount];
  4945. } );
  4946. var lastIndex = Math.max(...cmdSyntaxMap.map( command => command[0] ));
  4947. var matchCount = Math.max(...cmdSyntaxMap.filter( command => command[0] === lastIndex ).map( command => command[1] ));
  4948. var regex = new RegExp('/' + aliasCmd, 'g');
  4949. var cmdSyntax = minecraft.cmd.list[aliasCmd].filter( (command, i) => ( lastIndex === -1 || cmdSyntaxMap[i][0] === lastIndex ) && cmdSyntaxMap[i][1] === matchCount ).join('\n').replaceSave( regex, '/' + befehl );
  4950. msg.sendChannel( spoiler + '```md\n' + cmdSyntax + '```<' + mclang.link + mclang.cmd.page + aliasCmd + '>' + spoiler, {split:{maxLength:2000,prepend:spoiler + '```md\n',append:'```' + spoiler}} );
  4951. if ( reaction ) reaction.removeEmoji();
  4952. }
  4953. else {
  4954. msg.reactEmoji('❓');
  4955. msg.notminecraft = true;
  4956. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4957. }
  4958. }
  4959. function minecraft_command2(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4960. if ( args.join('') ) {
  4961. if ( args[0].startsWith( '/' ) ) minecraft_command(lang, mclang, msg, args[0].substring(1), args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  4962. else minecraft_command(lang, mclang, msg, args[0], args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  4963. }
  4964. else {
  4965. msg.notminecraft = true;
  4966. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4967. }
  4968. }
  4969. async function cmd_get(lang, msg, args, line, wiki) {
  4970. var id = args.join().replace( /^\\?<(?:@!?|#)(\d+)>$/, '$1' );
  4971. if ( /^\d+$/.test(id) ) {
  4972. var guild = await client.shard.broadcastEval( `if ( this.guilds.cache.has('${id}') ) {
  4973. var {name, id, memberCount, ownerID, owner, me: {permissions}} = this.guilds.cache.get('${id}');
  4974. ( {
  4975. name, id, memberCount, ownerID,
  4976. owner: owner?.user.tag,
  4977. permissions: permissions.missing(${defaultPermissions}),
  4978. pause: id in global.pause,
  4979. voice: id in global.voice,
  4980. shardId: global.shardId
  4981. } )
  4982. }` ).then( results => results.find( result => result !== null ) );
  4983. if ( guild ) {
  4984. var guildname = ['Guild:', guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( guild.pause ? '\\*' : '' )];
  4985. var guildowner = ['Owner:', ( guild.owner ? guild.owner.escapeFormatting() + ' ' : '' ) + '`' + guild.ownerID + '` <@' + guild.ownerID + '>'];
  4986. var guildsize = ['Size:', guild.memberCount + ' members'];
  4987. var guildshard = ['Shard:', guild.shardId];
  4988. var guildpermissions = ['Missing permissions:', ( guild.permissions.length ? '`' + guild.permissions.join('`, `') + '`' : '*none*' )];
  4989. var guildsettings = ['Settings:', '*unknown*'];
  4990. return db.all( 'SELECT channel, prefix, lang, wiki, inline FROM discord WHERE guild = ? ORDER BY channel ASC', [guild.id], (dberror, rows) => {
  4991. if ( dberror ) {
  4992. console.log( '- Error while getting the settings: ' + dberror );
  4993. }
  4994. else if ( rows.length ) {
  4995. row = rows.find( row => !row.channel );
  4996. row.patreon = guild.id in patreons;
  4997. row.voice = guild.voice;
  4998. guildsettings[1] = '```json\n' + JSON.stringify( rows, null, '\t' ) + '\n```';
  4999. }
  5000. else guildsettings[1] = '*default*';
  5001. if ( msg.showEmbed() ) {
  5002. var embed = new Discord.MessageEmbed().addField( guildname[0], guildname[1] ).addField( guildowner[0], guildowner[1] ).addField( guildsize[0], guildsize[1], true ).addField( guildshard[0], guildshard[1], true ).addField( guildpermissions[0], guildpermissions[1] );
  5003. var split = Discord.Util.splitMessage( guildsettings[1], {char:',\n',maxLength:1000,prepend:'```json\n',append:',\n```'} );
  5004. if ( split.length > 5 ) {
  5005. msg.sendChannel( '', {embed}, true );
  5006. msg.sendChannel( guildsettings.join(' '), {split:{char:',\n',prepend:'```json\n',append:',\n```'}}, true );
  5007. }
  5008. else {
  5009. split.forEach( guildsettingspart => embed.addField( guildsettings[0], guildsettingspart ) );
  5010. msg.sendChannel( '', {embed}, true );
  5011. }
  5012. }
  5013. else {
  5014. var text = guildname.join(' ') + '\n' + guildowner.join(' ') + '\n' + guildsize.join(' ') + '\n' + guildshard.join(' ') + '\n' + guildpermissions.join(' ') + '\n' + guildsettings.join(' ');
  5015. msg.sendChannel( text, {split:{char:',\n',prepend:'```json\n',append:',\n```'}}, true );
  5016. }
  5017. } );
  5018. }
  5019. var channel = await client.shard.broadcastEval( `if ( this.channels.cache.filter( channel => channel.type === 'text' ).has('${id}') ) {
  5020. var {name, id, guild: {name: guild, id: guildID, me}} = this.channels.cache.get('${id}');
  5021. ( {
  5022. name, id, guild, guildID,
  5023. permissions: me.permissionsIn(id).missing(${defaultPermissions}),
  5024. pause: guildID in global.pause,
  5025. shardId: global.shardId
  5026. } )
  5027. }` ).then( results => results.find( result => result !== null ) );
  5028. if ( channel ) {
  5029. var channelguild = ['Guild:', channel.guild.escapeFormatting() + ' `' + channel.guildID + '`' + ( channel.pause ? '\\*' : '' )];
  5030. var channelname = ['Channel:', '#' + channel.name.escapeFormatting() + ' `' + channel.id + '` <#' + channel.id + '>'];
  5031. var channelpermissions = ['Missing permissions:', ( channel.permissions.length ? '`' + channel.permissions.join('`, `') + '`' : '*none*' )];
  5032. var channellang = ['Language:', '*unknown*'];
  5033. var channelwiki = ['Default Wiki:', '*unknown*'];
  5034. var channelinline = ['Inline commands:', '*unknown*'];
  5035. return db.get( 'SELECT lang, wiki, inline FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [channel.guildID, channel.id], (dberror, row) => {
  5036. if ( dberror ) {
  5037. console.log( '- Error while getting the settings: ' + dberror );
  5038. }
  5039. else if ( row ) {
  5040. channellang[1] = row.lang;
  5041. channelwiki[1] = row.wiki;
  5042. channelinline[1] = ( row.inline ? 'disabled' : 'enabled' );
  5043. }
  5044. else {
  5045. channellang[1] = defaultSettings.lang;
  5046. channelwiki[1] = defaultSettings.wiki;
  5047. channelinline[1] = 'enabled';
  5048. }
  5049. if ( msg.showEmbed() ) {
  5050. var text = '';
  5051. 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] );
  5052. }
  5053. else {
  5054. var embed = {};
  5055. var text = channelguild.join(' ') + '\n' + channelname.join(' ') + '\n' + channelpermissions.join(' ') + '\n' + channellang.join(' ') + '\n' + channelwiki[0] + ' <' + channelwiki[1] + '>\n' + channelinline.join(' ');
  5056. }
  5057. msg.sendChannel( text, {embed}, true );
  5058. } );
  5059. }
  5060. var user = await client.users.fetch(id, false).catch( () => {} );
  5061. if ( user ) {
  5062. var username = ['User:', user.tag.escapeFormatting() + ' `' + user.id + '` <@' + user.id + '>'];
  5063. var guildlist = ['Guilds:', '*none*'];
  5064. var guilds = await client.shard.broadcastEval( `this.guilds.cache.filter( guild => guild.members.cache.has('${user.id}') ).map( guild => {
  5065. var member = guild.members.cache.get('${user.id}');
  5066. return {
  5067. name: guild.name,
  5068. id: guild.id,
  5069. isAdmin: member.permissions.has('MANAGE_GUILD'),
  5070. shardId: global.shardId
  5071. }
  5072. } )` ).then( results => results.reduce( (acc, val) => acc.concat(val), [] ).map( user_guild => {
  5073. return user_guild.name.escapeFormatting() + ' `' + user_guild.id + '`' + ( user_guild.isAdmin ? '\\*' : '' );
  5074. } ) );
  5075. if ( guilds.length ) guildlist[1] = guilds.join('\n');
  5076. if ( guildlist[1].length > 1000 ) guildlist[1] = guilds.length;
  5077. if ( msg.showEmbed() ) {
  5078. var text = '';
  5079. var embed = new Discord.MessageEmbed().addField( username[0], username[1] ).addField( guildlist[0], guildlist[1] );
  5080. }
  5081. else {
  5082. var embed = {};
  5083. var text = username.join(' ') + '\n' + guildlist.join('\n');
  5084. }
  5085. return msg.sendChannel( text, {embed}, true );
  5086. }
  5087. msg.replyMsg( 'I couldn\'t find a result for `' + id + '`', {}, true );
  5088. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  5089. }
  5090. function cmd_patreon(lang, msg, args, line, wiki) {
  5091. if ( msg.channel.id !== process.env.channel || !args.join('') ) {
  5092. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  5093. return;
  5094. }
  5095. if ( args[0] === 'enable' && /^\d+$/.test(args.slice(1).join(' ')) ) return client.shard.broadcastEval( `this.guilds.cache.get('${args[1]}')?.name` ).then( results => {
  5096. var guild = results.find( result => result !== null );
  5097. if ( guild === undefined ) return msg.replyMsg( 'I\'m not on a server with the id `' + args[1] + '`.', {}, true );
  5098. if ( args[1] in patreons ) return msg.replyMsg( '"' + guild + '" has the patreon features already enabled.', {}, true );
  5099. 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) => {
  5100. if ( dberror ) {
  5101. console.log( '- Error while getting the patreon: ' + dberror );
  5102. msg.replyMsg( 'I got an error while searching for you, please try again later.', {}, true );
  5103. return dberror;
  5104. }
  5105. if ( !row ) return msg.replyMsg( 'you can\'t have any server.', {}, true );
  5106. if ( row.count <= row.guilds ) return msg.replyMsg( 'you already reached your maximal server count.', {}, true );
  5107. db.run( 'UPDATE discord SET patreon = ? WHERE guild = ? AND channel IS NULL', [msg.author.id, args[1]], function (error) {
  5108. if ( error ) {
  5109. console.log( '- Error while updating the guild: ' + error );
  5110. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  5111. return error;
  5112. }
  5113. if ( !this.changes ) return db.run( 'INSERT INTO discord(guild, patreon) VALUES(?, ?)', [args[1], msg.author.id], function (inserror) {
  5114. if ( inserror ) {
  5115. console.log( '- Error while adding the guild: ' + inserror );
  5116. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  5117. return inserror;
  5118. }
  5119. console.log( '- Guild successfully added.' );
  5120. client.shard.broadcastEval( `global.patreons['${args[1]}'] = '${process.env.prefix}'` );
  5121. msg.replyMsg( 'the patreon features are now enabled on "' + guild + '".', {}, true );
  5122. } );
  5123. console.log( '- Guild successfully updated.' );
  5124. client.shard.broadcastEval( `global.patreons['${args[1]}'] = '${process.env.prefix}'` );
  5125. msg.replyMsg( 'the patreon features are now enabled on "' + guild + '".', {}, true );
  5126. } );
  5127. } );
  5128. } );
  5129. if ( args[0] === 'disable' && /^\d+$/.test(args.slice(1).join(' ')) ) return client.shard.broadcastEval( `this.guilds.cache.get('${args[1]}')?.name` ).then( results => {
  5130. var guild = results.find( result => result !== null );
  5131. if ( guild === undefined ) return msg.replyMsg( 'I\'m not on a server with the id `' + args[1] + '`.', {}, true );
  5132. if ( !( args[1] in patreons ) ) return msg.replyMsg( '"' + guild + '" doesn\'t have the patreon features enabled.', {}, true );
  5133. db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND patreon = ?', [args[1], msg.author.id], (dberror, row) => {
  5134. if ( dberror ) {
  5135. console.log( '- Error while getting the guild: ' + dberror );
  5136. msg.replyMsg( 'I got an error while searching for the server, please try again later.', {}, true );
  5137. return dberror;
  5138. }
  5139. if ( !row ) return msg.replyMsg( 'you didn\'t enable the patreon features for "' + guild + '"!', {}, true );
  5140. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, args[1]], function (error) {
  5141. if ( error ) {
  5142. console.log( '- Error while updating the guild: ' + error );
  5143. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  5144. return error;
  5145. }
  5146. console.log( '- Guild successfully updated.' );
  5147. client.shard.broadcastEval( `delete global.patreons['${args[1]}']` );
  5148. msg.replyMsg( 'the patreon features are now disabled on "' + guild + '".', {}, true );
  5149. } );
  5150. } );
  5151. } );
  5152. if ( args[1] ) args[1] = args[1].replace( /^\\?<@!?(\d+)>$/, '$1' );
  5153. if ( args[0] === 'check' ) {
  5154. 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) => {
  5155. if ( dberror ) {
  5156. console.log( '- Error while getting the patreon: ' + dberror );
  5157. msg.replyMsg( 'I got an error while searching for you, please try again later.', {}, true );
  5158. return dberror;
  5159. }
  5160. if ( !row ) return msg.replyMsg( 'you can\'t have any server.', {}, true );
  5161. var text = 'you can have up to ' + row.count + ' server.\n\n';
  5162. if ( row.guilds ) {
  5163. client.shard.broadcastEval( `'${row.guilds}'.split(',').map( guild => this.guilds.cache.get(guild)?.name )` ).then( results => {
  5164. var guilds = row.guilds.split(',').map( (guild, i) => '`' + guild + '` ' + ( results.find( result => result[i] !== null )?.[i] || '' ) );
  5165. text += 'Currently you have ' + guilds.length + ' server:\n' + guilds.join('\n');
  5166. msg.replyMsg( text, {}, true );
  5167. } );
  5168. }
  5169. else {
  5170. text += '*You don\'t have any server yet.*';
  5171. msg.replyMsg( text, {}, true );
  5172. }
  5173. } );
  5174. 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) => {
  5175. if ( dberror ) {
  5176. console.log( '- Error while getting the patreon: ' + dberror );
  5177. msg.replyMsg( 'I got an error while searching for <@' + args[1] + '>, please try again later.', {}, true );
  5178. return dberror;
  5179. }
  5180. if ( !row ) return msg.replyMsg( '<@' + args[1] + '> can\'t have any server.', {}, true );
  5181. var text = '<@' + args[1] + '> can have up to ' + row.count + ' server.\n\n';
  5182. if ( row.guilds ) {
  5183. client.shard.broadcastEval( `'${row.guilds}'.split(',').map( guild => this.guilds.cache.get(guild)?.name )` ).then( results => {
  5184. var guilds = row.guilds.split(',').map( (guild, i) => '`' + guild + '` ' + ( results.find( result => result[i] !== null )?.[i] || '' ) );
  5185. text += 'Currently they have ' + guilds.length + ' server:\n' + guilds.join('\n');
  5186. msg.replyMsg( text, {}, true );
  5187. } );
  5188. }
  5189. else {
  5190. text += '*They don\'t have any server yet.*';
  5191. msg.replyMsg( text, {}, true );
  5192. }
  5193. } );
  5194. }
  5195. 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) => {
  5196. if ( dberror ) {
  5197. console.log( '- Error while getting the patreon: ' + dberror );
  5198. msg.replyMsg( 'I got an error while searching for <@' + args[1] + '>, please try again later.', {}, true );
  5199. return dberror;
  5200. }
  5201. var value = parseInt(args[2], 10);
  5202. var count = ( row ? row.count : 0 );
  5203. var guilds = ( row && row.guilds ? row.guilds.split(',') : [] );
  5204. if ( args[2].startsWith( '+' ) || args[2].startsWith( '-' ) ) count += value;
  5205. else count = value;
  5206. if ( count <= 0 ) return db.run( 'DELETE FROM patreons WHERE patreon = ?', [args[1]], function (error) {
  5207. if ( error ) {
  5208. console.log( '- Error while deleting the patreon: ' + error );
  5209. msg.replyMsg( 'I got an error while deleting <@' + args[1] + '>, please try again later.', {}, true );
  5210. return error;
  5211. }
  5212. console.log( '- Patreon successfully deleted.' );
  5213. if ( !guilds.length ) return msg.replyMsg( '<@' + args[1] + '> is no longer a patreon.', {}, true );
  5214. db.each( 'SELECT guild, lang, inline FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ') AND channel IS NULL', guilds, (eacherror, eachrow) => {
  5215. if ( eacherror ) {
  5216. console.log( '- Error while getting the guild: ' + eacherror );
  5217. msg.replyMsg( 'I couldn\'t disable the patreon features.', {}, true );
  5218. return eacherror;
  5219. }
  5220. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ? WHERE guild = ?', [eachrow.lang, eachrow.inline, process.env.prefix, eachrow.guild], function (uperror) {
  5221. if ( uperror ) {
  5222. console.log( '- Error while updating the guild: ' + uperror );
  5223. msg.replyMsg( 'I couldn\'t disable the patreon features for `' + eachrow.guild + '`.', {}, true );
  5224. return uperror;
  5225. }
  5226. console.log( '- Guild successfully updated.' );
  5227. client.shard.broadcastEval( `delete global.patreons['${eachrow.guild}']` );
  5228. } );
  5229. }, (eacherror) => {
  5230. if ( eacherror ) {
  5231. console.log( '- Error while getting the guilds: ' + eacherror );
  5232. msg.replyMsg( 'I couldn\'t disable the patreon features for `' + guilds.join('`, `') + '`.', {}, true );
  5233. return eacherror;
  5234. }
  5235. msg.replyMsg( '<@' + args[1] + '> is no longer a patreon.', {}, true );
  5236. } );
  5237. } );
  5238. if ( !row ) return db.run( 'INSERT INTO patreons(patreon, count) VALUES(?, ?)', [args[1], count], function (error) {
  5239. if ( error ) {
  5240. console.log( '- Error while adding the patreon: ' + error );
  5241. msg.replyMsg( 'I got an error while adding <@' + args[1] + '>, please try again later.', {}, true );
  5242. return error;
  5243. }
  5244. console.log( '- Patreon successfully added.' );
  5245. msg.replyMsg( '<@' + args[1] + '> can now have up to ' + count + ' server.', {}, true );
  5246. } );
  5247. db.run( 'UPDATE patreons SET count = ? WHERE patreon = ?', [count, args[1]], function (error) {
  5248. if ( error ) {
  5249. console.log( '- Error while updating the patreon: ' + error );
  5250. msg.replyMsg( 'I got an error while updating <@' + args[1] + '>, please try again later.', {}, true );
  5251. return error;
  5252. }
  5253. console.log( '- Patreon successfully updated.' );
  5254. var text = '<@' + args[1] + '> can now have up to ' + count + ' server.';
  5255. if ( count < guilds.length ) text += '\n\n**They are now above their server limit!**';
  5256. msg.replyMsg( text, {}, true );
  5257. } );
  5258. } );
  5259. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  5260. }
  5261. function discussion_formatting(jsonModel) {
  5262. var description = '';
  5263. switch ( jsonModel.type ) {
  5264. case 'doc':
  5265. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  5266. break;
  5267. case 'paragraph':
  5268. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  5269. description += '\n';
  5270. break;
  5271. case 'openGraph':
  5272. if ( !jsonModel.attrs.wasAddedWithInlineLink ) description += jsonModel.attrs.url + '\n';
  5273. break;
  5274. case 'text':
  5275. var prepend = '';
  5276. var append = '';
  5277. if ( jsonModel.marks ) {
  5278. jsonModel.marks.forEach( mark => {
  5279. switch ( mark.type ) {
  5280. case 'mention':
  5281. prepend += '[';
  5282. append = ']({@wiki}f/u/' + mark.attrs.userId + ')' + append;
  5283. break;
  5284. case 'link':
  5285. prepend += '[';
  5286. append = '](' + mark.attrs.href + ')' + append;
  5287. break;
  5288. case 'strong':
  5289. prepend += '**';
  5290. append = '**' + append;
  5291. break;
  5292. case 'em':
  5293. prepend += '_';
  5294. append = '_' + append;
  5295. break;
  5296. }
  5297. } );
  5298. }
  5299. description += prepend + jsonModel.text.escapeFormatting() + append;
  5300. break;
  5301. case 'image':
  5302. if ( jsonModel.attrs.id !== null ) description += '{@' + jsonModel.attrs.id + '}\n';
  5303. break;
  5304. case 'code_block':
  5305. description += '```\n';
  5306. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  5307. description += '\n```\n';
  5308. break;
  5309. case 'bulletList':
  5310. jsonModel.content.forEach( listItem => {
  5311. description += '\t• ';
  5312. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  5313. } );
  5314. break;
  5315. case 'orderedList':
  5316. var n = 1;
  5317. jsonModel.content.forEach( listItem => {
  5318. description += '\t' + n + '. ';
  5319. n++;
  5320. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  5321. } );
  5322. break;
  5323. }
  5324. return description;
  5325. }
  5326. function htmlToPlain(html) {
  5327. var text = '';
  5328. var parser = new htmlparser.Parser( {
  5329. ontext: (htmltext) => {
  5330. text += htmltext.escapeFormatting();
  5331. }
  5332. }, {decodeEntities:true} );
  5333. parser.write( html );
  5334. parser.end();
  5335. return text;
  5336. };
  5337. function htmlToDiscord(html) {
  5338. var text = '';
  5339. var parser = new htmlparser.Parser( {
  5340. onopentag: (tagname, attribs) => {
  5341. switch (tagname) {
  5342. case 'b':
  5343. text += '**';
  5344. break;
  5345. case 'i':
  5346. text += '*';
  5347. break;
  5348. case 's':
  5349. text += '~~';
  5350. break;
  5351. case 'u':
  5352. text += '__';
  5353. break;
  5354. }
  5355. },
  5356. ontext: (htmltext) => {
  5357. text += htmltext.escapeFormatting();
  5358. },
  5359. onclosetag: (tagname) => {
  5360. switch (tagname) {
  5361. case 'b':
  5362. text += '**';
  5363. break;
  5364. case 'i':
  5365. text += '*';
  5366. break;
  5367. case 's':
  5368. text += '~~';
  5369. break;
  5370. case 'u':
  5371. text += '__';
  5372. break;
  5373. }
  5374. }
  5375. }, {decodeEntities:true} );
  5376. parser.write( html );
  5377. parser.end();
  5378. return text;
  5379. };
  5380. String.prototype.noWiki = function(href) {
  5381. if ( !href ) return false;
  5382. else if ( this.startsWith( 'https://www.' ) ) return true;
  5383. else if ( this.endsWith( '.gamepedia.com/' ) ) return 'https://www.gamepedia.com/' === href;
  5384. else return [
  5385. 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' ),
  5386. this + 'language-wikis'
  5387. ].includes( href.replace( /Unexpected token < in JSON at position 0 in "([^ ]+)"/, '$1' ) );
  5388. };
  5389. String.prototype.isFandom = function() {
  5390. return /^https:\/\/[a-z\d-]{1,50}\.(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?$/.test(this);
  5391. };
  5392. String.prototype.isMention = function(guild) {
  5393. var text = this.trim();
  5394. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  5395. };
  5396. Discord.Message.prototype.isAdmin = function() {
  5397. return this.channel.type === 'text' && this.member && ( this.member.permissions.has('MANAGE_GUILD') || ( this.isOwner() && this.evalUsed ) );
  5398. };
  5399. Discord.Message.prototype.isOwner = function() {
  5400. return this.author.id === process.env.owner;
  5401. };
  5402. Discord.Message.prototype.showEmbed = function() {
  5403. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  5404. };
  5405. Discord.Message.prototype.uploadFiles = function() {
  5406. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  5407. };
  5408. String.prototype.toLink = function(title = '', querystring = '', fragment = '', path, isMarkdown = false) {
  5409. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment.toSection() : '' );
  5410. 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 );
  5411. else if ( this.endsWith( '.gamepedia.com/' ) ) return this + title.toTitle(isMarkdown) + linksuffix;
  5412. else if ( this.isFandom() ) return this + 'wiki/' + title.toTitle(isMarkdown) + linksuffix;
  5413. else return this + 'index.php?title=' + title.toTitle(isMarkdown, true) + ( linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  5414. };
  5415. String.prototype.toDescLink = function(title = '') {
  5416. return this + 'wiki/' + encodeURIComponent( title.replace( / /g, '_' ) );
  5417. };
  5418. String.prototype.toTitle = function(isMarkdown = false, inQuery = false) {
  5419. var title = this.replace( / /g, '_' ).replace( /\%/g, '%25' ).replace( /\\/g, '%5C' ).replace( /\?/g, '%3F' ).replace( /@(here|everyone)/g, '%40$1' );
  5420. if ( inQuery ) title = title.replace( /\&/g, '%26' );
  5421. if ( isMarkdown ) title = title.replace( /([\(\)])/g, '\\$1' );
  5422. return title;
  5423. };
  5424. String.prototype.toSearch = function() {
  5425. return encodeURIComponent( this ).replace( /%20/g, '+' );
  5426. };
  5427. String.prototype.toSection = function() {
  5428. return encodeURIComponent( this.replace( / /g, '_' ) ).replace( /\'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\%/g, '.' );
  5429. };
  5430. String.prototype.toFormatting = function(showEmbed = false, ...args) {
  5431. if ( showEmbed ) return this.toMarkdown(...args);
  5432. else return this.toPlaintext();
  5433. };
  5434. String.prototype.toMarkdown = function(wiki, path, title = '') {
  5435. var text = this.replace( /[\(\)\\]/g, '\\$&' );
  5436. var link = null;
  5437. while ( ( link = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g.exec(text) ) !== null ) {
  5438. var pagetitle = ( link[1] || link[2] );
  5439. var page = wiki.toLink(( /^[#\/]/.test(pagetitle) ? title + ( pagetitle.startsWith( '/' ) ? pagetitle : '' ) : pagetitle ), '', ( pagetitle.startsWith( '#' ) ? pagetitle.substring(1) : '' ), path, true);
  5440. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + page + ')' );
  5441. }
  5442. while ( title !== '' && ( link = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g.exec(text) ) !== null ) {
  5443. text = text.replaceSave( link[0], '[→' + link[1] + '](' + wiki.toLink(title, '', link[1], path, true) + ')' + ( link[2] ? ': ' + link[2] : '' ) );
  5444. }
  5445. return text.escapeFormatting(true);
  5446. };
  5447. String.prototype.toPlaintext = function() {
  5448. return this.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' ).escapeFormatting();
  5449. };
  5450. String.prototype.escapeFormatting = function(isMarkdown) {
  5451. var text = this;
  5452. if ( !isMarkdown ) text = text.replace( /[\(\)\\]/g, '\\$&' );
  5453. return text.replace( /[`_\*~:<>{}@\|]|\/\//g, '\\$&' );
  5454. };
  5455. String.prototype.replaceSave = function(pattern, replacement) {
  5456. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  5457. };
  5458. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  5459. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  5460. var emoji = '440871715938238494';
  5461. switch ( name ) {
  5462. case 'nowiki':
  5463. emoji = ':unknown_wiki:505884572001763348';
  5464. break;
  5465. case 'error':
  5466. emoji = ':error:440871715938238494';
  5467. break;
  5468. default:
  5469. emoji = name;
  5470. }
  5471. return this.react(emoji).catch(log_error);
  5472. } else {
  5473. console.log( '- Aborted, paused.' );
  5474. return Promise.resolve();
  5475. }
  5476. };
  5477. Discord.MessageReaction.prototype.removeEmoji = function() {
  5478. return this.users.remove().catch(log_error);
  5479. };
  5480. Discord.Message.prototype.sendChannel = function(content, options = {}, ignorePause = false) {
  5481. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  5482. if ( !options.allowedMentions ) options.allowedMentions = {parse:[]};
  5483. return this.channel.send(content, options).then( msg => {
  5484. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  5485. else msg.allowDelete(this.author.id);
  5486. return msg;
  5487. }, log_error );
  5488. } else {
  5489. console.log( '- Aborted, paused.' );
  5490. return Promise.resolve();
  5491. }
  5492. };
  5493. Discord.Message.prototype.sendChannelError = function(content, options = {}) {
  5494. if ( !options.allowedMentions ) options.allowedMentions = {parse:[]};
  5495. return this.channel.send(content, options).then( msg => {
  5496. if ( msg.length ) msg.forEach( message => {
  5497. message.reactEmoji('error');
  5498. message.allowDelete(this.author.id);
  5499. } );
  5500. else {
  5501. msg.reactEmoji('error');
  5502. msg.allowDelete(this.author.id);
  5503. }
  5504. return msg;
  5505. }, log_error );
  5506. };
  5507. Discord.Message.prototype.replyMsg = function(content, options = {}, ignorePause = false, allowDelete = true) {
  5508. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  5509. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  5510. return this.reply(content, options).then( msg => {
  5511. if ( allowDelete ) {
  5512. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  5513. else msg.allowDelete(this.author.id);
  5514. }
  5515. return msg;
  5516. }, log_error );
  5517. } else {
  5518. console.log( '- Aborted, paused.' );
  5519. return Promise.resolve();
  5520. }
  5521. };
  5522. Discord.Message.prototype.deleteMsg = function(timeout = 0) {
  5523. return this.delete({timeout}).catch(log_error);
  5524. };
  5525. Discord.Message.prototype.allowDelete = function(author) {
  5526. return this.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:120000} ).then( reaction => {
  5527. if ( reaction.size ) {
  5528. this.deleteMsg();
  5529. }
  5530. } );
  5531. };
  5532. String.prototype.hasPrefix = function(prefix, flags = '') {
  5533. return new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + '(?: |$)', flags ).test(this.replace( /\u200b/g, '' ).toLowerCase());
  5534. };
  5535. client.on( 'message', msg => {
  5536. if ( stop || msg.type !== 'DEFAULT' || msg.system || msg.webhookID || msg.author.id === client.user.id ) return;
  5537. if ( !msg.content.hasPrefix(( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  5538. if ( msg.content === process.env.prefix + ' help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  5539. if ( msg.channel.permissionsFor(client.user).has('SEND_MESSAGES') ) {
  5540. console.log( msg.guild.name + ': ' + msg.content );
  5541. 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) => {
  5542. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  5543. msg.replyMsg( i18n[( row || defaultSettings ).lang].prefix.replaceSave( /%s/g, patreons[msg.guild.id] ), {}, true );
  5544. } );
  5545. }
  5546. }
  5547. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  5548. }
  5549. if ( !ready.allSites && !allSites.length ) getAllSites();
  5550. if ( msg.channel.type === 'text' ) {
  5551. var permissions = msg.channel.permissionsFor(client.user);
  5552. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  5553. if ( missing.length ) {
  5554. if ( msg.isAdmin() || msg.isOwner() ) {
  5555. console.log( msg.guild.id + ': Missing permissions - ' + missing.join(', ') );
  5556. if ( !missing.includes( 'SEND_MESSAGES' ) ) {
  5557. 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) => {
  5558. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  5559. if ( msg.content.hasPrefix(( patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  5560. msg.replyMsg( i18n[( row || defaultSettings ).lang].missingperm + ' `' + missing.join('`, `') + '`', {}, true );
  5561. }
  5562. } );
  5563. }
  5564. }
  5565. return;
  5566. }
  5567. 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) => {
  5568. if ( dberror ) {
  5569. console.log( '- Error while getting the wiki: ' + dberror );
  5570. if ( permissions.has('SEND_MESSAGES') ) {
  5571. msg.sendChannel( '⚠️ **Limited Functionality** ⚠️\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  5572. newMessage(msg);
  5573. }
  5574. return dberror;
  5575. }
  5576. if ( row ) newMessage(msg, row.wiki, i18n[row.lang], patreons[msg.guild.id], row.inline);
  5577. else {
  5578. msg.defaultSettings = true;
  5579. newMessage(msg);
  5580. }
  5581. } );
  5582. }
  5583. else newMessage(msg);
  5584. } );
  5585. function newMessage(msg, wiki = defaultSettings.wiki, lang = i18n[defaultSettings.lang], prefix = process.env.prefix, noInline = null, content) {
  5586. msg.noInline = noInline;
  5587. var cont = ( content || msg.content );
  5588. var cleanCont = ( content || msg.cleanContent );
  5589. var author = msg.author;
  5590. var channel = msg.channel;
  5591. var invoke = ( cont.split(' ')[1] ? cont.split(' ')[1].split('\n')[0].toLowerCase() : '' );
  5592. var aliasInvoke = ( lang.aliases[invoke] || invoke );
  5593. var ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  5594. if ( cont.hasPrefix(prefix) && ownercmd ) {
  5595. var args = cont.split(' ').slice(2);
  5596. if ( cont.split(' ')[1].split('\n')[1] ) args.unshift( '', cont.split(' ')[1].split('\n')[1] );
  5597. else console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + cont );
  5598. ownercmdmap[aliasInvoke](lang, msg, args, cont, wiki);
  5599. } else {
  5600. var count = 0;
  5601. var maxcount = ( channel.type === 'text' && msg.guild.id in patreons ? 15 : 10 );
  5602. cleanCont.replace( /\u200b/g, '' ).split('\n').forEach( line => {
  5603. if ( line.hasPrefix(prefix) && count < maxcount ) {
  5604. count++;
  5605. invoke = ( line.split(' ')[1] ? line.split(' ')[1].toLowerCase() : '' );
  5606. var args = line.split(' ').slice(2);
  5607. aliasInvoke = ( lang.aliases[invoke] || invoke );
  5608. ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  5609. if ( channel.type === 'text' && pause[msg.guild.id] && !( ( msg.isAdmin() && aliasInvoke in pausecmdmap ) || ownercmd ) ) console.log( msg.guild.id + ': Paused' );
  5610. else console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + line );
  5611. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, line, wiki);
  5612. else if ( channel.type !== 'text' || !pause[msg.guild.id] || ( msg.isAdmin() && aliasInvoke in pausecmdmap ) ) {
  5613. if ( aliasInvoke in cmdmap ) cmdmap[aliasInvoke](lang, msg, args, line, wiki);
  5614. else if ( /^![a-z\d-]{1,50}$/.test(invoke) ) {
  5615. cmd_link(lang, msg, args.join(' '), 'https://' + invoke.substring(1) + '.gamepedia.com/', ' ' + invoke + ' ');
  5616. }
  5617. else if ( /^\?(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  5618. var invokeWiki = wiki;
  5619. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.fandom.com/' + invoke.substring(1).split('.')[0] + '/';
  5620. else invokeWiki = 'https://' + invoke.substring(1) + '.fandom.com/';
  5621. cmd_link(lang, msg, args.join(' '), invokeWiki, ' ' + invoke + ' ');
  5622. }
  5623. else if ( /^\?\?(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  5624. var invokeWiki = wiki;
  5625. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.wikia.org/' + invoke.substring(2).split('.')[0] + '/';
  5626. else invokeWiki = 'https://' + invoke.substring(2) + '.wikia.org/';
  5627. cmd_link(lang, msg, args.join(' '), invokeWiki, ' ' + invoke + ' ');
  5628. }
  5629. else cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  5630. }
  5631. } else if ( line.hasPrefix(prefix) && count === maxcount ) {
  5632. count++;
  5633. console.log( '- Message contains too many commands!' );
  5634. msg.reactEmoji('⚠️');
  5635. msg.sendChannelError( lang.limit.replaceSave( '%s', '<@' + author.id + '>' ), {allowedMentions:{users:[author.id]}} );
  5636. }
  5637. } );
  5638. if ( ( channel.type !== 'text' || !pause[msg.guild.id] ) && !noInline && ( cont.includes( '[[' ) || cont.includes( '{{' ) ) ) {
  5639. var links = [];
  5640. var embeds = [];
  5641. var linkcount = 0;
  5642. var linkmaxcount = maxcount + 5;
  5643. msg.cleanContent.replace( /\u200b/g, '' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).replace( /(?<!\\)`.+?`/gs, '<code>' ).split('\n').forEach( line => {
  5644. if ( line.hasPrefix(prefix) || !( line.includes( '[[' ) || line.includes( '{{' ) ) ) return;
  5645. if ( line.includes( '[[' ) && line.includes( ']]' ) && linkcount <= linkmaxcount ) {
  5646. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)\\[\\[([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\]\\]\\1', 'g' );
  5647. let entry = null;
  5648. while ( ( entry = regex.exec(line) ) !== null ) {
  5649. if ( linkcount < linkmaxcount ) {
  5650. linkcount++;
  5651. console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  5652. let title = entry[2].split('#')[0];
  5653. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  5654. links.push({title,section,spoiler:entry[1]});
  5655. }
  5656. else if ( linkcount === linkmaxcount ) {
  5657. linkcount++;
  5658. console.log( '- Message contains too many links!' );
  5659. msg.reactEmoji('⚠️');
  5660. break;
  5661. }
  5662. }
  5663. }
  5664. if ( line.includes( '{{' ) && line.includes( '}}' ) && count <= maxcount ) {
  5665. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)(?<!\\{)\\{\\{([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\}\\}\\1', 'g' );
  5666. let entry = null;
  5667. while ( ( entry = regex.exec(line) ) !== null ) {
  5668. if ( count < maxcount ) {
  5669. count++;
  5670. console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  5671. let title = entry[2].split('#')[0];
  5672. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  5673. embeds.push({title,section,spoiler:entry[1]});
  5674. }
  5675. else if ( count === maxcount ) {
  5676. count++;
  5677. console.log( '- Message contains too many links!' );
  5678. msg.reactEmoji('⚠️');
  5679. break;
  5680. }
  5681. }
  5682. }
  5683. } );
  5684. 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', {
  5685. responseType: 'json'
  5686. } ).then( response => {
  5687. var body = response.body;
  5688. if ( response.statusCode !== 200 || !body || !body.query ) {
  5689. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  5690. console.log( '- This wiki doesn\'t exist!' );
  5691. msg.reactEmoji('nowiki');
  5692. return;
  5693. }
  5694. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  5695. return;
  5696. }
  5697. if ( body.query.normalized ) {
  5698. body.query.normalized.forEach( title => links.filter( link => link.title === title.from ).forEach( link => link.title = title.to ) );
  5699. }
  5700. if ( body.query.interwiki ) {
  5701. body.query.interwiki.forEach( interwiki => links.filter( link => link.title === interwiki.title ).forEach( link => {
  5702. link.url = interwiki.url + ( link.section ? '#' + link.section.toSection() : '' );
  5703. } ) );
  5704. }
  5705. if ( body.query.pages ) {
  5706. var querypages = Object.values(body.query.pages);
  5707. querypages.filter( page => page.invalid !== undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  5708. links.splice(links.indexOf(link), 1);
  5709. } ) );
  5710. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  5711. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  5712. link.url = wiki.toLink(link.title, 'action=edit&redlink=1', '', body.query.general);
  5713. } ) );
  5714. }
  5715. 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} );
  5716. }, error => {
  5717. if ( wiki.noWiki(error.message) ) {
  5718. console.log( '- This wiki doesn\'t exist!' );
  5719. msg.reactEmoji('nowiki');
  5720. }
  5721. else {
  5722. console.log( '- Error while following the links: ' + error );
  5723. }
  5724. } );
  5725. 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', {
  5726. responseType: 'json'
  5727. } ).then( response => {
  5728. var body = response.body;
  5729. if ( response.statusCode !== 200 || !body || !body.query ) {
  5730. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  5731. console.log( '- This wiki doesn\'t exist!' );
  5732. msg.reactEmoji('nowiki');
  5733. return;
  5734. }
  5735. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  5736. return;
  5737. }
  5738. if ( body.query.normalized ) {
  5739. body.query.normalized.forEach( title => embeds.filter( embed => embed.title === title.from ).forEach( embed => embed.title = title.to ) );
  5740. }
  5741. if ( body.query.pages ) {
  5742. var querypages = Object.values(body.query.pages);
  5743. querypages.filter( page => page.invalid !== undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  5744. embeds.splice(embeds.indexOf(embed), 1);
  5745. } ) );
  5746. var missing = [];
  5747. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  5748. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  5749. embeds.splice(embeds.indexOf(embed), 1);
  5750. if ( page.ns === 0 && !embed.section ) {
  5751. var template = querypages.find( template => template.ns === 10 && template.title.split(':').slice(1).join(':') === embed.title );
  5752. if ( template && template.missing === undefined ) embed.template = wiki.toLink(template.title, '', '', body.query.general);
  5753. }
  5754. if ( embed.template || !body.query.variables || !body.query.variables.some( variable => variable.toUpperCase() === embed.title ) ) missing.push(embed);
  5755. } ) );
  5756. if ( missing.length ) {
  5757. 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} );
  5758. }
  5759. }
  5760. if ( embeds.length ) {
  5761. if ( wiki.isFandom() ) embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  5762. fandom_check_wiki(lang, msg, embed.title, wiki, ' ', reaction, embed.spoiler, '', embed.section);
  5763. } ) );
  5764. else embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  5765. gamepedia_check_wiki(lang, msg, embed.title, wiki, ' ', reaction, embed.spoiler, '', embed.section);
  5766. } ) );
  5767. }
  5768. }, error => {
  5769. if ( wiki.noWiki(error.message) ) {
  5770. console.log( '- This wiki doesn\'t exist!' );
  5771. msg.reactEmoji('nowiki');
  5772. }
  5773. else {
  5774. console.log( '- Error while following the links: ' + error );
  5775. }
  5776. } );
  5777. }
  5778. }
  5779. }
  5780. client.on( 'voiceStateUpdate', (olds, news) => {
  5781. if ( stop || !( olds.guild.id in voice ) || !olds.guild.me.permissions.has('MANAGE_ROLES') || olds.channelID === news.channelID ) return;
  5782. if ( !ready.allSites && !allSites.length ) getAllSites();
  5783. var lang = i18n[voice[olds.guild.id]].voice;
  5784. if ( olds.member && olds.channel ) {
  5785. var oldrole = olds.member.roles.cache.find( role => role.name === lang.channel + ' – ' + olds.channel.name );
  5786. if ( oldrole && oldrole.comparePositionTo(olds.guild.me.roles.highest) < 0 ) {
  5787. console.log( olds.guild.id + ': ' + olds.member.id + ' left the voice channel "' + olds.channel.id + '".' );
  5788. olds.member.roles.remove( oldrole, lang.left.replaceSave( '%1$s', olds.member.displayName ).replaceSave( '%2$s', olds.channel.name ) ).catch(log_error);
  5789. }
  5790. }
  5791. if ( news.member && news.channel ) {
  5792. var newrole = news.guild.roles.cache.find( role => role.name === lang.channel + ' – ' + news.channel.name );
  5793. if ( newrole && newrole.comparePositionTo(news.guild.me.roles.highest) < 0 ) {
  5794. console.log( news.guild.id + ': ' + news.member.id + ' joined the voice channel "' + news.channel.id + '".' );
  5795. news.member.roles.add( newrole, lang.join.replaceSave( '%1$s', news.member.displayName ).replaceSave( '%2$s', news.channel.name ) ).catch(log_error);
  5796. }
  5797. }
  5798. } );
  5799. client.on( 'guildCreate', guild => {
  5800. console.log( '- I\'ve been added to a server.' );
  5801. } );
  5802. client.on( 'guildDelete', guild => {
  5803. if ( !guild.available ) {
  5804. console.log( '- ' + guild.id + ': This server isn\'t responding.' );
  5805. return;
  5806. }
  5807. console.log( '- I\'ve been removed from a server.' );
  5808. db.run( 'DELETE FROM discord WHERE guild = ?', [guild.id], function (dberror) {
  5809. if ( dberror ) {
  5810. console.log( '- Error while removing the settings: ' + dberror );
  5811. return dberror;
  5812. }
  5813. if ( guild.id in patreons ) client.shard.broadcastEval( `delete global.patreons['${guild.id}']` );
  5814. if ( guild.id in voice ) delete voice[guild.id];
  5815. console.log( '- Settings successfully removed.' );
  5816. } );
  5817. db.run( 'DELETE FROM verification WHERE guild = ?', [guild.id], function (dberror) {
  5818. if ( dberror ) {
  5819. console.log( '- Error while removing the verifications: ' + dberror );
  5820. return dberror;
  5821. }
  5822. console.log( '- Verifications successfully removed.' );
  5823. } );
  5824. } );
  5825. function removePatreons(guild, msg) {
  5826. try {
  5827. if ( !guild ) return 'removePatreons(guild, msg) – No guild provided!';
  5828. db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND channel IS NULL', [guild], (dberror, row) => {
  5829. try {
  5830. if ( dberror ) {
  5831. console.log( '- Error while getting the guild: ' + dberror );
  5832. if ( msg ) msg.replyMsg( 'I got an error while searching for the guild!', {}, true );
  5833. return dberror;
  5834. }
  5835. if ( !row ) {
  5836. if ( msg ) msg.replyMsg( 'that guild doesn\'t exist!', {}, true );
  5837. return;
  5838. }
  5839. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, guild], function (error) {
  5840. try {
  5841. if ( error ) {
  5842. console.log( '- Error while updating the guild: ' + error );
  5843. if ( msg ) msg.replyMsg( 'I got an error while updating the guild!', {}, true );
  5844. return error;
  5845. }
  5846. console.log( '- Guild successfully updated.' );
  5847. client.shard.broadcastEval( `delete global.patreons['${guild}']`);
  5848. if ( msg ) msg.replyMsg( 'the patreon features are now disabled on that guild.', {}, true );
  5849. }
  5850. catch ( tryerror ) {
  5851. console.log( '- Error while removing the patreon features: ' + tryerror );
  5852. }
  5853. } );
  5854. }
  5855. catch ( tryerror ) {
  5856. console.log( '- Error while removing the patreon features: ' + tryerror );
  5857. }
  5858. } );
  5859. }
  5860. catch ( tryerror ) {
  5861. console.log( '- Error while removing the patreon features: ' + tryerror );
  5862. return 'removePatreons(guild, msg) – Error while removing the patreon features: ' + tryerror;
  5863. }
  5864. }
  5865. function removeSettings() {
  5866. client.shard.broadcastEval( `[[...this.guilds.cache.keys()], [...this.channels.cache.filter( channel => channel.type === 'text' ).keys()]]` ).then( results => {
  5867. var all_guilds = results.map( result => result[0] ).reduce( (acc, val) => acc.concat(val), [] );
  5868. var all_channels = results.map( result => result[1] ).reduce( (acc, val) => acc.concat(val), [] );
  5869. var guilds = [];
  5870. var channels = [];
  5871. db.each( 'SELECT guild, channel FROM discord', [], (dberror, row) => {
  5872. if ( dberror ) {
  5873. console.log( '- Error while getting the setting: ' + dberror );
  5874. return dberror;
  5875. }
  5876. if ( !row.channel && !all_guilds.some(row.guild) ) {
  5877. if ( row.guild in patreons ) client.shard.broadcastEval( `delete global.patreons['${row.guild}']` );
  5878. if ( row.guild in voice ) delete voice[row.guild];
  5879. return guilds.push(row.guild);
  5880. }
  5881. if ( row.channel && all_guilds.some(row.guild) && !all_channels.some(row.channel) ) return channels.push(row.channel);
  5882. }, (error) => {
  5883. if ( error ) {
  5884. console.log( '- Error while getting the settings: ' + error );
  5885. return error;
  5886. }
  5887. if ( guilds.length ) {
  5888. db.run( 'DELETE FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  5889. if ( dberror ) {
  5890. console.log( '- Error while removing the guilds: ' + dberror );
  5891. return dberror;
  5892. }
  5893. console.log( '- Guilds successfully removed.' );
  5894. } );
  5895. db.run( 'DELETE FROM verification WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  5896. if ( dberror ) {
  5897. console.log( '- Error while removing the verifications: ' + dberror );
  5898. return dberror;
  5899. }
  5900. console.log( '- Verifications successfully removed.' );
  5901. } );
  5902. }
  5903. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( channel => '?' ).join(', ') + ')', channels, function (dberror) {
  5904. if ( dberror ) {
  5905. console.log( '- Error while removing the channels: ' + dberror );
  5906. return dberror;
  5907. }
  5908. console.log( '- Channels successfully removed.' );
  5909. } );
  5910. if ( !guilds.length && !channels.length ) console.log( '- Settings successfully removed.' );
  5911. } );
  5912. } );
  5913. }
  5914. process.on( 'message', message => {
  5915. if ( !message.shard ) return;
  5916. shardId = message.shard.id;
  5917. } );
  5918. client.on( 'error', error => log_error(error, true) );
  5919. client.on( 'warn', warning => log_warn(warning, false) );
  5920. client.login(process.env.token).catch( error => {
  5921. log_error(error, true, 'LOGIN-');
  5922. client.login(process.env.token).catch( error => {
  5923. log_error(error, true, 'LOGIN-');
  5924. client.login(process.env.token).catch( error => {
  5925. log_error(error, true, 'LOGIN-');
  5926. process.exit(1);
  5927. } );
  5928. } );
  5929. } );
  5930. if ( isDebug ) client.on( 'debug', debug => {
  5931. if ( isDebug ) console.log( '- ' + shardId + ': Debug: ' + debug );
  5932. } );
  5933. function log_error(error, isBig = false, type = '') {
  5934. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  5935. if ( isDebug ) {
  5936. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  5937. } else {
  5938. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  5939. else console.log( '- ' + error.name + ': ' + error.message );
  5940. }
  5941. }
  5942. function log_warn(warning, api = true) {
  5943. if ( isDebug ) {
  5944. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  5945. } else {
  5946. if ( api ) console.warn( '- Warning: ' + Object.keys(warning).join(', ') );
  5947. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  5948. }
  5949. }
  5950. async function graceful(signal) {
  5951. stop = true;
  5952. console.log( '- ' + shardId + ': ' + signal + ': Preparing to close...' );
  5953. setTimeout( async () => {
  5954. console.log( '- ' + shardId + ': ' + signal + ': Destroying client...' );
  5955. await client.destroy();
  5956. await db.close( dberror => {
  5957. if ( dberror ) {
  5958. console.log( '- ' + shardId + ': ' + signal + ': Error while closing the database connection: ' + dberror );
  5959. return dberror;
  5960. }
  5961. console.log( '- ' + shardId + ': ' + signal + ': Closed the database connection.' );
  5962. process.exit(0);
  5963. } );
  5964. }, 1000 ).unref();
  5965. }
  5966. process.once( 'SIGINT', graceful );
  5967. process.once( 'SIGTERM', graceful );