main.js 302 KB

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