main.js 303 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028
  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.startsWith( 'AND|' ) ? row.usergroup.split('|').slice(1).join('` and `') : 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.startsWith( 'AND|' ) ? row.usergroup.split('|').slice(1).join('` and `') : 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.startsWith( 'AND|' ) ? row.usergroup.split('|').slice(1).join('` and `') : 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. var and_or = '';
  1956. if ( usergroups[0] === 'and' ) {
  1957. usergroups = usergroups.slice(1);
  1958. and_or = 'AND|';
  1959. }
  1960. if ( usergroups.length > 10 ) return msg.replyMsg( 'too many usergroups provided.', {}, true );
  1961. if ( usergroups.some( usergroup => usergroup.length > 100 ) ) return msg.replyMsg( 'the provided usergroup is too long.', {}, true );
  1962. usergroups = usergroups.join('|');
  1963. if ( usergroups.length ) return db.run( 'UPDATE verification SET usergroup = ? WHERE guild = ? AND configid = ?', [and_or + usergroups, msg.guild.id, row.configid], function (dberror) {
  1964. if ( dberror ) {
  1965. console.log( '- Error while updating the verification: ' + dberror );
  1966. msg.replyMsg( 'sadly the verification couldn\'t be updated, please try again later.', {}, true );
  1967. return dberror;
  1968. }
  1969. console.log( '- Verification successfully updated.' );
  1970. row.usergroup = and_or + usergroups;
  1971. 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.startsWith( 'AND|' ) ? row.usergroup.split('|').slice(1).join('` and `') : row.usergroup.split('|').join('` or `') ) + '`\nAccount age: `' + row.accountage + '` (in days)';
  1972. if ( row.role.split('|').some( role => msg.guild.me.roles.highest.comparePositionTo(role) <= 0 ) ) {
  1973. text += '\n';
  1974. row.role.split('|').forEach( role => {
  1975. if ( msg.guild.me.roles.highest.comparePositionTo(role) <= 0 ) text += '\n**The role <@&' + role + '> is too high for ' + msg.guild.me.toString() + ' to assign!**';
  1976. } );
  1977. }
  1978. msg.replyMsg( text, {split:true}, true );
  1979. } );
  1980. }
  1981. if ( args[1] === 'channel' ) {
  1982. var channels = args[2].replace( /\s*>?\s*\|\s*<?\s*/g, '|' ).split('|').filter( channel => channel.length );
  1983. if ( channels.length > 10 ) return msg.replyMsg( 'too many channels provided.', {}, true );
  1984. channels = channels.map( channel => {
  1985. var new_channel = '';
  1986. if ( /^\d+$/.test(channel) ) new_channel = msg.guild.channels.cache.filter( tc => tc.type === 'text' ).get(channel);
  1987. if ( !new_channel ) new_channel = msg.guild.channels.cache.filter( gc => gc.type === 'text' ).find( gc => gc.name === channel.replace( /^#/, '' ) );
  1988. return new_channel;
  1989. } );
  1990. if ( channels.some( channel => !channel ) ) return msg.replyMsg( 'the provided channel does not exist.', {}, true );
  1991. channels = channels.map( channel => channel.id ).join('|');
  1992. if ( channels.length ) return db.run( 'UPDATE verification SET channel = ? WHERE guild = ? AND configid = ?', ['|' + channels + '|', msg.guild.id, row.configid], function (dberror) {
  1993. if ( dberror ) {
  1994. console.log( '- Error while updating the verification: ' + dberror );
  1995. msg.replyMsg( 'sadly the verification couldn\'t be updated, please try again later.', {}, true );
  1996. return dberror;
  1997. }
  1998. console.log( '- Verification successfully updated.' );
  1999. row.channel = '|' + channels + '|';
  2000. 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.startsWith( 'AND|' ) ? row.usergroup.split('|').slice(1).join('` and `') : row.usergroup.split('|').join('` or `') ) + '`\nAccount age: `' + row.accountage + '` (in days)';
  2001. if ( row.role.split('|').some( role => msg.guild.me.roles.highest.comparePositionTo(role) <= 0 ) ) {
  2002. text += '\n';
  2003. row.role.split('|').forEach( role => {
  2004. if ( msg.guild.me.roles.highest.comparePositionTo(role) <= 0 ) text += '\n**The role <@&' + role + '> is too high for ' + msg.guild.me.toString() + ' to assign!**';
  2005. } );
  2006. }
  2007. msg.replyMsg( text, {split:true}, true );
  2008. } );
  2009. }
  2010. }
  2011. 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.startsWith( 'AND|' ) ? row.usergroup.split('|').slice(1).join('` and `') : 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>`';
  2012. if ( row.role.split('|').some( role => msg.guild.me.roles.highest.comparePositionTo(role) <= 0 ) ) {
  2013. text += '\n';
  2014. row.role.split('|').forEach( role => {
  2015. if ( msg.guild.me.roles.highest.comparePositionTo(role) <= 0 ) text += '\n**The role <@&' + role + '> is too high for ' + msg.guild.me.toString() + ' to assign!**';
  2016. } );
  2017. }
  2018. text += '\n\nDelete this verification:\n`' + prefix + ' verification ' + row.configid + ' delete`';
  2019. return msg.replyMsg( text, {split:true}, true );
  2020. } );
  2021. }
  2022. function cmd_verify(lang, msg, args, line, wiki) {
  2023. if ( !( wiki.endsWith( '.gamepedia.com/' ) || wiki.isFandom() ) || msg.channel.type !== 'text' ) return cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  2024. if ( !msg.guild.me.permissions.has('MANAGE_ROLES') ) {
  2025. if ( msg.isAdmin() ) {
  2026. console.log( msg.guild.id + ': Missing permissions - MANAGE_ROLES' );
  2027. msg.replyMsg( lang.missingperm + ' `MANAGE_ROLES`' );
  2028. } else cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  2029. return
  2030. }
  2031. var username = args.join(' ').replace( /_/g, ' ' ).trim().replace( /^<\s*(.*)\s*>$/, '$1' ).replace( /^@/, '' ).split('#')[0];
  2032. if ( username.length > 250 ) username = username.substring(0, 250).trim();
  2033. if ( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.(?:gamepedia\.com\/|(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?wiki\/)/.test(username) ) {
  2034. username = decodeURIComponent( username.replace( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.(?:gamepedia\.com\/|(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?wiki\/)/, '' ) );
  2035. }
  2036. if ( wiki.endsWith( '.gamepedia.com/' ) ) username = username.replace( /^userprofile\s*:/i, '' );
  2037. 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) => {
  2038. if ( dberror || !rows ) {
  2039. console.log( '- Error while getting the verifications: ' + dberror );
  2040. embed.setTitle( username.escapeFormatting() ).setColor('#000000').setDescription( 'The verification failed due to an error, please try again.' );
  2041. msg.replyMsg( 'the verification failed due to an error, please try again.', {embed}, false, false ).then( message => message.reactEmoji('error') );
  2042. return dberror;
  2043. }
  2044. if ( !rows.length ) return cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  2045. if ( !username.trim() ) {
  2046. /*
  2047. args[0] = line.split(' ')[1];
  2048. return cmd_help(lang, msg, args, line);
  2049. */
  2050. 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.' );
  2051. }
  2052. var embed = new Discord.MessageEmbed().setFooter( 'Wiki Account Verification' ).setTimestamp();
  2053. 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', {
  2054. responseType: 'json'
  2055. } ).then( response => {
  2056. var body = response.body;
  2057. if ( body && body.warnings ) log_warn(body.warnings);
  2058. if ( response.statusCode !== 200 || !body || !body.query || !body.query.users ) {
  2059. console.log( '- ' + response.statusCode + ': Error while getting the user: ' + ( body && body.error && body.error.info ) );
  2060. embed.setTitle( username.escapeFormatting() ).setColor('#000000').setDescription( 'The verification failed due to an error, please try again.' );
  2061. msg.replyMsg( 'the verification failed due to an error, please try again.', {embed}, false, false ).then( message => message.reactEmoji('error') );
  2062. if ( reaction ) reaction.removeEmoji();
  2063. return;
  2064. }
  2065. var queryuser = body.query.users[0];
  2066. embed.setAuthor( body.query.general.sitename );
  2067. if ( body.query.users.length !== 1 || queryuser.missing !== undefined || queryuser.invalid !== undefined ) {
  2068. username = ( body.query.users.length === 1 ? queryuser.name : username );
  2069. embed.setTitle( username.escapeFormatting() ).setColor('#0000FF').setDescription( 'The wiki user "' + username.escapeFormatting() + '" doesn\'t exist.' );
  2070. msg.replyMsg( 'your linked wiki user "' + username.escapeFormatting() + '" doesn\'t exist.', {embed}, false, false );
  2071. if ( reaction ) reaction.removeEmoji();
  2072. return;
  2073. }
  2074. username = queryuser.name;
  2075. var pagelink = wiki.toLink('User:' + username, '', '', body.query.general, true);
  2076. embed.setTitle( username.escapeFormatting() ).setURL( pagelink );
  2077. if ( queryuser.blockexpiry ) {
  2078. embed.setColor('#FF0000').setDescription( '**The wiki user [' + username.escapeFormatting() + '](' + pagelink + ') is blocked!**' );
  2079. msg.replyMsg( 'your linked wiki user **"' + username.escapeFormatting() + '" is blocked!**', {embed}, false, false );
  2080. if ( reaction ) reaction.removeEmoji();
  2081. return;
  2082. }
  2083. var comment = [];
  2084. var url = '';
  2085. if ( wiki.endsWith( '.gamepedia.com/' ) ) {
  2086. url = 'https://help.gamepedia.com/Special:GlobalBlockList/' + encodeURIComponent( username ) + '?uselang=qqx';
  2087. }
  2088. else if ( wiki.isFandom() ) {
  2089. url = 'https://community.fandom.com/Special:Contributions/' + encodeURIComponent( username ) + '?limit=1';
  2090. }
  2091. got.get( url ).then( gbresponse => {
  2092. if ( gbresponse.statusCode !== 200 || !gbresponse.body ) {
  2093. console.log( '- ' + gbresponse.statusCode + ': Error while getting the global block.' );
  2094. comment.push('**Check for global block failed!**');
  2095. }
  2096. else {
  2097. let $ = cheerio.load(gbresponse.body);
  2098. if ( wiki.endsWith( '.gamepedia.com/' ) ) {
  2099. if ( $('.mw-blocklist').length ) {
  2100. return Promise.reject([
  2101. 'your linked wiki user **"' + username.escapeFormatting() + '" is globally blocked!**',
  2102. '**The wiki user [' + username.escapeFormatting() + '](' + pagelink + ') is globally blocked!**'
  2103. ]);
  2104. }
  2105. }
  2106. else if ( wiki.isFandom() ) {
  2107. if ( $('#mw-content-text .errorbox').length ) {
  2108. return Promise.reject([
  2109. 'your linked wiki user **"' + username.escapeFormatting() + '" is disabled!**',
  2110. '**The wiki user [' + username.escapeFormatting() + '](' + pagelink + ') is disabled!**'
  2111. ]);
  2112. }
  2113. else if ( $('.mw-warning-with-logexcerpt').length && !$(".mw-warning-with-logexcerpt .mw-logline-block").length ) {
  2114. return Promise.reject([
  2115. 'your linked wiki user **"' + username.escapeFormatting() + '" is globally blocked!**',
  2116. '**The wiki user [' + username.escapeFormatting() + '](' + pagelink + ') is globally blocked!**'
  2117. ]);
  2118. }
  2119. }
  2120. }
  2121. }, error => {
  2122. console.log( '- Error while getting the global block: ' + error );
  2123. comment.push('**Check for global block failed!**');
  2124. } ).then( () => {
  2125. var options = {responseType: 'json'};
  2126. if ( wiki.endsWith( '.gamepedia.com/' ) ) {
  2127. url = wiki + 'api.php?action=profile&do=getPublicProfile&user_name=' + encodeURIComponent( username ) + '&format=json';
  2128. }
  2129. else if ( wiki.isFandom() ) {
  2130. url = 'https://services.fandom.com/user-attribute/user/' + queryuser.userid + '/attr/discordHandle?format=json';
  2131. options.headers = {Accept: 'application/hal+json'};
  2132. }
  2133. got.get( url, options ).then( presponse => {
  2134. var pbody = presponse.body;
  2135. if ( presponse.statusCode !== 200 || !pbody || pbody.error || pbody.errormsg || pbody.title || !( pbody.profile || pbody.value !== undefined ) ) {
  2136. if ( !( pbody && pbody.status === 404 ) ) {
  2137. console.log( '- ' + presponse.statusCode + ': Error while getting the Discord tag: ' + ( pbody && ( pbody.error && pbody.error.info || pbody.errormsg || pbody.title ) ) );
  2138. embed.setColor('#000000').setDescription( 'The verification failed due to an error, please try again.' );
  2139. return msg.replyMsg( 'the verification failed due to an error, please try again.', {embed}, false, false ).then( message => message.reactEmoji('error') );
  2140. }
  2141. }
  2142. var discordname = '';
  2143. if ( pbody.profile ) discordname = pbody.profile['link-discord'].escapeFormatting().replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2144. else if ( pbody.value ) discordname = htmlToPlain( pbody.value ).replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2145. embed.addField( 'Discord user:', msg.author.tag.escapeFormatting(), true ).addField( 'Wiki user:', ( discordname || '*none*' ), true );
  2146. if ( msg.author.tag.escapeFormatting() !== discordname ) {
  2147. embed.setColor('#FFFF00').setDescription( 'Discord user ' + msg.member.toString() + ' doesn\'t match the wiki user [' + username.escapeFormatting() + '](' + pagelink + ').' );
  2148. return msg.replyMsg( 'your Discord tag doesn\'t match the wiki user "' + username.escapeFormatting() + '".', {embed}, false, false );
  2149. }
  2150. var roles = [];
  2151. var missing = [];
  2152. var verified = false;
  2153. var accountage = ( Date.now() - new Date(queryuser.registration) ) / 86400000;
  2154. rows.forEach( row => {
  2155. var and_or = 'some';
  2156. if ( row.usergroup.startsWith( 'AND|' ) ) {
  2157. row.usergroup = row.usergroup.replace( 'AND|', '' );
  2158. and_or = 'every';
  2159. }
  2160. if ( queryuser.editcount >= row.editcount && row.usergroup.split('|')[and_or]( usergroup => {
  2161. if ( !queryuser.groupmemberships ) return queryuser.groups.includes( usergroup );
  2162. if ( !queryuser.groups.includes( 'global_' + usergroup ) || queryuser.groupmemberships.some( member => member.group === usergroup ) ) {
  2163. return queryuser.groups.includes( usergroup );
  2164. }
  2165. return false;
  2166. } ) && accountage >= row.accountage && row.role.split('|').some( role => !roles.includes( role ) ) ) {
  2167. verified = true;
  2168. row.role.split('|').forEach( role => {
  2169. if ( !roles.includes( role ) ) {
  2170. if ( msg.guild.roles.cache.has(role) && msg.guild.me.roles.highest.comparePositionTo(role) > 0 ) roles.push(role);
  2171. else if ( !missing.includes( role ) ) missing.push(role);
  2172. }
  2173. } );
  2174. }
  2175. } );
  2176. if ( verified ) {
  2177. embed.setColor('#00FF00').setDescription( 'Discord user ' + msg.member.toString() + ' has been successfully verified as wiki user [' + username.escapeFormatting() + '](' + pagelink + ').' );
  2178. var text = 'you have been sucessfully verified as wiki user "' + username.escapeFormatting() + '".';
  2179. msg.member.roles.add( roles, 'Verified as "' + username + '"' ).catch( error => {
  2180. embed.setColor('#008800');
  2181. comment.push('**Adding roles failed!**');
  2182. } ).finally( () => {
  2183. if ( msg.showEmbed() ) {
  2184. if ( roles.length ) embed.addField( 'Qualified for:', roles.map( role => '<@&' + role + '>' ).join('\n') );
  2185. if ( missing.length ) embed.setColor('#008800').addField( 'Qualified for, but could not add:', missing.map( role => '<@&' + role + '>' ).join('\n') );
  2186. if ( comment.length ) embed.setColor('#008800').addField( 'Notice:', comment.join('\n') );
  2187. }
  2188. else {
  2189. if ( roles.length ) text += '\n\nQualified for: ' + roles.map( role => '<@&' + role + '>' ).join(', ');
  2190. if ( missing.length ) text += '\n\nQualified for, but could not add: ' + missing.map( role => '<@&' + role + '>' ).join(', ');
  2191. if ( comment.length ) text += '\n\n' + comment.join('\n');
  2192. }
  2193. msg.replyMsg( text, {embed}, false, false );
  2194. } );
  2195. }
  2196. else {
  2197. 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.' );
  2198. msg.replyMsg( 'your Discord tag matches the wiki user "' + username.escapeFormatting() + '", but you don\'t meet the requirements for any roles.', {embed}, false, false );
  2199. }
  2200. }, error => {
  2201. console.log( '- Error while getting the Discord tag: ' + error );
  2202. embed.setColor('#000000').setDescription( 'The verification failed due to an error, please try again.' );
  2203. msg.replyMsg( 'the verification failed due to an error, please try again.', {embed}, false, false ).then( message => message.reactEmoji('error') );
  2204. } ).finally( () => {
  2205. if ( reaction ) reaction.removeEmoji();
  2206. } );
  2207. }, error => {
  2208. embed.setColor('#FF0000').setDescription( error[1] );
  2209. msg.replyMsg( error[0], {embed}, false, false );
  2210. if ( reaction ) reaction.removeEmoji();
  2211. } );
  2212. }, error => {
  2213. console.log( '- Error while getting the user: ' + error );
  2214. embed.setColor('#000000').setDescription( 'The verification failed due to an error, please try again.' );
  2215. msg.replyMsg( 'the verification failed due to an error, please try again.', {embed}, false, false ).then( message => message.reactEmoji('error') );
  2216. if ( reaction ) reaction.removeEmoji();
  2217. } ) );
  2218. } );
  2219. }
  2220. function gamepedia_user(lang, msg, namespace, username, wiki, querystring, fragment, querypage, contribs, reaction, spoiler) {
  2221. if ( /^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2222. got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=blocks&bkprop=user|by|timestamp|expiry|reason&bkip=' + encodeURIComponent( username ) + '&format=json', {
  2223. responseType: 'json'
  2224. } ).then( response => {
  2225. var body = response.body;
  2226. if ( body && body.warnings ) log_warn(body.warnings);
  2227. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.blocks ) {
  2228. if ( body && body.error && ( body.error.code === 'param_ip' || body.error.code === 'cidrtoobroad' ) ) {
  2229. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('error');
  2230. else {
  2231. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment);
  2232. var embed = new Discord.MessageEmbed().setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2233. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  2234. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  2235. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  2236. embed.setTitle( displaytitle );
  2237. }
  2238. if ( querypage.pageprops && querypage.pageprops.description ) {
  2239. var description = htmlToPlain( querypage.pageprops.description );
  2240. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2241. embed.setDescription( description );
  2242. }
  2243. else if ( querypage.extract ) {
  2244. var extract = querypage.extract.escapeFormatting();
  2245. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  2246. embed.setDescription( extract );
  2247. }
  2248. if ( querypage.pageimage && querypage.original ) {
  2249. var pageimage = querypage.original.source;
  2250. embed.setThumbnail( pageimage );
  2251. }
  2252. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2253. }
  2254. }
  2255. else {
  2256. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2257. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2258. }
  2259. if ( reaction ) reaction.removeEmoji();
  2260. }
  2261. else {
  2262. if ( !querypage.noRedirect || ( querypage.missing === undefined && querypage.ns !== -1 ) ) namespace = contribs;
  2263. var blocks = body.query.blocks.map( block => {
  2264. var isBlocked = false;
  2265. var blockedtimestamp = new Date(block.timestamp).toLocaleString(lang.dateformat, timeoptions);
  2266. var blockexpiry = block.expiry;
  2267. if ( blockexpiry === 'infinity' ) {
  2268. blockexpiry = lang.user.block.until_infinity;
  2269. isBlocked = true;
  2270. } else if ( blockexpiry ) {
  2271. if ( Date.parse(blockexpiry) > Date.now() ) isBlocked = true;
  2272. blockexpiry = new Date(blockexpiry).toLocaleString(lang.dateformat, timeoptions);
  2273. }
  2274. 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 )];
  2275. } ).filter( block => block !== undefined );
  2276. if ( username.includes( '/' ) ) {
  2277. var rangeprefix = username;
  2278. if ( username.includes( ':' ) ) {
  2279. var range = parseInt(username.replace( /^.+\/(\d{2,3})$/, '$1' ), 10);
  2280. if ( range === 128 ) username = username.replace( /^(.+)\/\d{2,3}$/, '$1' );
  2281. else if ( range >= 112 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){7}).+$/, '$1' );
  2282. else if ( range >= 96 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){6}).+$/, '$1' );
  2283. else if ( range >= 80 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){5}).+$/, '$1' );
  2284. else if ( range >= 64 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){4}).+$/, '$1' );
  2285. else if ( range >= 48 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){3}).+$/, '$1' );
  2286. else if ( range >= 32 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){2}).+$/, '$1' );
  2287. else if ( range >= 19 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){1}).+$/, '$1' );
  2288. }
  2289. else {
  2290. var range = parseInt(username.substring(username.length - 2), 10);
  2291. if ( range === 32 ) username = username.replace( /^(.+)\/\d{2}$/, '$1' );
  2292. else if ( range >= 24 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){3}).+$/, '$1' );
  2293. else if ( range >= 16 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){2}).+$/, '$1' );
  2294. }
  2295. }
  2296. got.get( wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=50' + ( username.includes( '/' ) ? '&ucuserprefix=' + encodeURIComponent( rangeprefix ) : '&ucuser=' + encodeURIComponent( username ) ) + '&format=json', {
  2297. responseType: 'json'
  2298. } ).then( ucresponse => {
  2299. var ucbody = ucresponse.body;
  2300. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2301. if ( ucbody && ucbody.warnings ) log_warn(ucbody.warnings);
  2302. if ( ucresponse.statusCode !== 200 || !ucbody || ucbody.batchcomplete === undefined || !ucbody.query || !ucbody.query.usercontribs ) {
  2303. if ( ucbody && ucbody.error && ucbody.error.code === 'baduser_ucuser' ) {
  2304. msg.reactEmoji('error');
  2305. }
  2306. else {
  2307. console.log( '- ' + ucresponse.statusCode + ': Error while getting the search results: ' + ( ucbody && ucbody.error && ucbody.error.info ) );
  2308. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2309. }
  2310. }
  2311. else {
  2312. var editcount = [lang.user.info.editcount, ( username.includes( '/' ) && ( ( username.includes( ':' ) && range % 16 ) || range % 8 ) ? '~' : '' ) + ucbody.query.usercontribs.length + ( ucbody.continue ? '+' : '' )];
  2313. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2314. if ( msg.showEmbed() ) {
  2315. var text = '<' + pagelink + '>';
  2316. 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) + ')' );
  2317. if ( blocks.length ) blocks.forEach( block => embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) ) );
  2318. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2319. }
  2320. else {
  2321. var embed = {};
  2322. var text = '<' + pagelink + '>\n\n' + editcount.join(' ');
  2323. if ( blocks.length ) blocks.forEach( block => text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext() );
  2324. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2325. }
  2326. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2327. }
  2328. }, error => {
  2329. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2330. console.log( '- Error while getting the search results: ' + error );
  2331. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2332. } ).finally( () => {
  2333. if ( reaction ) reaction.removeEmoji();
  2334. } );
  2335. }
  2336. }, error => {
  2337. console.log( '- Error while getting the search results: ' + error );
  2338. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2339. if ( reaction ) reaction.removeEmoji();
  2340. } );
  2341. } else {
  2342. 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', {
  2343. responseType: 'json'
  2344. } ).then( response => {
  2345. var body = response.body;
  2346. if ( body && body.warnings ) log_warn(body.warnings);
  2347. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.users || !body.query.users[0] ) {
  2348. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2349. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2350. if ( reaction ) reaction.removeEmoji();
  2351. }
  2352. else {
  2353. var queryuser = body.query.users[0];
  2354. if ( queryuser.missing !== undefined || queryuser.invalid !== undefined ) {
  2355. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('🤷');
  2356. else {
  2357. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  2358. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2359. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  2360. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  2361. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  2362. embed.setTitle( displaytitle );
  2363. }
  2364. if ( querypage.pageprops && querypage.pageprops.description ) {
  2365. var description = htmlToPlain( querypage.pageprops.description );
  2366. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2367. embed.setDescription( description );
  2368. }
  2369. else if ( querypage.extract ) {
  2370. var extract = querypage.extract.escapeFormatting();
  2371. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  2372. embed.setDescription( extract );
  2373. }
  2374. if ( querypage.pageimage && querypage.original ) {
  2375. var pageimage = querypage.original.source;
  2376. embed.setThumbnail( pageimage );
  2377. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  2378. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2379. }
  2380. if ( reaction ) reaction.removeEmoji();
  2381. }
  2382. else {
  2383. username = queryuser.name;
  2384. var gender = [lang.user.info.gender];
  2385. switch (queryuser.gender) {
  2386. case 'male':
  2387. gender.push(lang.user.gender.male);
  2388. break;
  2389. case 'female':
  2390. gender.push(lang.user.gender.female);
  2391. break;
  2392. default:
  2393. gender.push(lang.user.gender.unknown);
  2394. }
  2395. var registration = [lang.user.info.registration, new Date(queryuser.registration).toLocaleString(lang.dateformat, timeoptions)];
  2396. var editcount = [lang.user.info.editcount, queryuser.editcount];
  2397. var groups = queryuser.groups;
  2398. var group = [lang.user.info.group];
  2399. var grouplist = lang.user.groups;
  2400. for ( var i = 0; i < grouplist.length; i++ ) {
  2401. if ( groups.includes( grouplist[i][0] ) && ( group.length === 1 || grouplist[i][0] !== 'user' ) ) {
  2402. var thisSite = allSites.find( site => site.wiki_domain === body.query.general.servername );
  2403. if ( grouplist[i][0] === 'wiki_manager' && thisSite && thisSite.wiki_managers.includes( username ) ) {
  2404. group.push('**' + grouplist[i][1] + '**');
  2405. }
  2406. else if ( !groups.includes( 'global_' + grouplist[i][0] ) || queryuser.groupmemberships.some( member => member.group === grouplist[i][0] ) ) {
  2407. group.push(grouplist[i][1]);
  2408. }
  2409. }
  2410. }
  2411. var isBlocked = false;
  2412. var blockedtimestamp = new Date(queryuser.blockedtimestamp).toLocaleString(lang.dateformat, timeoptions);
  2413. var blockexpiry = queryuser.blockexpiry;
  2414. if ( blockexpiry === 'infinity' ) {
  2415. blockexpiry = lang.user.block.until_infinity;
  2416. isBlocked = true;
  2417. } else if ( blockexpiry ) {
  2418. var blockexpirydate = blockexpiry.replace( /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2,3})/, '$1-$2-$3T$4:$5:$6Z' );
  2419. blockexpiry = new Date(blockexpirydate).toLocaleString(lang.dateformat, timeoptions);
  2420. if ( Date.parse(blockexpirydate) > Date.now() ) isBlocked = true;
  2421. }
  2422. var blockedby = '[[User:' + queryuser.blockedby + '|' + queryuser.blockedby + ']]';
  2423. var blockreason = queryuser.blockreason;
  2424. 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 )];
  2425. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2426. if ( msg.showEmbed() ) {
  2427. var text = '<' + pagelink + '>';
  2428. 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 );
  2429. if ( querypage.pageprops && querypage.pageprops.description ) {
  2430. var description = htmlToPlain( querypage.pageprops.description );
  2431. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2432. embed.setDescription( description );
  2433. }
  2434. else if ( querypage.extract ) {
  2435. var extract = querypage.extract.escapeFormatting();
  2436. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  2437. embed.setDescription( extract );
  2438. }
  2439. }
  2440. else {
  2441. var embed = {};
  2442. var text = '<' + pagelink + '>\n\n' + gender.join(' ') + '\n' + registration.join(' ') + '\n' + editcount.join(' ') + '\n' + group[0] + ' ' + group.slice(1).join(', ');
  2443. }
  2444. if ( wiki.endsWith( '.gamepedia.com/' ) ) got.get( wiki + 'api.php?action=profile&do=getPublicProfile&user_name=' + encodeURIComponent( username ) + '&format=json', {
  2445. responseType: 'json'
  2446. } ).then( presponse => {
  2447. var pbody = presponse.body;
  2448. if ( presponse.statusCode !== 200 || !pbody || pbody.error || pbody.errormsg || !pbody.profile ) {
  2449. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && ( pbody.error && pbody.error.info || pbody.errormsg ) ) );
  2450. }
  2451. else {
  2452. if ( pbody.profile['link-discord'] ) {
  2453. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  2454. return member.user.tag === pbody.profile['link-discord'].replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2455. } );
  2456. var discordname = [lang.user.info.discord,pbody.profile['link-discord'].escapeFormatting()];
  2457. if ( discordmember ) discordname[1] = discordmember.toString();
  2458. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  2459. else text += '\n' + discordname.join(' ');
  2460. }
  2461. if ( pbody.profile['favwiki'] ) {
  2462. var favwiki = [lang.user.info.favwiki,allSites.find( site => site.md5_key === pbody.profile['favwiki'] )];
  2463. if ( favwiki[1] ) {
  2464. if ( msg.showEmbed() ) embed.addField( favwiki[0], '[' + favwiki[1].wiki_display_name + '](<https://' + favwiki[1].wiki_domain + '/>)', true );
  2465. else text += '\n' + favwiki[0] + ' <https://' + favwiki[1].wiki_domain + '/>';
  2466. }
  2467. }
  2468. }
  2469. }, error => {
  2470. console.log( '- Error while getting the user profile: ' + error );
  2471. } ).finally( () => {
  2472. if ( msg.showEmbed() ) {
  2473. if ( isBlocked ) embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) );
  2474. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2475. }
  2476. else {
  2477. if ( isBlocked ) text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  2478. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2479. }
  2480. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2481. if ( reaction ) reaction.removeEmoji();
  2482. } );
  2483. else if ( wiki.isFandom() ) got.get( 'https://services.fandom.com/user-attribute/user/' + queryuser.userid + '?format=json', {
  2484. headers: {
  2485. Accept: 'application/hal+json'
  2486. },
  2487. responseType: 'json'
  2488. } ).then( presponse => {
  2489. var pbody = presponse.body;
  2490. if ( presponse.statusCode !== 200 || !pbody || pbody.title || !pbody._embedded || !pbody._embedded.properties ) {
  2491. if ( !( pbody && pbody.status === 404 ) ) {
  2492. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && pbody.title ) );
  2493. }
  2494. }
  2495. else {
  2496. var profile = pbody._embedded.properties;
  2497. var discordfield = profile.find( field => field.name === 'discordHandle' );
  2498. var avatarfield = profile.find( field => field.name === 'avatar' );
  2499. var biofield = profile.find( field => field.name === 'bio' );
  2500. if ( discordfield && discordfield.value ) {
  2501. discordfield.value = htmlToPlain( discordfield.value ).replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2502. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  2503. return member.user.tag.escapeFormatting() === discordfield.value;
  2504. } );
  2505. var discordname = [lang.user.info.discord,discordfield.value];
  2506. if ( discordmember ) discordname[1] = discordmember.toString();
  2507. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  2508. else text += '\n' + discordname.join(' ');
  2509. }
  2510. if ( msg.showEmbed() ) {
  2511. if ( avatarfield && avatarfield.value ) embed.setThumbnail( avatarfield.value );
  2512. if ( biofield && biofield.value && !embed.description ) {
  2513. var bio = biofield.value.escapeFormatting();
  2514. if ( bio.length > 2000 ) bio = bio.substring(0, 2000) + '\u2026';
  2515. embed.setDescription( bio );
  2516. }
  2517. }
  2518. }
  2519. }, error => {
  2520. console.log( '- Error while getting the user profile: ' + error );
  2521. } ).finally( () => {
  2522. if ( msg.showEmbed() ) {
  2523. if ( isBlocked ) embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) );
  2524. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2525. }
  2526. else {
  2527. if ( isBlocked ) text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  2528. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2529. }
  2530. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2531. if ( reaction ) reaction.removeEmoji();
  2532. } );
  2533. else {
  2534. if ( isBlocked ) {
  2535. if ( msg.showEmbed() ) embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) );
  2536. else text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  2537. }
  2538. msg.sendChannel( spoiler + text + spoiler, {embed} );
  2539. if ( reaction ) reaction.removeEmoji();
  2540. }
  2541. }
  2542. }
  2543. }, error => {
  2544. console.log( '- Error while getting the search results: ' + error );
  2545. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2546. if ( reaction ) reaction.removeEmoji();
  2547. } );
  2548. }
  2549. }
  2550. function fandom_user(lang, msg, namespace, username, wiki, querystring, fragment, querypage, contribs, reaction, spoiler) {
  2551. if ( /^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2552. got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=blocks&bkprop=user|by|timestamp|expiry|reason&bkip=' + encodeURIComponent( username ) + '&format=json', {
  2553. responseType: 'json'
  2554. } ).then( response => {
  2555. var body = response.body;
  2556. if ( body && body.warnings ) log_warn(body.warnings);
  2557. if ( response.statusCode !== 200 || !body || !body.query || !body.query.blocks ) {
  2558. if ( body && body.error && ( body.error.code === 'param_ip' || body.error.code === 'cidrtoobroad' ) ) {
  2559. if ( querypage.missing !== undefined || querypage.ns === -1 ) {
  2560. msg.reactEmoji('error');
  2561. if ( reaction ) reaction.removeEmoji();
  2562. }
  2563. else {
  2564. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment);
  2565. var embed = new Discord.MessageEmbed().setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2566. got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  2567. var descbody = descresponse.body;
  2568. if ( descresponse.statusCode !== 200 || !descbody ) {
  2569. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  2570. } else {
  2571. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png');
  2572. var parser = new htmlparser.Parser( {
  2573. onopentag: (tagname, attribs) => {
  2574. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2575. var description = attribs.content.escapeFormatting();
  2576. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2577. embed.setDescription( description );
  2578. }
  2579. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2580. thumbnail = attribs.content;
  2581. }
  2582. }
  2583. }, {decodeEntities:true} );
  2584. parser.write( descbody );
  2585. parser.end();
  2586. embed.setThumbnail( thumbnail );
  2587. }
  2588. }, error => {
  2589. console.log( '- Error while getting the description: ' + error );
  2590. } ).finally( () => {
  2591. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2592. if ( reaction ) reaction.removeEmoji();
  2593. } );
  2594. }
  2595. }
  2596. else {
  2597. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2598. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2599. if ( reaction ) reaction.removeEmoji();
  2600. }
  2601. }
  2602. else {
  2603. if ( !querypage.noRedirect || ( querypage.missing === undefined && querypage.ns !== -1 ) ) namespace = contribs;
  2604. var blocks = body.query.blocks.map( block => {
  2605. var isBlocked = false;
  2606. var blockedtimestamp = new Date(block.timestamp).toLocaleString(lang.dateformat, timeoptions);
  2607. var blockexpiry = block.expiry;
  2608. if ( blockexpiry === 'infinity' ) {
  2609. blockexpiry = lang.user.block.until_infinity;
  2610. isBlocked = true;
  2611. } else if ( blockexpiry ) {
  2612. if ( Date.parse(blockexpiry) > Date.now() ) isBlocked = true;
  2613. blockexpiry = new Date(blockexpiry).toLocaleString(lang.dateformat, timeoptions);
  2614. }
  2615. 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 )];
  2616. } ).filter( block => block !== undefined );
  2617. if ( username.includes( '/' ) ) {
  2618. var rangeprefix = username;
  2619. if ( username.includes( ':' ) ) {
  2620. var range = parseInt(username.replace( /^.+\/(\d{2,3})$/, '$1' ), 10);
  2621. if ( range === 128 ) username = username.replace( /^(.+)\/\d{2,3}$/, '$1' );
  2622. else if ( range >= 112 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){7}).+$/, '$1' );
  2623. else if ( range >= 96 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){6}).+$/, '$1' );
  2624. else if ( range >= 80 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){5}).+$/, '$1' );
  2625. else if ( range >= 64 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){4}).+$/, '$1' );
  2626. else if ( range >= 48 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){3}).+$/, '$1' );
  2627. else if ( range >= 32 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){2}).+$/, '$1' );
  2628. else if ( range >= 19 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){1}).+$/, '$1' );
  2629. }
  2630. else {
  2631. var range = parseInt(username.substring(username.length - 2), 10);
  2632. if ( range === 32 ) username = username.replace( /^(.+)\/\d{2}$/, '$1' );
  2633. else if ( range >= 24 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){3}).+$/, '$1' );
  2634. else if ( range >= 16 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){2}).+$/, '$1' );
  2635. }
  2636. }
  2637. got.get( wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=50&ucuser=' + encodeURIComponent( username ) + '&format=json', {
  2638. responseType: 'json'
  2639. } ).then( ucresponse => {
  2640. var ucbody = ucresponse.body;
  2641. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2642. if ( ucbody && ucbody.warnings ) log_warn(ucbody.warnings);
  2643. if ( ucresponse.statusCode !== 200 || !ucbody || !ucbody.query || !ucbody.query.usercontribs ) {
  2644. if ( ucbody && ucbody.error && ucbody.error.code === 'baduser_ucuser' ) {
  2645. msg.reactEmoji('error');
  2646. }
  2647. else {
  2648. console.log( '- ' + ucresponse.statusCode + ': Error while getting the search results: ' + ( ucbody && ucbody.error && ucbody.error.info ) );
  2649. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2650. }
  2651. }
  2652. else {
  2653. var editcount = [lang.user.info.editcount, ( username.includes( '/' ) ? '~' : '' ) + ucbody.query.usercontribs.length + ( ucbody.continue ? '+' : '' )];
  2654. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2655. if ( msg.showEmbed() ) {
  2656. var text = '<' + pagelink + '>';
  2657. 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) + ')' );
  2658. if ( blocks.length ) blocks.forEach( block => embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) ) );
  2659. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2660. }
  2661. else {
  2662. var embed = {};
  2663. var text = '<' + pagelink + '>\n\n' + editcount.join(' ');
  2664. if ( blocks.length ) blocks.forEach( block => text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext() );
  2665. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2666. }
  2667. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2668. }
  2669. }, error => {
  2670. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  2671. console.log( '- Error while getting the search results: ' + error );
  2672. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general) + '>' + spoiler );
  2673. } ).finally( () => {
  2674. if ( reaction ) reaction.removeEmoji();
  2675. } );
  2676. }
  2677. }, error => {
  2678. console.log( '- Error while getting the search results: ' + error );
  2679. msg.sendChannelError( spoiler + '<' + wiki.toLink(( querypage.noRedirect ? namespace : contribs ) + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2680. if ( reaction ) reaction.removeEmoji();
  2681. } );
  2682. } else {
  2683. 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', {
  2684. responseType: 'json'
  2685. } ).then( response => {
  2686. var body = response.body;
  2687. if ( body && body.warnings ) log_warn(body.warnings);
  2688. if ( response.statusCode !== 200 || !body || !body.query || !body.query.users ) {
  2689. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  2690. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2691. if ( reaction ) reaction.removeEmoji();
  2692. }
  2693. else {
  2694. var queryuser = body.query.users[0];
  2695. if ( !queryuser ) {
  2696. if ( querypage.missing !== undefined || querypage.ns === -1 ) {
  2697. msg.reactEmoji('🤷');
  2698. if ( reaction ) reaction.removeEmoji();
  2699. }
  2700. else {
  2701. var pagelink = wiki.toLink(querypage.title, querystring.toTitle(), fragment, body.query.general);
  2702. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  2703. got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  2704. var descbody = descresponse.body;
  2705. if ( descresponse.statusCode !== 200 || !descbody ) {
  2706. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  2707. } else {
  2708. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  2709. var parser = new htmlparser.Parser( {
  2710. onopentag: (tagname, attribs) => {
  2711. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2712. var description = attribs.content.escapeFormatting();
  2713. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2714. embed.setDescription( description );
  2715. }
  2716. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2717. thumbnail = attribs.content;
  2718. }
  2719. }
  2720. }, {decodeEntities:true} );
  2721. parser.write( descbody );
  2722. parser.end();
  2723. embed.setThumbnail( thumbnail );
  2724. }
  2725. }, error => {
  2726. console.log( '- Error while getting the description: ' + error );
  2727. } ).finally( () => {
  2728. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2729. if ( reaction ) reaction.removeEmoji();
  2730. } );
  2731. }
  2732. }
  2733. else {
  2734. username = queryuser.name;
  2735. var gender = [lang.user.info.gender];
  2736. switch (queryuser.gender) {
  2737. case 'male':
  2738. gender.push(lang.user.gender.male);
  2739. break;
  2740. case 'female':
  2741. gender.push(lang.user.gender.female);
  2742. break;
  2743. default:
  2744. gender.push(lang.user.gender.unknown);
  2745. }
  2746. var registration = [lang.user.info.registration, new Date(queryuser.registration).toLocaleString(lang.dateformat, timeoptions)];
  2747. var editcount = [lang.user.info.editcount, queryuser.editcount];
  2748. var groups = queryuser.groups;
  2749. var group = [lang.user.info.group];
  2750. var grouplist = lang.user.groups;
  2751. for ( var i = 0; i < grouplist.length; i++ ) {
  2752. if ( groups.includes( grouplist[i][0] ) && ( group.length === 1 || grouplist[i][0] !== 'user' ) ) {
  2753. if ( grouplist[i][0] === 'wiki-manager' && body.query.allmessages[0]['*'] === username ) {
  2754. group.push('**' + grouplist[i][1] + '**');
  2755. }
  2756. else group.push(grouplist[i][1]);
  2757. }
  2758. }
  2759. var isBlocked = false;
  2760. var blockedtimestamp = new Date(queryuser.blockedtimestamp).toLocaleString(lang.dateformat, timeoptions);
  2761. var blockexpiry = queryuser.blockexpiry;
  2762. if ( blockexpiry === 'infinity' ) {
  2763. blockexpiry = lang.user.block.until_infinity;
  2764. isBlocked = true;
  2765. } else if ( blockexpiry ) {
  2766. var blockexpirydate = blockexpiry.replace( /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2,3})/, '$1-$2-$3T$4:$5:$6Z' );
  2767. blockexpiry = new Date(blockexpirydate).toLocaleString(lang.dateformat, timeoptions);
  2768. if ( Date.parse(blockexpirydate) > Date.now() ) isBlocked = true;
  2769. }
  2770. var blockedby = '[[User:' + queryuser.blockedby + '|' + queryuser.blockedby + ']]';
  2771. var blockreason = queryuser.blockreason;
  2772. 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 )];
  2773. var pagelink = wiki.toLink(namespace + username, querystring.toTitle(), fragment, body.query.general);
  2774. if ( msg.showEmbed() ) {
  2775. var text = '<' + pagelink + '>';
  2776. 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 );
  2777. }
  2778. else {
  2779. var embed = {};
  2780. var text = '<' + pagelink + '>\n\n' + gender.join(' ') + '\n' + registration.join(' ') + '\n' + editcount.join(' ') + '\n' + group[0] + ' ' + group.slice(1).join(', ');
  2781. }
  2782. got.get( 'https://services.fandom.com/user-attribute/user/' + queryuser.userid + '?format=json', {
  2783. headers: {
  2784. Accept: 'application/hal+json'
  2785. },
  2786. responseType: 'json'
  2787. } ).then( presponse => {
  2788. var pbody = presponse.body;
  2789. if ( presponse.statusCode !== 200 || !pbody || pbody.title || !pbody._embedded || !pbody._embedded.properties ) {
  2790. if ( !( pbody && pbody.status === 404 ) ) {
  2791. console.log( '- ' + presponse.statusCode + ': Error while getting the user profile: ' + ( pbody && pbody.title ) );
  2792. }
  2793. }
  2794. else {
  2795. var profile = pbody._embedded.properties;
  2796. var discordfield = profile.find( field => field.name === 'discordHandle' );
  2797. var avatarfield = profile.find( field => field.name === 'avatar' );
  2798. var biofield = profile.find( field => field.name === 'bio' );
  2799. if ( discordfield && discordfield.value ) {
  2800. discordfield.value = htmlToPlain( discordfield.value ).replace( /^\s*([^@#:]{2,32}?)\s*#(\d{4,6})\s*$/, '$1#$2' );
  2801. if ( msg.channel.type === 'text' ) var discordmember = msg.guild.members.cache.find( member => {
  2802. return member.user.tag.escapeFormatting() === discordfield.value;
  2803. } );
  2804. var discordname = [lang.user.info.discord,discordfield.value];
  2805. if ( discordmember ) discordname[1] = discordmember.toString();
  2806. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  2807. else text += '\n' + discordname.join(' ');
  2808. }
  2809. if ( msg.showEmbed() ) {
  2810. if ( avatarfield && avatarfield.value ) embed.setThumbnail( avatarfield.value );
  2811. if ( biofield && biofield.value && !embed.description ) {
  2812. var bio = biofield.value.escapeFormatting();
  2813. if ( bio.length > 2000 ) bio = bio.substring(0, 2000) + '\u2026';
  2814. embed.setDescription( bio );
  2815. }
  2816. }
  2817. }
  2818. }, error => {
  2819. console.log( '- Error while getting the user profile: ' + error );
  2820. } ).finally( () => {
  2821. if ( msg.showEmbed() ) {
  2822. if ( isBlocked ) embed.addField( block[0], block[1].toMarkdown(wiki, body.query.general) );
  2823. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) embed.addField( '\u200b', '<a:loading:641343250661113886> **' + lang.user.info.loading + '**' );
  2824. }
  2825. else {
  2826. if ( isBlocked ) text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  2827. if ( msg.channel.type === 'text' && msg.guild.id in patreons ) text += '\n\n<a:loading:641343250661113886> **' + lang.user.info.loading + '**';
  2828. }
  2829. msg.sendChannel( spoiler + text + spoiler, {embed} ).then( message => global_block(lang, message, username, text, embed, wiki, spoiler) );
  2830. if ( reaction ) reaction.removeEmoji();
  2831. } );
  2832. }
  2833. }
  2834. }, error => {
  2835. console.log( '- Error while getting the search results: ' + error );
  2836. msg.sendChannelError( spoiler + '<' + wiki.toLink(namespace + username, querystring.toTitle(), fragment) + '>' + spoiler );
  2837. if ( reaction ) reaction.removeEmoji();
  2838. } );
  2839. }
  2840. }
  2841. function global_block(lang, msg, username, text, embed, wiki, spoiler) {
  2842. if ( !msg || msg.channel.type !== 'text' || !( msg.guild.id in patreons ) ) return;
  2843. if ( msg.showEmbed() ) embed.fields.pop();
  2844. else {
  2845. let splittext = text.split('\n\n');
  2846. splittext.pop();
  2847. text = splittext.join('\n\n');
  2848. }
  2849. if ( wiki.isFandom() ) got.get( 'https://community.fandom.com/Special:Contributions/' + encodeURIComponent( username ) + '?limit=1' ).then( response => {
  2850. var body = response.body;
  2851. if ( response.statusCode !== 200 || !body ) {
  2852. console.log( '- ' + response.statusCode + ': Error while getting the global block.' );
  2853. }
  2854. else {
  2855. let $ = cheerio.load(body);
  2856. if ( $('#mw-content-text .errorbox').length ) {
  2857. if ( msg.showEmbed() ) embed.addField( lang.user.gblock.disabled, '\u200b' );
  2858. else text += '\n\n**' + lang.user.gblock.disabled + '**';
  2859. }
  2860. else if ( $('.mw-warning-with-logexcerpt').length && !$(".mw-warning-with-logexcerpt .mw-logline-block").length ) {
  2861. if ( msg.showEmbed() ) embed.addField( lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting(), '\u200b' );
  2862. else text += '\n\n**' + lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting() + '**';
  2863. }
  2864. }
  2865. }, error => {
  2866. console.log( '- Error while getting the global block: ' + error );
  2867. } ).finally( () => {
  2868. if ( !/^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2869. got.get( 'https://community.fandom.com/wiki/Special:Editcount/' + encodeURIComponent( username ) ).then( gresponse => {
  2870. var gbody = gresponse.body;
  2871. if ( gresponse.statusCode !== 200 || !gbody ) {
  2872. console.log( '- ' + gresponse.statusCode + ': Error while getting the global edit count.' );
  2873. }
  2874. else {
  2875. let $ = cheerio.load(gbody);
  2876. var globaledits = $('#editcount .TablePager th').eq(7).text().replace( /[,\.]/g, '' );
  2877. if ( globaledits ) {
  2878. 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});
  2879. else {
  2880. let splittext = text.split('\n');
  2881. splittext.splice(5, 0, lang.user.info.globaleditcount + ' ' + globaledits);
  2882. text = splittext.join('\n');
  2883. }
  2884. }
  2885. }
  2886. }, error => {
  2887. console.log( '- Error while getting the global edit count: ' + error );
  2888. } ).finally( () => {
  2889. msg.edit( spoiler + text + spoiler, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  2890. } );
  2891. }
  2892. else msg.edit( spoiler + text + spoiler, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  2893. } );
  2894. else if ( wiki.endsWith( '.gamepedia.com/' ) ) got.get( 'https://help.gamepedia.com/Special:GlobalBlockList/' + encodeURIComponent( username ) + '?uselang=qqx' ).then( response => {
  2895. var body = response.body;
  2896. if ( response.statusCode !== 200 || !body ) {
  2897. console.log( '- ' + response.statusCode + ': Error while getting the global block.' );
  2898. }
  2899. else {
  2900. let $ = cheerio.load(body);
  2901. var gblock = $('.mw-blocklist');
  2902. if ( gblock.length ) {
  2903. var reason = gblock.find('.TablePager_col_reason').text().replace( /\)$/, '' ).split(', ');
  2904. 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);
  2905. var expiry = gblock.find('.TablePager_col_expiry').text();
  2906. if ( expiry.startsWith( '(infiniteblock)' ) ) expiry = lang.user.block.until_infinity;
  2907. 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);
  2908. if ( msg.showEmbed() ) {
  2909. var gblocktitle = lang.user.gblock.header.replaceSave( '%s', username ).escapeFormatting();
  2910. 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() );
  2911. if ( globalblock ) globalblock.name = gblocktitle;
  2912. else {
  2913. 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(', ') );
  2914. embed.addField( gblocktitle, gblocktext.toMarkdown( reason[3].replace( /Special:BlockList$/, '' ) ) );
  2915. }
  2916. }
  2917. else {
  2918. let splittext = text.split('\n\n');
  2919. 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());
  2920. 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();
  2921. 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());
  2922. text = splittext.join('\n\n');
  2923. }
  2924. }
  2925. }
  2926. }, error => {
  2927. console.log( '- Error while getting the global block: ' + error );
  2928. } ).finally( () => {
  2929. if ( !/^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  2930. got.get( 'https://help.gamepedia.com/UserProfile:' + encodeURIComponent( username ) ).then( gresponse => {
  2931. var gbody = gresponse.body;
  2932. if ( gresponse.statusCode !== 200 || !gbody ) {
  2933. console.log( '- ' + gresponse.statusCode + ': Error while getting the global edit count.' );
  2934. }
  2935. else {
  2936. let $ = cheerio.load(gbody);
  2937. var wikisedited = $('.curseprofile .rightcolumn .section.stats dd').eq(0).text().replace( /[,\.]/g, '' );
  2938. if ( wikisedited ) {
  2939. if ( msg.showEmbed() ) embed.spliceFields(1, 0, {name:lang.user.info.wikisedited,value:wikisedited,inline:true});
  2940. else {
  2941. let splittext = text.split('\n');
  2942. splittext.splice(5, 0, lang.user.info.wikisedited + ' ' + wikisedited);
  2943. text = splittext.join('\n');
  2944. }
  2945. }
  2946. var globaledits = $('.curseprofile .rightcolumn .section.stats dd').eq(2).text().replace( /[,\.]/g, '' );
  2947. if ( globaledits ) {
  2948. 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});
  2949. else {
  2950. let splittext = text.split('\n');
  2951. splittext.splice(5, 0, lang.user.info.globaleditcount + ' ' + globaledits);
  2952. text = splittext.join('\n');
  2953. }
  2954. }
  2955. }
  2956. }, error => {
  2957. console.log( '- Error while getting the global edit count: ' + error );
  2958. } ).finally( () => {
  2959. msg.edit( spoiler + text + spoiler, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  2960. } );
  2961. }
  2962. else msg.edit( spoiler + text + spoiler, {embed,allowedMentions:{parse:[]}} ).catch(log_error);
  2963. } );
  2964. }
  2965. function fandom_discussion(lang, msg, wiki, title, query, reaction, spoiler) {
  2966. if ( !title ) {
  2967. var pagelink = wiki + 'f';
  2968. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename ).setTitle( lang.discussion.main ).setURL( pagelink );
  2969. got.get( wiki + 'f' ).then( descresponse => {
  2970. var descbody = descresponse.body;
  2971. if ( descresponse.statusCode !== 200 || !descbody ) {
  2972. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  2973. } else {
  2974. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', query.general);
  2975. var parser = new htmlparser.Parser( {
  2976. onopentag: (tagname, attribs) => {
  2977. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2978. var description = attribs.content.escapeFormatting();
  2979. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2980. embed.setDescription( description );
  2981. }
  2982. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2983. thumbnail = attribs.content;
  2984. }
  2985. }
  2986. }, {decodeEntities:true} );
  2987. parser.write( descbody );
  2988. parser.end();
  2989. embed.setThumbnail( thumbnail );
  2990. }
  2991. }, error => {
  2992. console.log( '- Error while getting the description: ' + error );
  2993. } ).finally( () => {
  2994. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  2995. if ( reaction ) reaction.removeEmoji();
  2996. } );
  2997. }
  2998. else if ( !query.wikidesc ) {
  2999. return got.get( 'https://community.fandom.com/api/v1/Wikis/ByString?includeDomain=true&limit=10&string=' + query.general.servername + query.general.scriptpath + '&format=json', {
  3000. responseType: 'json'
  3001. } ).then( wvresponse => {
  3002. var wvbody = wvresponse.body;
  3003. if ( wvresponse.statusCode !== 200 || !wvbody || wvbody.exception || !wvbody.items || !wvbody.items.length ) {
  3004. console.log( '- ' + wvresponse.statusCode + ': Error while getting the wiki id: ' + ( wvbody && wvbody.exception && wvbody.exception.details ) );
  3005. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3006. if ( reaction ) reaction.removeEmoji();
  3007. }
  3008. else if ( wvbody.items.some( site => site.domain === query.general.servername + query.general.scriptpath ) ) {
  3009. query.wikidesc = {id: wvbody.items.find( site => site.domain === query.general.servername + query.general.scriptpath ).id};
  3010. fandom_discussion(lang, msg, wiki, title, query, reaction, spoiler);
  3011. }
  3012. else {
  3013. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3014. if ( reaction ) reaction.removeEmoji();
  3015. }
  3016. }, error => {
  3017. console.log( '- Error while getting the wiki id: ' + error );
  3018. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3019. if ( reaction ) reaction.removeEmoji();
  3020. } );
  3021. }
  3022. else if ( title.split(' ')[0].toLowerCase() === 'post' || title.split(' ')[0].toLowerCase() === lang.discussion.post ) {
  3023. title = title.split(' ').slice(1).join(' ');
  3024. var limit = ( msg.channel.type === 'text' && msg.guild.id in patreons ? '100' : '50' );
  3025. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/posts?limit=' + limit + '&format=json', {
  3026. headers: {
  3027. Accept: 'application/hal+json'
  3028. },
  3029. responseType: 'json'
  3030. } ).then( response => {
  3031. var body = response.body;
  3032. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded['doc:posts'] ) {
  3033. console.log( '- ' + response.statusCode + ': Error while getting the posts: ' + ( body && body.title ) );
  3034. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3035. if ( reaction ) reaction.removeEmoji();
  3036. }
  3037. else if ( body._embedded['doc:posts'].length ) {
  3038. var posts = body._embedded['doc:posts'];
  3039. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename );
  3040. if ( posts.some( post => post.id === title ) ) {
  3041. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.id === title ), embed, spoiler);
  3042. if ( reaction ) reaction.removeEmoji();
  3043. }
  3044. else if ( /^\d+$/.test(title) ) {
  3045. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/posts/' + title + '?format=json', {
  3046. headers: {
  3047. Accept: 'application/hal+json'
  3048. },
  3049. responseType: 'json'
  3050. } ).then( presponse => {
  3051. var pbody = presponse.body;
  3052. if ( presponse.statusCode !== 200 || !pbody || pbody.id !== title ) {
  3053. if ( pbody && pbody.title === 'The requested resource was not found.' ) {
  3054. if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3055. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3056. }
  3057. else msg.reactEmoji('🤷');
  3058. }
  3059. else {
  3060. console.log( '- ' + presponse.statusCode + ': Error while getting the post: ' + ( pbody && pbody.title ) );
  3061. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3062. }
  3063. if ( reaction ) reaction.removeEmoji();
  3064. }
  3065. else if ( pbody.title ) {
  3066. fandom_discussionsend(lang, msg, wiki, pbody, embed, spoiler);
  3067. if ( reaction ) reaction.removeEmoji();
  3068. }
  3069. else got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads/' + pbody.threadId + '?format=json', {
  3070. headers: {
  3071. Accept: 'application/hal+json'
  3072. },
  3073. responseType: 'json'
  3074. } ).then( thresponse => {
  3075. var thbody = thresponse.body;
  3076. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== pbody.threadId ) {
  3077. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  3078. embed.setTitle( '~~' + pbody.threadId + '~~' );
  3079. }
  3080. else embed.setTitle( thbody.title.escapeFormatting() );
  3081. }, error => {
  3082. console.log( '- Error while getting the thread: ' + error );
  3083. embed.setTitle( '~~' + pbody.threadId + '~~' );
  3084. } ).finally( () => {
  3085. fandom_discussionsend(lang, msg, wiki, pbody, embed, spoiler);
  3086. if ( reaction ) reaction.removeEmoji();
  3087. } );
  3088. }, error => {
  3089. console.log( '- Error while getting the post: ' + error );
  3090. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3091. if ( reaction ) reaction.removeEmoji();
  3092. } );
  3093. }
  3094. else if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3095. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3096. if ( reaction ) reaction.removeEmoji();
  3097. }
  3098. else {
  3099. msg.reactEmoji('🤷');
  3100. if ( reaction ) reaction.removeEmoji();
  3101. }
  3102. }
  3103. else {
  3104. msg.reactEmoji('🤷');
  3105. if ( reaction ) reaction.removeEmoji();
  3106. }
  3107. }, error => {
  3108. console.log( '- Error while getting the posts: ' + error );
  3109. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3110. if ( reaction ) reaction.removeEmoji();
  3111. } );
  3112. }
  3113. else {
  3114. var limit = ( msg.channel.type === 'text' && msg.guild.id in patreons ? '100' : '50' );
  3115. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads?sortKey=trending&limit=' + limit + '&format=json', {
  3116. headers: {
  3117. Accept: 'application/hal+json'
  3118. },
  3119. responseType: 'json'
  3120. } ).then( response => {
  3121. var body = response.body;
  3122. if ( response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded.threads ) {
  3123. console.log( '- ' + response.statusCode + ': Error while getting the threads: ' + ( body && body.title ) );
  3124. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3125. if ( reaction ) reaction.removeEmoji();
  3126. }
  3127. else if ( body._embedded.threads.length ) {
  3128. var threads = body._embedded.threads;
  3129. var embed = new Discord.MessageEmbed().setAuthor( query.general.sitename );
  3130. if ( threads.some( thread => thread.id === title ) ) {
  3131. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.id === title ), embed, spoiler);
  3132. if ( reaction ) reaction.removeEmoji();
  3133. }
  3134. else if ( threads.some( thread => thread.title === title ) ) {
  3135. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title === title ), embed, spoiler);
  3136. if ( reaction ) reaction.removeEmoji();
  3137. }
  3138. else if ( threads.some( thread => thread.title.toLowerCase() === title.toLowerCase() ) ) {
  3139. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase() === title.toLowerCase() ), embed, spoiler);
  3140. if ( reaction ) reaction.removeEmoji();
  3141. }
  3142. else if ( threads.some( thread => thread.title.includes( title ) ) ) {
  3143. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.includes( title ) ), embed, spoiler);
  3144. if ( reaction ) reaction.removeEmoji();
  3145. }
  3146. else if ( threads.some( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3147. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3148. if ( reaction ) reaction.removeEmoji();
  3149. }
  3150. else if ( /^\d+$/.test(title) ) {
  3151. got.get( 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads/' + title + '?format=json', {
  3152. headers: {
  3153. Accept: 'application/hal+json'
  3154. },
  3155. responseType: 'json'
  3156. } ).then( thresponse => {
  3157. var thbody = thresponse.body;
  3158. if ( thresponse.statusCode !== 200 || !thbody || thbody.id !== title ) {
  3159. if ( thbody && thbody.status === 404 ) {
  3160. if (threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3161. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3162. }
  3163. else msg.reactEmoji('🤷');
  3164. }
  3165. else {
  3166. console.log( '- ' + thresponse.statusCode + ': Error while getting the thread: ' + ( thbody && thbody.title ) );
  3167. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  3168. }
  3169. }
  3170. else fandom_discussionsend(lang, msg, wiki, thbody, embed, spoiler);
  3171. }, error => {
  3172. console.log( '- Error while getting the thread: ' + error );
  3173. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  3174. } ).finally( () => {
  3175. if ( reaction ) reaction.removeEmoji();
  3176. } );
  3177. }
  3178. else if ( threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  3179. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  3180. if ( reaction ) reaction.removeEmoji();
  3181. }
  3182. else {
  3183. msg.reactEmoji('🤷');
  3184. if ( reaction ) reaction.removeEmoji();
  3185. }
  3186. }
  3187. else {
  3188. msg.reactEmoji('🤷');
  3189. if ( reaction ) reaction.removeEmoji();
  3190. }
  3191. }, error => {
  3192. console.log( '- Error while getting the threads: ' + error );
  3193. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  3194. if ( reaction ) reaction.removeEmoji();
  3195. } );
  3196. }
  3197. }
  3198. function fandom_discussionsend(lang, msg, wiki, discussion, embed, spoiler) {
  3199. if ( discussion.title ) {
  3200. embed.setTitle( discussion.title.escapeFormatting() );
  3201. var pagelink = wiki + 'f/p/' + ( discussion.threadId || discussion.id );
  3202. }
  3203. else {
  3204. if ( discussion._embedded.thread ) embed.setTitle( discussion._embedded.thread[0].title.escapeFormatting() );
  3205. var pagelink = wiki + 'f/p/' + discussion.threadId + '/r/' + discussion.id;
  3206. }
  3207. var text = '<' + pagelink + '>';
  3208. embed.setURL( pagelink ).setFooter( discussion.createdBy.name, discussion.createdBy.avatarUrl ).setTimestamp( discussion.creationDate.epochSecond * 1000 );
  3209. var description = '';
  3210. switch ( discussion.funnel ) {
  3211. case 'IMAGE':
  3212. embed.setImage( discussion._embedded.contentImages[0].url );
  3213. break;
  3214. case 'POLL':
  3215. 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 ) );
  3216. break;
  3217. case 'QUIZ':
  3218. description = discussion.quiz.title.escapeFormatting();
  3219. if ( discussion._embedded.openGraph ) embed.setThumbnail( discussion._embedded.openGraph[0].imageUrl );
  3220. break;
  3221. default:
  3222. if ( discussion.jsonModel ) {
  3223. try {
  3224. description = discussion_formatting(JSON.parse(discussion.jsonModel)).replace( /(?:\*\*\*\*|(?<!\\)\_\_)/g, '' ).replace( /{@wiki}/g, wiki );
  3225. if ( discussion._embedded.contentImages.length ) {
  3226. if ( description.trim().endsWith( '{@0}' ) ) {
  3227. embed.setImage( discussion._embedded.contentImages[0].url );
  3228. description = description.replace( '{@0}', '' ).trim();
  3229. }
  3230. else {
  3231. description = description.replace( /\{\@(\d+)\}/g, (match, n) => {
  3232. if ( n >= discussion._embedded.contentImages.length ) return '';
  3233. else return '[__' + lang.discussion.image.escapeFormatting() + '__](' + discussion._embedded.contentImages[n].url + ')';
  3234. } );
  3235. embed.setThumbnail( discussion._embedded.contentImages[0].url );
  3236. }
  3237. }
  3238. else embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png') );
  3239. }
  3240. catch ( jsonerror ) {
  3241. console.log( '- Error while getting the formatting: ' + jsonerror );
  3242. description = discussion.rawContent.escapeFormatting();
  3243. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  3244. }
  3245. }
  3246. else if ( discussion.renderedContent ) {
  3247. var current_tag = '';
  3248. var parser = new htmlparser.Parser( {
  3249. onopentag: (tagname, attribs) => {
  3250. if ( tagname === 'a' ) {
  3251. current_tag = attribs.href;
  3252. description += '[';
  3253. }
  3254. },
  3255. ontext: (htmltext) => {
  3256. description += htmltext.escapeFormatting();
  3257. },
  3258. onclosetag: (tagname) => {
  3259. if ( tagname === 'a' ) {
  3260. description += '](' + current_tag + ')';
  3261. current_tag = '';
  3262. }
  3263. if ( tagname === 'p' ) description += '\n';
  3264. }
  3265. }, {decodeEntities:true} );
  3266. parser.write( discussion.renderedContent );
  3267. parser.end();
  3268. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  3269. }
  3270. else {
  3271. description = discussion.rawContent.escapeFormatting();
  3272. if ( discussion._embedded.contentImages.length ) embed.setThumbnail( discussion._embedded.contentImages[0].url );
  3273. }
  3274. }
  3275. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  3276. embed.setDescription( description );
  3277. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3278. }
  3279. function gamepedia_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  3280. if ( args[0] ) {
  3281. var error = false;
  3282. var title = '';
  3283. var revision = 0;
  3284. var diff = 0;
  3285. var relative = 'prev';
  3286. if ( /^\d+$/.test(args[0]) ) {
  3287. revision = parseInt(args[0], 10);
  3288. if ( args[1] ) {
  3289. if ( /^\d+$/.test(args[1]) ) {
  3290. diff = parseInt(args[1], 10);
  3291. }
  3292. else if ( args[1] === 'prev' || args[1] === 'next' || args[1] === 'cur' ) {
  3293. relative = args[1];
  3294. }
  3295. else error = true;
  3296. }
  3297. }
  3298. else if ( args[0] === 'prev' || args[0] === 'next' || args[0] === 'cur' ) {
  3299. relative = args[0];
  3300. if ( args[1] ) {
  3301. if ( /^\d+$/.test(args[1]) ) {
  3302. revision = parseInt(args[1], 10);
  3303. }
  3304. else error = true;
  3305. }
  3306. else error = true;
  3307. }
  3308. else title = args.join(' ');
  3309. if ( error ) {
  3310. msg.reactEmoji('error');
  3311. if ( reaction ) reaction.removeEmoji();
  3312. }
  3313. else if ( diff ) {
  3314. gamepedia_diffsend(lang, msg, [diff, revision], wiki, reaction, spoiler);
  3315. }
  3316. else {
  3317. got.get( wiki + 'api.php?action=compare&prop=ids|diff' + ( title ? '&fromtitle=' + encodeURIComponent( title ) : '&fromrev=' + revision ) + '&torelative=' + relative + '&format=json', {
  3318. responseType: 'json'
  3319. } ).then( response => {
  3320. var body = response.body;
  3321. if ( body && body.warnings ) log_warn(body.warnings);
  3322. if ( response.statusCode !== 200 || !body || !body.compare ) {
  3323. var noerror = false;
  3324. if ( body && body.error ) {
  3325. switch ( body.error.code ) {
  3326. case 'nosuchrevid':
  3327. noerror = true;
  3328. break;
  3329. case 'missingtitle':
  3330. noerror = true;
  3331. break;
  3332. case 'invalidtitle':
  3333. noerror = true;
  3334. break;
  3335. case 'missingcontent':
  3336. noerror = true;
  3337. break;
  3338. default:
  3339. noerror = false;
  3340. }
  3341. }
  3342. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3343. console.log( '- This wiki doesn\'t exist!' );
  3344. msg.reactEmoji('nowiki');
  3345. }
  3346. else if ( noerror ) {
  3347. msg.replyMsg( lang.diff.badrev );
  3348. }
  3349. else {
  3350. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3351. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + relative + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  3352. }
  3353. if ( reaction ) reaction.removeEmoji();
  3354. }
  3355. else {
  3356. if ( body.compare.fromarchive !== undefined || body.compare.toarchive !== undefined ) {
  3357. msg.reactEmoji('error');
  3358. if ( reaction ) reaction.removeEmoji();
  3359. } else {
  3360. var argids = [];
  3361. var ids = body.compare;
  3362. if ( ids.fromrevid && !ids.torevid ) argids = [ids.fromrevid];
  3363. else if ( !ids.fromrevid && ids.torevid ) argids = [ids.torevid];
  3364. else {
  3365. argids = [ids.torevid, ids.fromrevid];
  3366. var compare = ['', ''];
  3367. if ( ids.fromtexthidden === undefined && ids.totexthidden === undefined && ids['*'] !== undefined ) {
  3368. var more = '\n__' + lang.diff.info.more + '__';
  3369. var current_tag = '';
  3370. var small_prev_ins = '';
  3371. var small_prev_del = '';
  3372. var ins_length = more.length;
  3373. var del_length = more.length;
  3374. var added = false;
  3375. var parser = new htmlparser.Parser( {
  3376. onopentag: (tagname, attribs) => {
  3377. if ( tagname === 'ins' || tagname == 'del' ) {
  3378. current_tag = tagname;
  3379. }
  3380. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3381. current_tag = tagname+'a';
  3382. }
  3383. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3384. current_tag = tagname+"d";
  3385. }
  3386. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3387. added = true;
  3388. }
  3389. },
  3390. ontext: (htmltext) => {
  3391. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3392. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3393. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3394. else small_prev_ins += more;
  3395. }
  3396. if ( current_tag === 'del' && del_length <= 1000 ) {
  3397. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3398. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3399. else small_prev_del += more;
  3400. }
  3401. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3402. ins_length += htmltext.escapeFormatting().length;
  3403. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3404. else small_prev_ins += more;
  3405. }
  3406. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3407. del_length += htmltext.escapeFormatting().length;
  3408. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3409. else small_prev_del += more;
  3410. }
  3411. if ( added ) {
  3412. if ( htmltext === '+' && ins_length <= 1000 ) {
  3413. ins_length++;
  3414. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3415. else small_prev_ins += more;
  3416. }
  3417. if ( htmltext === '−' && del_length <= 1000 ) {
  3418. del_length++;
  3419. if ( del_length <= 1000 ) small_prev_del += '\n';
  3420. else small_prev_del += more;
  3421. }
  3422. added = false;
  3423. }
  3424. },
  3425. onclosetag: (tagname) => {
  3426. if ( tagname === 'ins' ) {
  3427. current_tag = 'afterins';
  3428. } else if ( tagname === 'del' ) {
  3429. current_tag = 'afterdel';
  3430. } else {
  3431. current_tag = '';
  3432. }
  3433. }
  3434. }, {decodeEntities:true} );
  3435. parser.write( ids['*'] );
  3436. parser.end();
  3437. if ( small_prev_del.length ) {
  3438. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3439. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  3440. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  3441. }
  3442. if ( small_prev_ins.length ) {
  3443. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3444. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  3445. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  3446. }
  3447. }
  3448. else if ( ids.fromtexthidden !== undefined ) compare[0] = '__' + lang.diff.hidden + '__';
  3449. else if ( ids.totexthidden !== undefined ) compare[1] = '__' + lang.diff.hidden + '__';
  3450. }
  3451. gamepedia_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  3452. }
  3453. }
  3454. }, error => {
  3455. if ( wiki.noWiki(error.message) ) {
  3456. console.log( '- This wiki doesn\'t exist!' );
  3457. msg.reactEmoji('nowiki');
  3458. }
  3459. else {
  3460. console.log( '- Error while getting the search results: ' + error );
  3461. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + relative + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  3462. }
  3463. if ( reaction ) reaction.removeEmoji();
  3464. } );
  3465. }
  3466. }
  3467. else {
  3468. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, {embed} );
  3469. else msg.reactEmoji('error');
  3470. if ( reaction ) reaction.removeEmoji();
  3471. }
  3472. }
  3473. function gamepedia_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  3474. 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', {
  3475. responseType: 'json'
  3476. } ).then( response => {
  3477. var body = response.body;
  3478. if ( body && body.warnings ) log_warn(body.warnings);
  3479. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  3480. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3481. console.log( '- This wiki doesn\'t exist!' );
  3482. msg.reactEmoji('nowiki');
  3483. }
  3484. else {
  3485. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3486. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3487. }
  3488. if ( reaction ) reaction.removeEmoji();
  3489. }
  3490. else {
  3491. if ( body.query.badrevids ) {
  3492. msg.replyMsg( lang.diff.badrev );
  3493. if ( reaction ) reaction.removeEmoji();
  3494. }
  3495. else if ( body.query.pages && !body.query.pages['-1'] ) {
  3496. var pages = Object.values(body.query.pages);
  3497. if ( pages.length !== 1 ) {
  3498. msg.sendChannel( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0], '', '', body.query.general) + '>' + spoiler );
  3499. if ( reaction ) reaction.removeEmoji();
  3500. }
  3501. else {
  3502. var title = pages[0].title;
  3503. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  3504. var diff = revisions[0].revid;
  3505. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  3506. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  3507. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  3508. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  3509. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  3510. 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 ) )];
  3511. 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(', ')];
  3512. var pagelink = wiki.toLink(title, 'diff=' + diff + '&oldid=' + oldid, '', body.query.general);
  3513. if ( msg.showEmbed() ) {
  3514. var text = '<' + pagelink + '>';
  3515. var editorlink = '[' + editor[1] + '](' + wiki.toLink('User:' + editor[1], '', '', body.query.general, true) + ')';
  3516. if ( revisions[0].anon !== undefined ) {
  3517. editorlink = '[' + editor[1] + '](' + wiki.toLink('Special:Contributions/' + editor[1], '', '', body.query.general, true) + ')';
  3518. }
  3519. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  3520. 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] );
  3521. if ( tags ) {
  3522. var taglink = '';
  3523. var tagtext = '';
  3524. var tagparser = new htmlparser.Parser( {
  3525. onopentag: (tagname, attribs) => {
  3526. if ( tagname === 'a' ) taglink = attribs.href;
  3527. },
  3528. ontext: (htmltext) => {
  3529. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  3530. else tagtext += htmltext.escapeFormatting();
  3531. },
  3532. onclosetag: (tagname) => {
  3533. if ( tagname === 'a' ) taglink = '';
  3534. }
  3535. }, {decodeEntities:true} );
  3536. tagparser.write( tags[1] );
  3537. tagparser.end();
  3538. embed.addField( tags[0], tagtext );
  3539. }
  3540. var more = '\n__' + lang.diff.info.more + '__';
  3541. if ( !compare && oldid ) got.get( wiki + 'api.php?action=compare&prop=diff&fromrev=' + oldid + '&torev=' + diff + '&format=json', {
  3542. responseType: 'json'
  3543. } ).then( cpresponse => {
  3544. var cpbody = cpresponse.body;
  3545. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  3546. if ( cpresponse.statusCode !== 200 || !cpbody || !cpbody.compare || cpbody.compare['*'] === undefined ) {
  3547. var noerror = false;
  3548. if ( cpbody && cpbody.error ) {
  3549. switch ( cpbody.error.code ) {
  3550. case 'nosuchrevid':
  3551. noerror = true;
  3552. break;
  3553. case 'missingcontent':
  3554. noerror = true;
  3555. break;
  3556. default:
  3557. noerror = false;
  3558. }
  3559. }
  3560. if ( !noerror ) console.log( '- ' + cpresponse.statusCode + ': Error while getting the diff: ' + ( cpbody && cpbody.error && cpbody.error.info ) );
  3561. }
  3562. else if ( cpbody.compare.fromtexthidden === undefined && cpbody.compare.totexthidden === undefined && cpbody.compare.fromarchive === undefined && cpbody.compare.toarchive === undefined ) {
  3563. var current_tag = '';
  3564. var small_prev_ins = '';
  3565. var small_prev_del = '';
  3566. var ins_length = more.length;
  3567. var del_length = more.length;
  3568. var added = false;
  3569. var parser = new htmlparser.Parser( {
  3570. onopentag: (tagname, attribs) => {
  3571. if ( tagname === 'ins' || tagname == 'del' ) {
  3572. current_tag = tagname;
  3573. }
  3574. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3575. current_tag = tagname+'a';
  3576. }
  3577. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3578. current_tag = tagname+"d";
  3579. }
  3580. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3581. added = true;
  3582. }
  3583. },
  3584. ontext: (htmltext) => {
  3585. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3586. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3587. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3588. else small_prev_ins += more;
  3589. }
  3590. if ( current_tag === 'del' && del_length <= 1000 ) {
  3591. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3592. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3593. else small_prev_del += more;
  3594. }
  3595. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3596. ins_length += htmltext.escapeFormatting().length;
  3597. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3598. else small_prev_ins += more;
  3599. }
  3600. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3601. del_length += htmltext.escapeFormatting().length;
  3602. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3603. else small_prev_del += more;
  3604. }
  3605. if ( added ) {
  3606. if ( htmltext === '+' && ins_length <= 1000 ) {
  3607. ins_length++;
  3608. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3609. else small_prev_ins += more;
  3610. }
  3611. if ( htmltext === '−' && del_length <= 1000 ) {
  3612. del_length++;
  3613. if ( del_length <= 1000 ) small_prev_del += '\n';
  3614. else small_prev_del += more;
  3615. }
  3616. added = false;
  3617. }
  3618. },
  3619. onclosetag: (tagname) => {
  3620. if ( tagname === 'ins' ) {
  3621. current_tag = 'afterins';
  3622. } else if ( tagname === 'del' ) {
  3623. current_tag = 'afterdel';
  3624. } else {
  3625. current_tag = '';
  3626. }
  3627. }
  3628. }, {decodeEntities:true} );
  3629. parser.write( cpbody.compare['*'] );
  3630. parser.end();
  3631. if ( small_prev_del.length ) {
  3632. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3633. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  3634. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  3635. }
  3636. if ( small_prev_ins.length ) {
  3637. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3638. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  3639. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3640. }
  3641. }
  3642. else if ( cpbody.compare.fromtexthidden !== undefined ) {
  3643. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  3644. }
  3645. else if ( cpbody.compare.totexthidden !== undefined ) {
  3646. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  3647. }
  3648. }, error => {
  3649. console.log( '- Error while getting the diff: ' + error );
  3650. } ).finally( () => {
  3651. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3652. if ( reaction ) reaction.removeEmoji();
  3653. } );
  3654. else {
  3655. if ( compare ) {
  3656. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  3657. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  3658. }
  3659. else if ( revisions[0]['*'] ) {
  3660. var content = revisions[0]['*'].escapeFormatting();
  3661. if ( content.trim().length ) {
  3662. if ( content.length <= 1000 ) content = '**' + content + '**';
  3663. else {
  3664. content = content.substring(0, 1000 - more.length);
  3665. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  3666. }
  3667. embed.addField( lang.diff.info.added, content, true );
  3668. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3669. }
  3670. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3671. if ( reaction ) reaction.removeEmoji();
  3672. }
  3673. }
  3674. else {
  3675. var embed = {};
  3676. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  3677. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  3678. msg.sendChannel( spoiler + text + spoiler, {embed} );
  3679. if ( reaction ) reaction.removeEmoji();
  3680. }
  3681. }
  3682. }
  3683. else {
  3684. msg.reactEmoji('error');
  3685. if ( reaction ) reaction.removeEmoji();
  3686. }
  3687. }
  3688. }, error => {
  3689. if ( wiki.noWiki(error.message) ) {
  3690. console.log( '- This wiki doesn\'t exist!' );
  3691. msg.reactEmoji('nowiki');
  3692. }
  3693. else {
  3694. console.log( '- Error while getting the search results: ' + error );
  3695. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3696. }
  3697. if ( reaction ) reaction.removeEmoji();
  3698. } );
  3699. }
  3700. function fandom_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  3701. if ( args[0] ) {
  3702. var error = false;
  3703. var title = '';
  3704. var revision = 0;
  3705. var diff = 'prev';
  3706. if ( /^\d+$/.test(args[0]) ) {
  3707. revision = args[0];
  3708. if ( args[1] ) {
  3709. if ( /^\d+$/.test(args[1]) ) {
  3710. diff = args[1];
  3711. }
  3712. else if ( args[1] === 'prev' || args[1] === 'next' ) {
  3713. diff = args[1];
  3714. }
  3715. else error = true;
  3716. }
  3717. }
  3718. else if ( args[0] === 'prev' || args[0] === 'next' ) {
  3719. diff = args[0];
  3720. if ( args[1] ) {
  3721. if ( /^\d+$/.test(args[1]) ) {
  3722. revision = args[1];
  3723. }
  3724. else error = true;
  3725. }
  3726. else error = true;
  3727. }
  3728. else title = args.join(' ');
  3729. if ( error ) msg.reactEmoji('error');
  3730. else if ( /^\d+$/.test(diff) ) {
  3731. var argids = [];
  3732. if ( parseInt(revision, 10) > parseInt(diff, 10) ) argids = [revision, diff];
  3733. else if ( parseInt(revision, 10) === parseInt(diff, 10) ) argids = [revision];
  3734. else argids = [diff, revision];
  3735. fandom_diffsend(lang, msg, argids, wiki, reaction, spoiler);
  3736. }
  3737. else {
  3738. got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=' + ( title ? '&titles=' + encodeURIComponent( title ) : '&revids=' + revision ) + '&rvdiffto=' + diff + '&format=json', {
  3739. responseType: 'json'
  3740. } ).then( response => {
  3741. var body = response.body;
  3742. if ( body && body.warnings ) log_warn(body.warnings);
  3743. if ( response.statusCode !== 200 || !body || !body.query ) {
  3744. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3745. console.log( '- This wiki doesn\'t exist!' );
  3746. msg.reactEmoji('nowiki');
  3747. }
  3748. else {
  3749. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3750. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + diff + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  3751. }
  3752. if ( reaction ) reaction.removeEmoji();
  3753. }
  3754. else {
  3755. if ( body.query.badrevids ) {
  3756. msg.replyMsg( lang.diff.badrev );
  3757. if ( reaction ) reaction.removeEmoji();
  3758. } else if ( body.query.pages && !body.query.pages[-1] ) {
  3759. var revisions = Object.values(body.query.pages)[0].revisions[0];
  3760. if ( revisions.texthidden === undefined ) {
  3761. var argids = [];
  3762. var ids = revisions.diff;
  3763. if ( !ids.from ) argids = [ids.to];
  3764. else {
  3765. argids = [ids.to, ids.from];
  3766. var compare = ['', ''];
  3767. if ( ids['*'] !== undefined ) {
  3768. var more = '\n__' + lang.diff.info.more + '__';
  3769. var current_tag = '';
  3770. var small_prev_ins = '';
  3771. var small_prev_del = '';
  3772. var ins_length = more.length;
  3773. var del_length = more.length;
  3774. var added = false;
  3775. var parser = new htmlparser.Parser( {
  3776. onopentag: (tagname, attribs) => {
  3777. if ( tagname === 'ins' || tagname == 'del' ) {
  3778. current_tag = tagname;
  3779. }
  3780. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3781. current_tag = tagname+'a';
  3782. }
  3783. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3784. current_tag = tagname+"d";
  3785. }
  3786. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3787. added = true;
  3788. }
  3789. },
  3790. ontext: (htmltext) => {
  3791. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3792. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3793. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3794. else small_prev_ins += more;
  3795. }
  3796. if ( current_tag === 'del' && del_length <= 1000 ) {
  3797. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3798. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3799. else small_prev_del += more;
  3800. }
  3801. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3802. ins_length += htmltext.escapeFormatting().length;
  3803. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3804. else small_prev_ins += more;
  3805. }
  3806. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3807. del_length += htmltext.escapeFormatting().length;
  3808. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3809. else small_prev_del += more;
  3810. }
  3811. if ( added ) {
  3812. if ( htmltext === '+' && ins_length <= 1000 ) {
  3813. ins_length++;
  3814. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3815. else small_prev_ins += more;
  3816. }
  3817. if ( htmltext === '−' && del_length <= 1000 ) {
  3818. del_length++;
  3819. if ( del_length <= 1000 ) small_prev_del += '\n';
  3820. else small_prev_del += more;
  3821. }
  3822. added = false;
  3823. }
  3824. },
  3825. onclosetag: (tagname) => {
  3826. if ( tagname === 'ins' ) {
  3827. current_tag = 'afterins';
  3828. } else if ( tagname === 'del' ) {
  3829. current_tag = 'afterdel';
  3830. } else {
  3831. current_tag = '';
  3832. }
  3833. }
  3834. }, {decodeEntities:true} );
  3835. parser.write( ids['*'] );
  3836. parser.end();
  3837. if ( small_prev_del.length ) {
  3838. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3839. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  3840. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  3841. }
  3842. if ( small_prev_ins.length ) {
  3843. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3844. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  3845. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  3846. }
  3847. }
  3848. }
  3849. fandom_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  3850. } else {
  3851. msg.replyMsg( lang.diff.badrev );
  3852. if ( reaction ) reaction.removeEmoji();
  3853. }
  3854. } else {
  3855. if ( body.query.pages && body.query.pages[-1] ) msg.replyMsg( lang.diff.badrev );
  3856. else msg.reactEmoji('error');
  3857. if ( reaction ) reaction.removeEmoji();
  3858. }
  3859. }
  3860. }, error => {
  3861. if ( wiki.noWiki(error.message) ) {
  3862. console.log( '- This wiki doesn\'t exist!' );
  3863. msg.reactEmoji('nowiki');
  3864. }
  3865. else {
  3866. console.log( '- Error while getting the search results: ' + error );
  3867. msg.sendChannelError( spoiler + '<' + wiki.toLink(title, 'diff=' + diff + ( title ? '' : '&oldid=' + revision )) + '>' + spoiler );
  3868. }
  3869. if ( reaction ) reaction.removeEmoji();
  3870. } );
  3871. }
  3872. }
  3873. else {
  3874. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, {embed} );
  3875. else msg.reactEmoji('error');
  3876. if ( reaction ) reaction.removeEmoji();
  3877. }
  3878. }
  3879. function fandom_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  3880. 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', {
  3881. responseType: 'json'
  3882. } ).then( response => {
  3883. var body = response.body;
  3884. if ( body && body.warnings ) log_warn(body.warnings);
  3885. if ( response.statusCode !== 200 || !body || !body.query ) {
  3886. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  3887. console.log( '- This wiki doesn\'t exist!' );
  3888. msg.reactEmoji('nowiki');
  3889. }
  3890. else {
  3891. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  3892. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  3893. }
  3894. if ( reaction ) reaction.removeEmoji();
  3895. }
  3896. else {
  3897. if ( body.query.badrevids ) {
  3898. msg.replyMsg( lang.diff.badrev );
  3899. if ( reaction ) reaction.removeEmoji();
  3900. }
  3901. else if ( body.query.pages && !body.query.pages['-1'] ) {
  3902. var pages = Object.values(body.query.pages);
  3903. if ( pages.length !== 1 ) {
  3904. msg.sendChannel( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0], '', '', body.query.general) + '>' + spoiler );
  3905. if ( reaction ) reaction.removeEmoji();
  3906. }
  3907. else {
  3908. var title = pages[0].title;
  3909. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  3910. var diff = revisions[0].revid;
  3911. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  3912. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  3913. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  3914. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  3915. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  3916. 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 ) )];
  3917. 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(', ')];
  3918. var pagelink = wiki.toLink(title, 'diff=' + diff + '&oldid=' + oldid, '', body.query.general);
  3919. if ( msg.showEmbed() ) {
  3920. var text = '<' + pagelink + '>';
  3921. var editorlink = '[' + editor[1] + '](' + wiki.toLink('User:' + editor[1], '', '', body.query.general, true) + ')';
  3922. if ( revisions[0].anon !== undefined ) {
  3923. editorlink = '[' + editor[1] + '](' + wiki.toLink('Special:Contributions/' + editor[1], '', '', body.query.general, true) + ')';
  3924. }
  3925. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  3926. 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] );
  3927. if ( tags ) {
  3928. var taglink = '';
  3929. var tagtext = '';
  3930. var tagparser = new htmlparser.Parser( {
  3931. onopentag: (tagname, attribs) => {
  3932. if ( tagname === 'a' ) taglink = attribs.href;
  3933. },
  3934. ontext: (htmltext) => {
  3935. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  3936. else tagtext += htmltext.escapeFormatting();
  3937. },
  3938. onclosetag: (tagname) => {
  3939. if ( tagname === 'a' ) taglink = '';
  3940. }
  3941. }, {decodeEntities:true} );
  3942. tagparser.write( tags[1] );
  3943. tagparser.end();
  3944. embed.addField( tags[0], tagtext );
  3945. }
  3946. var more = '\n__' + lang.diff.info.more + '__';
  3947. if ( !compare && oldid ) got.get( wiki + 'api.php?action=query&prop=revisions&rvprop=&revids=' + oldid + '&rvdiffto=' + diff + '&format=json', {
  3948. responseType: 'json'
  3949. } ).then( cpresponse => {
  3950. var cpbody = cpresponse.body;
  3951. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  3952. if ( cpresponse.statusCode !== 200 || !cpbody || !cpbody.query || cpbody.query.badrevids || !cpbody.query.pages && cpbody.query.pages[-1] ) {
  3953. console.log( '- ' + cpresponse.statusCode + ': Error while getting the diff: ' + ( cpbody && cpbody.error && cpbody.error.info ) );
  3954. }
  3955. else {
  3956. var revision = Object.values(cpbody.query.pages)[0].revisions[0];
  3957. if ( revision.texthidden === undefined && revision.diff && revision.diff['*'] !== undefined ) {
  3958. var current_tag = '';
  3959. var small_prev_ins = '';
  3960. var small_prev_del = '';
  3961. var ins_length = more.length;
  3962. var del_length = more.length;
  3963. var added = false;
  3964. var parser = new htmlparser.Parser( {
  3965. onopentag: (tagname, attribs) => {
  3966. if ( tagname === 'ins' || tagname == 'del' ) {
  3967. current_tag = tagname;
  3968. }
  3969. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3970. current_tag = tagname+'a';
  3971. }
  3972. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3973. current_tag = tagname+"d";
  3974. }
  3975. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3976. added = true;
  3977. }
  3978. },
  3979. ontext: (htmltext) => {
  3980. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3981. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3982. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3983. else small_prev_ins += more;
  3984. }
  3985. if ( current_tag === 'del' && del_length <= 1000 ) {
  3986. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3987. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3988. else small_prev_del += more;
  3989. }
  3990. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3991. ins_length += htmltext.escapeFormatting().length;
  3992. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3993. else small_prev_ins += more;
  3994. }
  3995. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3996. del_length += htmltext.escapeFormatting().length;
  3997. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3998. else small_prev_del += more;
  3999. }
  4000. if ( added ) {
  4001. if ( htmltext === '+' && ins_length <= 1000 ) {
  4002. ins_length++;
  4003. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  4004. else small_prev_ins += more;
  4005. }
  4006. if ( htmltext === '−' && del_length <= 1000 ) {
  4007. del_length++;
  4008. if ( del_length <= 1000 ) small_prev_del += '\n';
  4009. else small_prev_del += more;
  4010. }
  4011. added = false;
  4012. }
  4013. },
  4014. onclosetag: (tagname) => {
  4015. if ( tagname === 'ins' ) {
  4016. current_tag = 'afterins';
  4017. } else if ( tagname === 'del' ) {
  4018. current_tag = 'afterdel';
  4019. } else {
  4020. current_tag = '';
  4021. }
  4022. }
  4023. }, {decodeEntities:true} );
  4024. parser.write( revision.diff['*'] );
  4025. parser.end();
  4026. if ( small_prev_del.length ) {
  4027. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  4028. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  4029. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  4030. }
  4031. if ( small_prev_ins.length ) {
  4032. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  4033. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  4034. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  4035. }
  4036. }
  4037. else if ( revision.texthidden !== undefined ) {
  4038. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  4039. }
  4040. else if ( revision.diff && revision.diff['*'] === undefined ) {
  4041. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  4042. }
  4043. }
  4044. }, error => {
  4045. console.log( '- Error while getting the diff: ' + error );
  4046. } ).finally( () => {
  4047. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4048. if ( reaction ) reaction.removeEmoji();
  4049. } );
  4050. else {
  4051. if ( compare ) {
  4052. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  4053. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  4054. }
  4055. else if ( revisions[0]['*'] ) {
  4056. var content = revisions[0]['*'].escapeFormatting();
  4057. if ( content.trim().length ) {
  4058. if ( content.length <= 1000 ) content = '**' + content + '**';
  4059. else {
  4060. content = content.substring(0, 1000 - more.length);
  4061. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  4062. }
  4063. embed.addField( lang.diff.info.added, content, true );
  4064. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  4065. }
  4066. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4067. if ( reaction ) reaction.removeEmoji();
  4068. }
  4069. }
  4070. else {
  4071. var embed = {};
  4072. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  4073. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  4074. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4075. if ( reaction ) reaction.removeEmoji();
  4076. }
  4077. }
  4078. }
  4079. else {
  4080. msg.reactEmoji('error');
  4081. if ( reaction ) reaction.removeEmoji();
  4082. }
  4083. }
  4084. }, error => {
  4085. if ( wiki.noWiki(error.message) ) {
  4086. console.log( '- This wiki doesn\'t exist!' );
  4087. msg.reactEmoji('nowiki');
  4088. }
  4089. else {
  4090. console.log( '- Error while getting the search results: ' + error );
  4091. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0]) + '>' + spoiler );
  4092. }
  4093. if ( reaction ) reaction.removeEmoji();
  4094. } );
  4095. }
  4096. function gamepedia_random(lang, msg, wiki, reaction, spoiler) {
  4097. 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', {
  4098. responseType: 'json'
  4099. } ).then( response => {
  4100. var body = response.body;
  4101. if ( body && body.warnings ) log_warn(body.warnings);
  4102. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  4103. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4104. console.log( '- This wiki doesn\'t exist!' );
  4105. msg.reactEmoji('nowiki');
  4106. }
  4107. else {
  4108. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  4109. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  4110. }
  4111. }
  4112. else {
  4113. var querypage = Object.values(body.query.pages)[0];
  4114. var pagelink = wiki.toLink(querypage.title, '', '', body.query.general);
  4115. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  4116. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  4117. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  4118. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  4119. embed.setTitle( displaytitle );
  4120. }
  4121. if ( querypage.pageprops && querypage.pageprops.description ) {
  4122. var description = htmlToPlain( querypage.pageprops.description );
  4123. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  4124. embed.setDescription( description );
  4125. }
  4126. else if ( querypage.extract ) {
  4127. var extract = querypage.extract.escapeFormatting();
  4128. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  4129. embed.setDescription( extract );
  4130. }
  4131. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  4132. embed.setThumbnail( querypage.original.source );
  4133. }
  4134. else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  4135. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  4136. }
  4137. }, error => {
  4138. if ( wiki.noWiki(error.message) ) {
  4139. console.log( '- This wiki doesn\'t exist!' );
  4140. msg.reactEmoji('nowiki');
  4141. }
  4142. else {
  4143. console.log( '- Error while getting the search results: ' + error );
  4144. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  4145. }
  4146. } ).finally( () => {
  4147. if ( reaction ) reaction.removeEmoji();
  4148. } );
  4149. }
  4150. function fandom_random(lang, msg, wiki, reaction, spoiler) {
  4151. got.get( wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=description&siprop=general&generator=random&grnnamespace=0&format=json', {
  4152. responseType: 'json'
  4153. } ).then( response => {
  4154. var body = response.body;
  4155. if ( body && body.warnings ) log_warn(body.warnings);
  4156. if ( response.statusCode !== 200 || !body || !body.query || !body.query.pages ) {
  4157. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4158. console.log( '- This wiki doesn\'t exist!' );
  4159. msg.reactEmoji('nowiki');
  4160. }
  4161. else {
  4162. console.log( '- ' + response.statusCode + ': Error while getting the search results: ' + ( body && body.error && body.error.info ) );
  4163. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  4164. }
  4165. if ( reaction ) reaction.removeEmoji();
  4166. }
  4167. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  4168. return gamepedia_random(lang, msg, wiki, reaction, spoiler);
  4169. }
  4170. else {
  4171. var querypage = Object.values(body.query.pages)[0];
  4172. var pagelink = wiki.toLink(querypage.title, '', '', body.query.general);
  4173. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  4174. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  4175. embed.setDescription( body.query.allmessages[0]['*'] );
  4176. embed.setThumbnail( wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general) );
  4177. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  4178. if ( reaction ) reaction.removeEmoji();
  4179. }
  4180. else got.get( wiki.toDescLink(querypage.title) ).then( descresponse => {
  4181. var descbody = descresponse.body;
  4182. if ( descresponse.statusCode !== 200 || !descbody ) {
  4183. console.log( '- ' + descresponse.statusCode + ': Error while getting the description.' );
  4184. } else {
  4185. var thumbnail = wiki.toLink('Special:FilePath/Wiki-wordmark.png', '', '', body.query.general);
  4186. var parser = new htmlparser.Parser( {
  4187. onopentag: (tagname, attribs) => {
  4188. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  4189. var description = attribs.content.escapeFormatting();
  4190. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  4191. embed.setDescription( description );
  4192. }
  4193. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  4194. thumbnail = attribs.content;
  4195. }
  4196. }
  4197. }, {decodeEntities:true} );
  4198. parser.write( descbody );
  4199. parser.end();
  4200. embed.setThumbnail( thumbnail );
  4201. }
  4202. }, error => {
  4203. console.log( '- Error while getting the description: ' + error );
  4204. } ).finally( () => {
  4205. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, {embed} );
  4206. if ( reaction ) reaction.removeEmoji();
  4207. } );
  4208. }
  4209. }, error => {
  4210. if ( wiki.noWiki(error.message) ) {
  4211. console.log( '- This wiki doesn\'t exist!' );
  4212. msg.reactEmoji('nowiki');
  4213. }
  4214. else {
  4215. console.log( '- Error while getting the search results: ' + error );
  4216. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Random') + '>' + spoiler );
  4217. }
  4218. if ( reaction ) reaction.removeEmoji();
  4219. } );
  4220. }
  4221. function gamepedia_overview(lang, msg, wiki, reaction, spoiler) {
  4222. 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', {
  4223. responseType: 'json'
  4224. } ).then( response => {
  4225. var body = response.body;
  4226. if ( body && body.warnings ) log_warn(body.warnings);
  4227. if ( response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  4228. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4229. console.log( '- This wiki doesn\'t exist!' );
  4230. msg.reactEmoji('nowiki');
  4231. }
  4232. else {
  4233. console.log( '- ' + response.statusCode + ': Error while getting the statistics: ' + ( body && body.error && body.error.info ) );
  4234. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4235. }
  4236. if ( reaction ) reaction.removeEmoji();
  4237. }
  4238. else {
  4239. var site = false;
  4240. if ( allSites.some( site => site.wiki_domain === body.query.general.servername ) ) {
  4241. site = allSites.find( site => site.wiki_domain === body.query.general.servername );
  4242. var name = [lang.overview.name, site.wiki_display_name];
  4243. var created = [lang.overview.created, new Date(parseInt(site.created + '000', 10)).toLocaleString(lang.dateformat, timeoptions)];
  4244. var manager = [lang.overview.manager, site.wiki_managers];
  4245. var official = [lang.overview.official, ( site.official_wiki ? lang.overview.yes : lang.overview.no )];
  4246. var crossover = [lang.overview.crossover, ( site.wiki_crossover ? '<https://' + site.wiki_crossover + '/>' : '' )];
  4247. var description = [lang.overview.description, site.wiki_description];
  4248. var image = [lang.overview.image, site.wiki_image];
  4249. if ( description[1] ) {
  4250. description[1] = description[1].escapeFormatting();
  4251. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  4252. }
  4253. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  4254. }
  4255. var articles = [lang.overview.articles, body.query.statistics.articles];
  4256. var pages = [lang.overview.pages, body.query.statistics.pages];
  4257. var edits = [lang.overview.edits, body.query.statistics.edits];
  4258. var users = [lang.overview.users, body.query.statistics.activeusers];
  4259. var title = body.query.pages['-1'].title;
  4260. var pagelink = wiki.toLink(title, '', '', body.query.general);
  4261. if ( msg.showEmbed() ) {
  4262. var text = '<' + pagelink + '>';
  4263. 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 );
  4264. }
  4265. else {
  4266. var embed = {};
  4267. var text = '<' + pagelink + '>\n\n';
  4268. }
  4269. 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', {
  4270. responseType: 'json'
  4271. } ).then( ovresponse => {
  4272. var ovbody = ovresponse.body;
  4273. if ( ovresponse.statusCode !== 200 || !ovbody || ovbody.exception || !ovbody.items || !ovbody.items.length ) {
  4274. console.log( '- ' + ovresponse.statusCode + ': Error while getting the wiki details: ' + ( ovbody && ovbody.exception && ovbody.exception.details ) );
  4275. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4276. if ( reaction ) reaction.removeEmoji();
  4277. }
  4278. else if ( ovbody.items.some( site => site.url === body.query.general.server + ( body.query.general.scriptpath ? body.query.general.scriptpath + '/' : '' ) ) ) {
  4279. site = ovbody.items.find( site => site.url === body.query.general.server + ( body.query.general.scriptpath ? body.query.general.scriptpath + '/' : '' ) );
  4280. var vertical = [lang.overview.vertical, site.hub];
  4281. var topic = [lang.overview.topic, site.topic];
  4282. var founder = [lang.overview.founder, site.founding_user_id];
  4283. var manager = [lang.overview.manager, body.query.allmessages[0]['*']];
  4284. var crossover = [lang.overview.crossover, ( body.query.allmessages[1]['*'] ? '<https://' + body.query.allmessages[1]['*'] + '.gamepedia.com/>' : '' )];
  4285. var created = [lang.overview.created, new Date(site.creation_date).toLocaleString(lang.dateformat, timeoptions)];
  4286. var description = [lang.overview.description, site.desc];
  4287. var image = [lang.overview.image, site.image];
  4288. if ( description[1] ) {
  4289. description[1] = description[1].escapeFormatting();
  4290. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  4291. }
  4292. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  4293. if ( msg.showEmbed() ) {
  4294. embed.addField( vertical[0], vertical[1], true );
  4295. if ( topic[1] ) embed.addField( topic[0], topic[1], true );
  4296. }
  4297. else text += vertical.join(' ') + ( topic[1] ? '\n' + topic.join(' ') : '' );
  4298. if ( founder[1] > 0 ) got.get( wiki + 'api.php?action=query&list=users&usprop=&ususerids=' + founder[1] + '&format=json', {
  4299. responseType: 'json'
  4300. } ).then( usresponse => {
  4301. var usbody = usresponse.body;
  4302. if ( usbody && usbody.warnings ) log_warn(usbody.warnings);
  4303. if ( usresponse.statusCode !== 200 || !usbody || !usbody.query || !usbody.query.users || !usbody.query.users[0] ) {
  4304. console.log( '- ' + usresponse.statusCode + ': Error while getting the wiki founder: ' + ( usbody && usbody.error && usbody.error.info ) );
  4305. founder[1] = 'ID: ' + founder[1];
  4306. }
  4307. else {
  4308. var user = usbody.query.users[0].name;
  4309. if ( msg.showEmbed() ) founder[1] = '[' + user + '](' + wiki.toLink('User:' + user, '', '', body.query.general, true) + ')';
  4310. else founder[1] = user;
  4311. }
  4312. }, error => {
  4313. console.log( '- Error while getting the wiki founder: ' + error );
  4314. founder[1] = 'ID: ' + founder[1];
  4315. } ).finally( () => {
  4316. if ( msg.showEmbed() ) {
  4317. embed.addField( founder[0], founder[1], true );
  4318. 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 );
  4319. 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 );
  4320. if ( crossover[1] ) {
  4321. var crossoverSite = allSites.find( site => '<https://' + site.wiki_domain + '/>' === crossover[1] );
  4322. if ( crossoverSite ) embed.addField( crossover[0], '[' + crossoverSite.wiki_display_name + '](' + crossover[1] + ')', true );
  4323. else embed.addField( crossover[0], crossover[1], true );
  4324. }
  4325. if ( description[1] ) embed.addField( description[0], description[1] );
  4326. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4327. }
  4328. else {
  4329. text += '\n' + founder.join(' ') + ( manager[1] ? '\n' + manager.join(' ') : '' ) + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4330. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4331. if ( description[1] ) text += '\n' + description.join(' ');
  4332. if ( image[1] ) {
  4333. text += '\n' + image.join(' ');
  4334. if ( msg.uploadFiles() ) embed.files = [image[1]];
  4335. }
  4336. text += '\n\n*' + lang.overview.inaccurate + '*';
  4337. }
  4338. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4339. if ( reaction ) reaction.removeEmoji();
  4340. } );
  4341. else {
  4342. founder[1] = lang.overview.none;
  4343. if ( msg.showEmbed() ) {
  4344. 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 );
  4345. if ( crossover[1] ) {
  4346. var crossoverSite = allSites.find( site => '<https://' + site.wiki_domain + '/>' === crossover[1] );
  4347. if ( crossoverSite ) embed.addField( crossover[0], '[' + crossoverSite.wiki_display_name + '](' + crossover[1] + ')', true );
  4348. else embed.addField( crossover[0], crossover[1], true );
  4349. }
  4350. if ( description[1] ) embed.addField( description[0], description[1] );
  4351. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4352. }
  4353. else {
  4354. text += '\n' + founder.join(' ') + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4355. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4356. if ( description[1] ) text += '\n' + description.join(' ');
  4357. if ( image[1] ) {
  4358. text += '\n' + image.join(' ');
  4359. if ( msg.uploadFiles() ) embed.files = [image[1]];
  4360. }
  4361. text += '\n\n*' + lang.overview.inaccurate + '*';
  4362. }
  4363. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4364. if ( reaction ) reaction.removeEmoji();
  4365. }
  4366. }
  4367. else {
  4368. 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 );
  4369. else text = articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ') + '\n\n*' + lang.overview.inaccurate + '*';
  4370. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4371. if ( reaction ) reaction.removeEmoji();
  4372. }
  4373. }, error => {
  4374. console.log( '- Error while getting the wiki details: ' + error );
  4375. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4376. if ( reaction ) reaction.removeEmoji();
  4377. } );
  4378. else {
  4379. if ( msg.showEmbed() ) {
  4380. if ( site ) {
  4381. 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');
  4382. 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 );
  4383. }
  4384. 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 );
  4385. if ( site ) {
  4386. if ( crossover[1] ) embed.addField( crossover[0], crossover[1], true );
  4387. if ( description[1] ) embed.addField( description[0], description[1] );
  4388. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4389. }
  4390. }
  4391. else {
  4392. if ( site ) text += name.join(' ') + '\n' + created.join(' ') + '\n' + manager[0] + ' ' + ( manager[1].join(', ') || lang.overview.none ) + '\n' + official.join(' ') + '\n';
  4393. text += articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4394. if ( site ) {
  4395. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4396. if ( description[1] ) text += '\n' + description.join(' ');
  4397. if ( image[1] ) {
  4398. text += '\n' + image.join(' ');
  4399. if ( msg.uploadFiles() ) embed.files = [{attachment:image[1],name:( spoiler ? 'SPOILER ' : '' ) + name[1] + image[1].substring(image[1].lastIndexOf('.'))}];
  4400. }
  4401. }
  4402. text += '\n\n*' + lang.overview.inaccurate + '*';
  4403. }
  4404. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4405. if ( reaction ) reaction.removeEmoji();
  4406. }
  4407. }
  4408. }, error => {
  4409. if ( wiki.noWiki(error.message) ) {
  4410. console.log( '- This wiki doesn\'t exist!' );
  4411. msg.reactEmoji('nowiki');
  4412. }
  4413. else {
  4414. console.log( '- Error while getting the statistics: ' + error );
  4415. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4416. }
  4417. if ( reaction ) reaction.removeEmoji();
  4418. } );
  4419. }
  4420. function fandom_overview(lang, msg, wiki, reaction, spoiler) {
  4421. 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', {
  4422. responseType: 'json'
  4423. } ).then( response => {
  4424. var body = response.body;
  4425. if ( body && body.warnings ) log_warn(body.warnings);
  4426. if ( response.statusCode !== 200 || !body || !body.query || !body.query.pages ) {
  4427. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  4428. console.log( '- This wiki doesn\'t exist!' );
  4429. msg.reactEmoji('nowiki');
  4430. }
  4431. else {
  4432. console.log( '- ' + response.statusCode + ': Error while getting the statistics: ' + ( body && body.error && body.error.info ) );
  4433. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4434. }
  4435. if ( reaction ) reaction.removeEmoji();
  4436. }
  4437. else if ( body.query.general.generator.startsWith( 'MediaWiki 1.3' ) ) {
  4438. return gamepedia_overview(lang, msg, wiki, reaction, spoiler);
  4439. }
  4440. else got.get( 'https://community.fandom.com/api/v1/Wikis/Details?ids=' + body.query.wikidesc.id + '&format=json', {
  4441. responseType: 'json'
  4442. } ).then( ovresponse => {
  4443. var ovbody = ovresponse.body;
  4444. if ( ovresponse.statusCode !== 200 || !ovbody || ovbody.exception || !ovbody.items || !ovbody.items[body.query.wikidesc.id] ) {
  4445. console.log( '- ' + ovresponse.statusCode + ': Error while getting the wiki details: ' + ( ovbody && ovbody.exception && ovbody.exception.details ) );
  4446. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4447. if ( reaction ) reaction.removeEmoji();
  4448. }
  4449. else {
  4450. var site = ovbody.items[body.query.wikidesc.id];
  4451. var vertical = [lang.overview.vertical, site.hub];
  4452. var topic = [lang.overview.topic, site.topic];
  4453. var founder = [lang.overview.founder, site.founding_user_id];
  4454. var manager = [lang.overview.manager, body.query.allmessages[0]['*']];
  4455. var crossover = [lang.overview.crossover, ( body.query.allmessages[1]['*'] ? '<https://' + body.query.allmessages[1]['*'] + '.gamepedia.com/>' : '' )];
  4456. var created = [lang.overview.created, new Date(site.creation_date).toLocaleString(lang.dateformat, timeoptions)];
  4457. var articles = [lang.overview.articles, body.query.statistics.articles];
  4458. var pages = [lang.overview.pages, body.query.statistics.pages];
  4459. var edits = [lang.overview.edits, body.query.statistics.edits];
  4460. var users = [lang.overview.users, body.query.statistics.activeusers];
  4461. var description = [lang.overview.description, site.desc];
  4462. var image = [lang.overview.image, site.image];
  4463. if ( description[1] ) {
  4464. description[1] = description[1].escapeFormatting();
  4465. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  4466. }
  4467. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  4468. var title = body.query.pages['-1'].title;
  4469. var pagelink = wiki.toLink(title, '', '', body.query.general);
  4470. if ( msg.showEmbed() ) {
  4471. var text = '<' + pagelink + '>';
  4472. var embed = new Discord.MessageEmbed().setAuthor( body.query.general.sitename ).setTitle( title.escapeFormatting() ).setURL( pagelink ).setThumbnail( site.wordmark ).addField( vertical[0], vertical[1], true );
  4473. if ( topic[1] ) embed.addField( topic[0], topic[1], true );
  4474. }
  4475. else {
  4476. var embed = {};
  4477. var text = '<' + pagelink + '>\n\n' + vertical.join(' ') + ( topic[1] ? '\n' + topic.join(' ') : '' );
  4478. }
  4479. if ( founder[1] > 0 ) got.get( wiki + 'api.php?action=query&list=users&usprop=&usids=' + founder[1] + '&format=json', {
  4480. responseType: 'json'
  4481. } ).then( usresponse => {
  4482. var usbody = usresponse.body;
  4483. if ( usbody && usbody.warnings ) log_warn(usbody.warnings);
  4484. if ( usresponse.statusCode !== 200 || !usbody || !usbody.query || !usbody.query.users || !usbody.query.users[0] ) {
  4485. console.log( '- ' + usresponse.statusCode + ': Error while getting the wiki founder: ' + ( usbody && usbody.error && usbody.error.info ) );
  4486. founder[1] = 'ID: ' + founder[1];
  4487. }
  4488. else {
  4489. var user = usbody.query.users[0].name;
  4490. if ( msg.showEmbed() ) founder[1] = '[' + user + '](' + wiki.toLink('User:' + user, '', '', body.query.general, true) + ')';
  4491. else founder[1] = user;
  4492. }
  4493. }, error => {
  4494. console.log( '- Error while getting the wiki founder: ' + error );
  4495. founder[1] = 'ID: ' + founder[1];
  4496. } ).finally( () => {
  4497. if ( msg.showEmbed() ) {
  4498. embed.addField( founder[0], founder[1], true );
  4499. 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 );
  4500. 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 );
  4501. if ( crossover[1] ) {
  4502. var crossoverSite = allSites.find( site => '<https://' + site.wiki_domain + '/>' === crossover[1] );
  4503. if ( crossoverSite ) embed.addField( crossover[0], '[' + crossoverSite.wiki_display_name + '](' + crossover[1] + ')', true );
  4504. else embed.addField( crossover[0], crossover[1], true );
  4505. }
  4506. if ( description[1] ) embed.addField( description[0], description[1] );
  4507. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4508. }
  4509. else {
  4510. text += '\n' + founder.join(' ') + ( manager[1] ? '\n' + manager.join(' ') : '' ) + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4511. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4512. if ( description[1] ) text += '\n' + description.join(' ');
  4513. if ( image[1] ) {
  4514. text += '\n' + image.join(' ');
  4515. if ( msg.uploadFiles() ) embed.files = [image[1]];
  4516. }
  4517. text += '\n\n*' + lang.overview.inaccurate + '*';
  4518. }
  4519. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4520. if ( reaction ) reaction.removeEmoji();
  4521. } );
  4522. else {
  4523. founder[1] = lang.overview.none;
  4524. if ( msg.showEmbed() ) {
  4525. 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 );
  4526. if ( crossover[1] ) {
  4527. var crossoverSite = allSites.find( site => '<https://' + site.wiki_domain + '/>' === crossover[1] );
  4528. if ( crossoverSite ) embed.addField( crossover[0], '[' + crossoverSite.wiki_display_name + '](' + crossover[1] + ')', true );
  4529. else embed.addField( crossover[0], crossover[1], true );
  4530. }
  4531. if ( description[1] ) embed.addField( description[0], description[1] );
  4532. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  4533. }
  4534. else {
  4535. text += '\n' + founder.join(' ') + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  4536. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  4537. if ( description[1] ) text += '\n' + description.join(' ');
  4538. if ( image[1] ) {
  4539. text += '\n' + image.join(' ');
  4540. if ( msg.uploadFiles() ) embed.files = [image[1]];
  4541. }
  4542. text += '\n\n*' + lang.overview.inaccurate + '*';
  4543. }
  4544. msg.sendChannel( spoiler + text + spoiler, {embed} );
  4545. if ( reaction ) reaction.removeEmoji();
  4546. }
  4547. }
  4548. }, error => {
  4549. console.log( '- Error while getting the wiki details: ' + error );
  4550. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics', '', '', body.query.general) + '>' + spoiler );
  4551. if ( reaction ) reaction.removeEmoji();
  4552. } );
  4553. }, error => {
  4554. if ( wiki.noWiki(error.message) ) {
  4555. console.log( '- This wiki doesn\'t exist!' );
  4556. msg.reactEmoji('nowiki');
  4557. }
  4558. else {
  4559. console.log( '- Error while getting the statistics: ' + error );
  4560. msg.sendChannelError( spoiler + '<' + wiki.toLink('Special:Statistics') + '>' + spoiler );
  4561. }
  4562. if ( reaction ) reaction.removeEmoji();
  4563. } );
  4564. }
  4565. function minecraft_bug(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4566. var invoke = args[0];
  4567. args = args.slice(1);
  4568. if ( invoke && /\d+$/.test(invoke) && !args.length ) {
  4569. if ( /^\d+$/.test(invoke) ) invoke = 'MC-' + invoke;
  4570. var link = 'https://bugs.mojang.com/browse/';
  4571. got.get( 'https://bugs.mojang.com/rest/api/2/issue/' + encodeURIComponent( invoke ) + '?fields=summary,issuelinks,fixVersions,resolution,status', {
  4572. responseType: 'json'
  4573. } ).then( response => {
  4574. var body = response.body;
  4575. if ( response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  4576. if ( body && body.errorMessages ) {
  4577. if ( body.errorMessages.includes( 'Issue Does Not Exist' ) ) {
  4578. msg.reactEmoji('🤷');
  4579. }
  4580. else if ( body.errorMessages.includes( 'You do not have the permission to see the specified issue.' ) ) {
  4581. msg.sendChannel( spoiler + mclang.bug.private + '\n<' + link + invoke + '>' + spoiler );
  4582. }
  4583. else {
  4584. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + body.errorMessages.join(' - ') );
  4585. msg.reactEmoji('error');
  4586. }
  4587. }
  4588. else {
  4589. console.log( '- ' + response.statusCode + ': Error while getting the issue: ' + ( body && body.message ) );
  4590. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  4591. else msg.sendChannelError( spoiler + '<' + link + invoke + '>' + spoiler );
  4592. }
  4593. }
  4594. else {
  4595. if ( !body.fields ) {
  4596. msg.reactEmoji('error');
  4597. }
  4598. else {
  4599. var bugs = body.fields.issuelinks.filter( bug => bug.outwardIssue || ( bug.inwardIssue && bug.type.name != 'Duplicate' ) );
  4600. if ( bugs.length ) {
  4601. var embed = new Discord.MessageEmbed();
  4602. var extrabugs = [];
  4603. bugs.forEach( bug => {
  4604. var ward = ( bug.outwardIssue ? 'outward' : 'inward' );
  4605. var issue = bug[ward + 'Issue'];
  4606. var name = bug.type[ward] + ' ' + issue.key;
  4607. var value = issue.fields.status.name + ': [' + issue.fields.summary.escapeFormatting() + '](' + link + issue.key + ')';
  4608. if ( embed.fields.length < 25 ) embed.addField( name, value );
  4609. else extrabugs.push({name,value,inline:false});
  4610. } );
  4611. if ( extrabugs.length ) embed.setFooter( mclang.bug.more.replaceSave( '%s', extrabugs.length ) );
  4612. }
  4613. var status = '**' + ( body.fields.resolution ? body.fields.resolution.name : body.fields.status.name ) + ':** ';
  4614. var fixed = '';
  4615. if ( body.fields.resolution && body.fields.fixVersions && body.fields.fixVersions.length ) {
  4616. fixed = '\n' + mclang.bug.fixed + ' ' + body.fields.fixVersions.map( v => v.name ).join(', ');
  4617. }
  4618. msg.sendChannel( spoiler + status + body.fields.summary.escapeFormatting() + '\n<' + link + body.key + '>' + fixed + spoiler, {embed} );
  4619. }
  4620. }
  4621. }, error => {
  4622. console.log( '- Error while getting the issue: ' + error );
  4623. msg.sendChannelError( spoiler + '<' + link + invoke + '>' + spoiler );
  4624. } ).finally( () => {
  4625. if ( reaction ) reaction.removeEmoji();
  4626. } );
  4627. }
  4628. else if ( invoke && invoke.toLowerCase() === 'version' && args.length && args.join(' ').length < 100 ) {
  4629. var jql = 'fixVersion="' + args.join(' ').replace( /(["\\])/g, '\\$1' ).toSearch() + '"+order+by+key';
  4630. var link = 'https://bugs.mojang.com/issues/?jql=' + jql;
  4631. got.get( 'https://bugs.mojang.com/rest/api/2/search?fields=summary,resolution,status&jql=' + jql + '&maxResults=25', {
  4632. responseType: 'json'
  4633. } ).then( response => {
  4634. var body = response.body;
  4635. if ( response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  4636. if ( body && body.errorMessages ) {
  4637. if ( body.errorMessages.includes( 'The value \'' + args.join(' ') + '\' does not exist for the field \'fixVersion\'.' ) ) {
  4638. msg.reactEmoji('🤷');
  4639. }
  4640. else {
  4641. console.log( '- ' + response.statusCode + ': Error while getting the issues: ' + body.errorMessages.join(' - ') );
  4642. msg.reactEmoji('error');
  4643. }
  4644. }
  4645. else {
  4646. console.log( '- ' + response.statusCode + ': Error while getting the issues: ' + ( body && body.message ) );
  4647. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  4648. else msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  4649. }
  4650. }
  4651. else {
  4652. if ( !body.issues ) {
  4653. msg.reactEmoji('error');
  4654. }
  4655. else {
  4656. if ( body.total > 0 ) {
  4657. var embed = new Discord.MessageEmbed();
  4658. body.issues.forEach( bug => {
  4659. var status = ( bug.fields.resolution ? bug.fields.resolution.name : bug.fields.status.name );
  4660. var value = status + ': [' + bug.fields.summary.escapeFormatting() + '](https://bugs.mojang.com/browse/' + bug.key + ')';
  4661. embed.addField( bug.key, value );
  4662. } );
  4663. if ( body.total > 25 ) embed.setFooter( mclang.bug.more.replaceSave( '%s', body.total - 25 ) );
  4664. }
  4665. var total = '**' + args.join(' ') + ':** ' + mclang.bug.total.replaceSave( '%s', body.total );
  4666. msg.sendChannel( spoiler + total + '\n<' + link + '>' + spoiler, {embed} );
  4667. }
  4668. }
  4669. }, error => {
  4670. console.log( '- Error while getting the issues: ' + error );
  4671. msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  4672. } ).finally( () => {
  4673. if ( reaction ) reaction.removeEmoji();
  4674. } );
  4675. }
  4676. else {
  4677. msg.notminecraft = true;
  4678. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4679. }
  4680. }
  4681. function minecraft_command(lang, mclang, msg, befehl, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4682. befehl = befehl.toLowerCase();
  4683. var aliasCmd = ( minecraft.cmd.aliase[befehl] || befehl );
  4684. if ( aliasCmd in minecraft.cmd.list ) {
  4685. var cmdSyntaxMap = minecraft.cmd.list[aliasCmd].map( command => {
  4686. var cmdargs = command.split(' ');
  4687. if ( cmdargs[0].startsWith( '/' ) ) cmdargs = cmdargs.slice(1);
  4688. var argmatches = cmdargs.map( (arg, i) => {
  4689. if ( arg === args[i] ) return true;
  4690. } );
  4691. var matchCount = 0;
  4692. argmatches.forEach( match => {
  4693. if ( match ) matchCount++;
  4694. } );
  4695. return [argmatches.lastIndexOf(true),matchCount];
  4696. } );
  4697. var lastIndex = Math.max(...cmdSyntaxMap.map( command => command[0] ));
  4698. var matchCount = Math.max(...cmdSyntaxMap.filter( command => command[0] === lastIndex ).map( command => command[1] ));
  4699. var regex = new RegExp('/' + aliasCmd, 'g');
  4700. var cmdSyntax = minecraft.cmd.list[aliasCmd].filter( (command, i) => ( lastIndex === -1 || cmdSyntaxMap[i][0] === lastIndex ) && cmdSyntaxMap[i][1] === matchCount ).join('\n').replaceSave( regex, '/' + befehl );
  4701. msg.sendChannel( spoiler + '```md\n' + cmdSyntax + '```<' + mclang.link + mclang.cmd.page + aliasCmd + '>' + spoiler, {split:{maxLength:2000,prepend:spoiler + '```md\n',append:'```' + spoiler}} );
  4702. if ( reaction ) reaction.removeEmoji();
  4703. }
  4704. else {
  4705. msg.reactEmoji('❓');
  4706. msg.notminecraft = true;
  4707. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4708. }
  4709. }
  4710. function minecraft_command2(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  4711. if ( args.join('') ) {
  4712. if ( args[0].startsWith( '/' ) ) minecraft_command(lang, mclang, msg, args[0].substring(1), args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  4713. else minecraft_command(lang, mclang, msg, args[0], args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  4714. }
  4715. else {
  4716. msg.notminecraft = true;
  4717. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  4718. }
  4719. }
  4720. function cmd_get(lang, msg, args, line, wiki) {
  4721. var id = args.join().replace( /^\\?<(?:@!?|#)(\d+)>$/, '$1' );
  4722. if ( /^\d+$/.test(id) ) {
  4723. if ( client.guilds.cache.has(id) ) {
  4724. var guild = client.guilds.cache.get(id);
  4725. var guildname = ['Guild:', guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( pause[guild.id] ? '\\*' : '' )];
  4726. var guildowner = ['Owner:', ( guild.owner ? guild.owner.user.tag.escapeFormatting() + ' `' + guild.ownerID + '` ' + guild.owner.toString() : '`' + guild.ownerID + '`' )];
  4727. var guildsize = ['Size:', guild.memberCount + ' members (' + guild.members.cache.filter( member => member.user.bot ).size + ' bots)'];
  4728. var guildpermissions = ['Missing permissions:', ( guild.me.permissions.has(defaultPermissions) ? '*none*' : '`' + guild.me.permissions.missing(defaultPermissions).join('`, `') + '`' )];
  4729. var guildsettings = ['Settings:', '*unknown*'];
  4730. db.all( 'SELECT channel, prefix, lang, wiki, inline FROM discord WHERE guild = ? ORDER BY channel ASC', [guild.id], (dberror, rows) => {
  4731. if ( dberror ) {
  4732. console.log( '- Error while getting the settings: ' + dberror );
  4733. }
  4734. else if ( rows.length ) {
  4735. row = rows.find( row => !row.channel );
  4736. row.patreon = guild.id in patreons;
  4737. row.voice = guild.id in voice;
  4738. guildsettings[1] = '```json\n' + JSON.stringify( rows, null, '\t' ) + '\n```';
  4739. }
  4740. else guildsettings[1] = '*default*';
  4741. if ( msg.showEmbed() ) {
  4742. 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] );
  4743. var split = Discord.Util.splitMessage( guildsettings[1], {char:',\n',maxLength:1000,prepend:'```json\n',append:',\n```'} );
  4744. if ( split.length > 5 ) {
  4745. msg.sendChannel( '', {embed}, true );
  4746. msg.sendChannel( guildsettings.join(' '), {split:{char:',\n',prepend:'```json\n',append:',\n```'}}, true );
  4747. }
  4748. else {
  4749. split.forEach( guildsettingspart => embed.addField( guildsettings[0], guildsettingspart ) );
  4750. msg.sendChannel( '', {embed}, true );
  4751. }
  4752. }
  4753. else {
  4754. var text = guildname.join(' ') + '\n' + guildowner.join(' ') + '\n' + guildsize.join(' ') + '\n' + guildpermissions.join(' ') + '\n' + guildsettings.join(' ');
  4755. msg.sendChannel( text, {split:{char:',\n',prepend:'```json\n',append:',\n```'}}, true );
  4756. }
  4757. } );
  4758. } else if ( client.guilds.cache.some( guild => guild.members.cache.has(id) ) ) {
  4759. var username = [];
  4760. var guildlist = ['Guilds:'];
  4761. var guilds = client.guilds.cache.filter( guild => guild.members.cache.has(id) );
  4762. guildlist.push('\n' + guilds.map( function(guild) {
  4763. var member = guild.members.cache.get(id);
  4764. if ( !username.length ) username.push('User:', member.user.tag.escapeFormatting() + ' `' + member.id + '` ' + member.toString());
  4765. return guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( member.permissions.has('MANAGE_GUILD') ? '\\*' : '' );
  4766. } ).join('\n'));
  4767. if ( guildlist[1].length > 1000 ) guildlist[1] = guilds.size;
  4768. if ( msg.showEmbed() ) {
  4769. var text = '';
  4770. var embed = new Discord.MessageEmbed().addField( username[0], username[1] ).addField( guildlist[0], guildlist[1] );
  4771. }
  4772. else {
  4773. var embed = {};
  4774. var text = username.join(' ') + '\n' + guildlist.join(' ');
  4775. }
  4776. msg.sendChannel( text, {embed}, true );
  4777. } else if ( client.guilds.cache.some( guild => guild.channels.cache.filter( chat => chat.type === 'text' ).has(id) ) ) {
  4778. var channel = client.guilds.cache.find( guild => guild.channels.cache.filter( chat => chat.type === 'text' ).has(id) ).channels.cache.get(id);
  4779. var channelguild = ['Guild:', channel.guild.name.escapeFormatting() + ' `' + channel.guild.id + '`' + ( pause[channel.guild.id] ? '\\*' : '' )];
  4780. var channelname = ['Channel:', '#' + channel.name.escapeFormatting() + ' `' + channel.id + '` ' + channel.toString()];
  4781. var channelpermissions = ['Missing permissions:', ( channel.permissionsFor(channel.guild.me).has(defaultPermissions) ? '*none*' : '`' + channel.permissionsFor(channel.guild.me).missing(defaultPermissions).join('`, `') + '`' )];
  4782. var channellang = ['Language:', '*unknown*'];
  4783. var channelwiki = ['Default Wiki:', '*unknown*'];
  4784. var channelinline = ['Inline commands:', '*unknown*'];
  4785. 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) => {
  4786. if ( dberror ) {
  4787. console.log( '- Error while getting the settings: ' + dberror );
  4788. }
  4789. else if ( row ) {
  4790. channellang[1] = row.lang;
  4791. channelwiki[1] = row.wiki;
  4792. channelinline[1] = ( row.inline ? 'disabled' : 'enabled' );
  4793. }
  4794. else {
  4795. channellang[1] = defaultSettings.lang;
  4796. channelwiki[1] = defaultSettings.wiki;
  4797. channelinline[1] = 'enabled';
  4798. }
  4799. if ( msg.showEmbed() ) {
  4800. var text = '';
  4801. 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] );
  4802. }
  4803. else {
  4804. var embed = {};
  4805. var text = channelguild.join(' ') + '\n' + channelname.join(' ') + '\n' + channelpermissions.join(' ') + '\n' + channellang.join(' ') + '\n' + channelwiki[0] + ' <' + channelwiki[1] + '>\n' + channelinline.join(' ');
  4806. }
  4807. msg.sendChannel( text, {embed}, true );
  4808. } );
  4809. } else msg.replyMsg( 'I couldn\'t find a result for `' + id + '`', {}, true );
  4810. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4811. }
  4812. function cmd_patreon(lang, msg, args, line, wiki) {
  4813. if ( msg.channel.id !== process.env.channel || !args.join('') ) {
  4814. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4815. return;
  4816. }
  4817. if ( args[0] === 'enable' && /^\d+$/.test(args.slice(1).join(' ')) ) {
  4818. if ( !client.guilds.cache.has(args[1]) ) return msg.replyMsg( 'I\'m not on a server with the id `' + args[1] + '`.', {}, true );
  4819. if ( args[1] in patreons ) return msg.replyMsg( '"' + client.guilds.cache.get(args[1]) + '" has the patreon features already enabled.', {}, true );
  4820. 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) => {
  4821. if ( dberror ) {
  4822. console.log( '- Error while getting the patreon: ' + dberror );
  4823. msg.replyMsg( 'I got an error while searching for you, please try again later.', {}, true );
  4824. return dberror;
  4825. }
  4826. if ( !row ) return msg.replyMsg( 'you can\'t have any server.', {}, true );
  4827. if ( row.count <= row.guilds ) return msg.replyMsg( 'you already reached your maximal server count.', {}, true );
  4828. db.run( 'UPDATE discord SET patreon = ? WHERE guild = ? AND channel IS NULL', [msg.author.id, args[1]], function (error) {
  4829. if ( error ) {
  4830. console.log( '- Error while updating the guild: ' + error );
  4831. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4832. return error;
  4833. }
  4834. if ( !this.changes ) return db.run( 'INSERT INTO discord(guild, patreon) VALUES(?, ?)', [args[1], msg.author.id], function (inserror) {
  4835. if ( inserror ) {
  4836. console.log( '- Error while adding the guild: ' + inserror );
  4837. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4838. return inserror;
  4839. }
  4840. console.log( '- Guild successfully added.' );
  4841. patreons[args[1]] = process.env.prefix;
  4842. msg.replyMsg( 'the patreon features are now enabled on "' + client.guilds.cache.get(args[1]) + '".', {}, true );
  4843. } );
  4844. console.log( '- Guild successfully updated.' );
  4845. patreons[args[1]] = process.env.prefix;
  4846. msg.replyMsg( 'the patreon features are now enabled on "' + client.guilds.cache.get(args[1]) + '".', {}, true );
  4847. } );
  4848. } );
  4849. }
  4850. if ( args[0] === 'disable' && /^\d+$/.test(args.slice(1).join(' ')) ) {
  4851. if ( !client.guilds.cache.has(args[1]) ) return msg.replyMsg( 'I\'m not on a server with the id `' + args[1] + '`.', {}, true );
  4852. if ( !( args[1] in patreons ) ) return msg.replyMsg( '"' + client.guilds.cache.get(args[1]) + '" doesn\'t have the patreon features enabled.', {}, true );
  4853. return db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND patreon = ?', [args[1], msg.author.id], (dberror, row) => {
  4854. if ( dberror ) {
  4855. console.log( '- Error while getting the guild: ' + dberror );
  4856. msg.replyMsg( 'I got an error while searching for the server, please try again later.', {}, true );
  4857. return dberror;
  4858. }
  4859. if ( !row ) return msg.replyMsg( 'you didn\'t enable the patreon features for "' + client.guilds.cache.get(args[1]) + '"!', {}, true );
  4860. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, args[1]], function (error) {
  4861. if ( error ) {
  4862. console.log( '- Error while updating the guild: ' + error );
  4863. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4864. return error;
  4865. }
  4866. console.log( '- Guild successfully updated.' );
  4867. delete patreons[args[1]];
  4868. msg.replyMsg( 'the patreon features are now disabled on "' + client.guilds.cache.get(args[1]) + '".', {}, true );
  4869. } );
  4870. } );
  4871. }
  4872. if ( args[1] ) args[1] = args[1].replace( /^\\?<@!?(\d+)>$/, '$1' );
  4873. if ( args[0] === 'check' ) {
  4874. 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) => {
  4875. if ( dberror ) {
  4876. console.log( '- Error while getting the patreon: ' + dberror );
  4877. msg.replyMsg( 'I got an error while searching for you, please try again later.', {}, true );
  4878. return dberror;
  4879. }
  4880. if ( !row ) return msg.replyMsg( 'you can\'t have any server.', {}, true );
  4881. var text = 'you can have up to ' + row.count + ' server.\n\n';
  4882. if ( row.guilds ) {
  4883. var guilds = row.guilds.split(',').map( guild => '`' + guild + '` ' + ( client.guilds.cache.has(guild) ? client.guilds.cache.get(guild).name : '' ) );
  4884. text += 'Currently you have ' + guilds.length + ' server:\n' + guilds.join('\n');
  4885. }
  4886. else text += '*You don\'t have any server yet.*';
  4887. msg.replyMsg( text, {}, true );
  4888. } );
  4889. 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) => {
  4890. if ( dberror ) {
  4891. console.log( '- Error while getting the patreon: ' + dberror );
  4892. msg.replyMsg( 'I got an error while searching for <@' + args[1] + '>, please try again later.', {}, true );
  4893. return dberror;
  4894. }
  4895. if ( !row ) return msg.replyMsg( '<@' + args[1] + '> can\'t have any server.', {}, true );
  4896. var text = '<@' + args[1] + '> can have up to ' + row.count + ' server.\n\n';
  4897. if ( row.guilds ) {
  4898. var guilds = row.guilds.split(',').map( guild => '`' + guild + '` ' + ( client.guilds.cache.has(guild) ? client.guilds.cache.get(guild).name : '' ) );
  4899. text += 'Currently they have ' + guilds.length + ' server:\n' + guilds.join('\n');
  4900. }
  4901. else text += '*They don\'t have any server yet.*';
  4902. msg.replyMsg( text, {}, true );
  4903. } );
  4904. }
  4905. 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) => {
  4906. if ( dberror ) {
  4907. console.log( '- Error while getting the patreon: ' + dberror );
  4908. msg.replyMsg( 'I got an error while searching for <@' + args[1] + '>, please try again later.', {}, true );
  4909. return dberror;
  4910. }
  4911. var value = parseInt(args[2], 10);
  4912. var count = ( row ? row.count : 0 );
  4913. var guilds = ( row && row.guilds ? row.guilds.split(',') : [] );
  4914. if ( args[2].startsWith( '+' ) || args[2].startsWith( '-' ) ) count += value;
  4915. else count = value;
  4916. if ( count <= 0 ) return db.run( 'DELETE FROM patreons WHERE patreon = ?', [args[1]], function (error) {
  4917. if ( error ) {
  4918. console.log( '- Error while deleting the patreon: ' + error );
  4919. msg.replyMsg( 'I got an error while deleting <@' + args[1] + '>, please try again later.', {}, true );
  4920. return error;
  4921. }
  4922. console.log( '- Patreon successfully deleted.' );
  4923. if ( !guilds.length ) return msg.replyMsg( '<@' + args[1] + '> is no longer a patreon.', {}, true );
  4924. db.each( 'SELECT guild, lang, inline FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ') AND channel IS NULL', guilds, (eacherror, eachrow) => {
  4925. if ( eacherror ) {
  4926. console.log( '- Error while getting the guild: ' + eacherror );
  4927. msg.replyMsg( 'I couldn\'t disable the patreon features.', {}, true );
  4928. return eacherror;
  4929. }
  4930. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ? WHERE guild = ?', [eachrow.lang, eachrow.inline, process.env.prefix, eachrow.guild], function (uperror) {
  4931. if ( uperror ) {
  4932. console.log( '- Error while updating the guild: ' + uperror );
  4933. msg.replyMsg( 'I couldn\'t disable the patreon features for `' + eachrow.guild + '`.', {}, true );
  4934. return uperror;
  4935. }
  4936. console.log( '- Guild successfully updated.' );
  4937. delete patreons[eachrow.guild];
  4938. } );
  4939. }, (eacherror) => {
  4940. if ( eacherror ) {
  4941. console.log( '- Error while getting the guilds: ' + eacherror );
  4942. msg.replyMsg( 'I couldn\'t disable the patreon features for `' + guilds.join('`, `') + '`.', {}, true );
  4943. return eacherror;
  4944. }
  4945. msg.replyMsg( '<@' + args[1] + '> is no longer a patreon.', {}, true );
  4946. } );
  4947. } );
  4948. if ( !row ) return db.run( 'INSERT INTO patreons(patreon, count) VALUES(?, ?)', [args[1], count], function (error) {
  4949. if ( error ) {
  4950. console.log( '- Error while adding the patreon: ' + error );
  4951. msg.replyMsg( 'I got an error while adding <@' + args[1] + '>, please try again later.', {}, true );
  4952. return error;
  4953. }
  4954. console.log( '- Patreon successfully added.' );
  4955. msg.replyMsg( '<@' + args[1] + '> can now have up to ' + count + ' server.', {}, true );
  4956. } );
  4957. db.run( 'UPDATE patreons SET count = ? WHERE patreon = ?', [count, args[1]], function (error) {
  4958. if ( error ) {
  4959. console.log( '- Error while updating the patreon: ' + error );
  4960. msg.replyMsg( 'I got an error while updating <@' + args[1] + '>, please try again later.', {}, true );
  4961. return error;
  4962. }
  4963. console.log( '- Patreon successfully updated.' );
  4964. var text = '<@' + args[1] + '> can now have up to ' + count + ' server.';
  4965. if ( count < guilds.length ) text += '\n\n**They are now above their server limit!**';
  4966. msg.replyMsg( text, {}, true );
  4967. } );
  4968. } );
  4969. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4970. }
  4971. function discussion_formatting(jsonModel) {
  4972. var description = '';
  4973. switch ( jsonModel.type ) {
  4974. case 'doc':
  4975. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  4976. break;
  4977. case 'paragraph':
  4978. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  4979. description += '\n';
  4980. break;
  4981. case 'openGraph':
  4982. if ( !jsonModel.attrs.wasAddedWithInlineLink ) description += jsonModel.attrs.url + '\n';
  4983. break;
  4984. case 'text':
  4985. var prepend = '';
  4986. var append = '';
  4987. if ( jsonModel.marks ) {
  4988. jsonModel.marks.forEach( mark => {
  4989. switch ( mark.type ) {
  4990. case 'mention':
  4991. prepend += '[';
  4992. append = ']({@wiki}f/u/' + mark.attrs.userId + ')' + append;
  4993. break;
  4994. case 'link':
  4995. prepend += '[';
  4996. append = '](' + mark.attrs.href + ')' + append;
  4997. break;
  4998. case 'strong':
  4999. prepend += '**';
  5000. append = '**' + append;
  5001. break;
  5002. case 'em':
  5003. prepend += '_';
  5004. append = '_' + append;
  5005. break;
  5006. }
  5007. } );
  5008. }
  5009. description += prepend + jsonModel.text.escapeFormatting() + append;
  5010. break;
  5011. case 'image':
  5012. if ( jsonModel.attrs.id !== null ) description += '{@' + jsonModel.attrs.id + '}\n';
  5013. break;
  5014. case 'code_block':
  5015. description += '```\n';
  5016. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  5017. description += '\n```\n';
  5018. break;
  5019. case 'bulletList':
  5020. jsonModel.content.forEach( listItem => {
  5021. description += '\t• ';
  5022. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  5023. } );
  5024. break;
  5025. case 'orderedList':
  5026. var n = 1;
  5027. jsonModel.content.forEach( listItem => {
  5028. description += '\t' + n + '. ';
  5029. n++;
  5030. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  5031. } );
  5032. break;
  5033. }
  5034. return description;
  5035. }
  5036. function htmlToPlain(html) {
  5037. var text = '';
  5038. var parser = new htmlparser.Parser( {
  5039. ontext: (htmltext) => {
  5040. text += htmltext.escapeFormatting();
  5041. }
  5042. }, {decodeEntities:true} );
  5043. parser.write( html );
  5044. parser.end();
  5045. return text;
  5046. };
  5047. function htmlToDiscord(html) {
  5048. var text = '';
  5049. var parser = new htmlparser.Parser( {
  5050. onopentag: (tagname, attribs) => {
  5051. switch (tagname) {
  5052. case 'b':
  5053. text += '**';
  5054. break;
  5055. case 'i':
  5056. text += '*';
  5057. break;
  5058. case 's':
  5059. text += '~~';
  5060. break;
  5061. case 'u':
  5062. text += '__';
  5063. break;
  5064. }
  5065. },
  5066. ontext: (htmltext) => {
  5067. text += htmltext.escapeFormatting();
  5068. },
  5069. onclosetag: (tagname) => {
  5070. switch (tagname) {
  5071. case 'b':
  5072. text += '**';
  5073. break;
  5074. case 'i':
  5075. text += '*';
  5076. break;
  5077. case 's':
  5078. text += '~~';
  5079. break;
  5080. case 'u':
  5081. text += '__';
  5082. break;
  5083. }
  5084. }
  5085. }, {decodeEntities:true} );
  5086. parser.write( html );
  5087. parser.end();
  5088. return text;
  5089. };
  5090. String.prototype.noWiki = function(href) {
  5091. if ( !href ) return false;
  5092. else if ( this.startsWith( 'https://www.' ) ) return true;
  5093. else if ( this.endsWith( '.gamepedia.com/' ) ) return 'https://www.gamepedia.com/' === href;
  5094. else return [
  5095. 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' ),
  5096. this + 'language-wikis'
  5097. ].includes( href.replace( /Unexpected token < in JSON at position 0 in "([^ ]+)"/, '$1' ) );
  5098. };
  5099. String.prototype.isFandom = function() {
  5100. return /^https:\/\/[a-z\d-]{1,50}\.(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?$/.test(this);
  5101. };
  5102. String.prototype.isMention = function(guild) {
  5103. var text = this.trim();
  5104. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  5105. };
  5106. Discord.Message.prototype.isAdmin = function() {
  5107. return this.channel.type === 'text' && this.member && ( this.member.permissions.has('MANAGE_GUILD') || ( this.isOwner() && this.evalUsed ) );
  5108. };
  5109. Discord.Message.prototype.isOwner = function() {
  5110. return this.author.id === process.env.owner;
  5111. };
  5112. Discord.Message.prototype.showEmbed = function() {
  5113. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  5114. };
  5115. Discord.Message.prototype.uploadFiles = function() {
  5116. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  5117. };
  5118. Array.prototype.toEmojis = function() {
  5119. var text = this.join(' ');
  5120. var regex = /(<a?:)(\d+)(>)/g;
  5121. if ( regex.test(text) ) {
  5122. regex.lastIndex = 0;
  5123. var emojis = client.emojis.cache;
  5124. var entry = null;
  5125. while ( ( entry = regex.exec(text) ) !== null ) {
  5126. if ( emojis.has(entry[2]) ) {
  5127. text = text.replaceSave(entry[0], emojis.get(entry[2]).toString());
  5128. } else {
  5129. text = text.replaceSave(entry[0], entry[1] + 'unknown_emoji:' + entry[2] + entry[3]);
  5130. }
  5131. }
  5132. return text.split(' ');
  5133. }
  5134. else return this;
  5135. };
  5136. String.prototype.toLink = function(title = '', querystring = '', fragment = '', path, isMarkdown = false) {
  5137. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment.toSection() : '' );
  5138. 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 );
  5139. else if ( this.endsWith( '.gamepedia.com/' ) ) return this + title.toTitle(isMarkdown) + linksuffix;
  5140. else if ( this.isFandom() ) return this + 'wiki/' + title.toTitle(isMarkdown) + linksuffix;
  5141. else return this + 'index.php?title=' + title.toTitle(isMarkdown, true) + ( linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  5142. };
  5143. String.prototype.toDescLink = function(title = '') {
  5144. return this + 'wiki/' + encodeURIComponent( title.replace( / /g, '_' ) );
  5145. };
  5146. String.prototype.toTitle = function(isMarkdown = false, inQuery = false) {
  5147. var title = this.replace( / /g, '_' ).replace( /\%/g, '%25' ).replace( /\\/g, '%5C' ).replace( /\?/g, '%3F' ).replace( /@(here|everyone)/g, '%40$1' );
  5148. if ( inQuery ) title = title.replace( /\&/g, '%26' );
  5149. if ( isMarkdown ) title = title.replace( /([\(\)])/g, '\\$1' );
  5150. return title;
  5151. };
  5152. String.prototype.toSearch = function() {
  5153. return encodeURIComponent( this ).replace( /%20/g, '+' );
  5154. };
  5155. String.prototype.toSection = function() {
  5156. return encodeURIComponent( this.replace( / /g, '_' ) ).replace( /\'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\%/g, '.' );
  5157. };
  5158. String.prototype.toFormatting = function(showEmbed = false, ...args) {
  5159. if ( showEmbed ) return this.toMarkdown(...args);
  5160. else return this.toPlaintext();
  5161. };
  5162. String.prototype.toMarkdown = function(wiki, path, title = '') {
  5163. var text = this.replace( /[\(\)\\]/g, '\\$&' );
  5164. var link = null;
  5165. while ( ( link = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g.exec(text) ) !== null ) {
  5166. var pagetitle = ( link[1] || link[2] );
  5167. var page = wiki.toLink(( /^[#\/]/.test(pagetitle) ? title + ( pagetitle.startsWith( '/' ) ? pagetitle : '' ) : pagetitle ), '', ( pagetitle.startsWith( '#' ) ? pagetitle.substring(1) : '' ), path, true);
  5168. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + page + ')' );
  5169. }
  5170. while ( title !== '' && ( link = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g.exec(text) ) !== null ) {
  5171. text = text.replaceSave( link[0], '[→' + link[1] + '](' + wiki.toLink(title, '', link[1], path, true) + ')' + ( link[2] ? ': ' + link[2] : '' ) );
  5172. }
  5173. return text.escapeFormatting(true);
  5174. };
  5175. String.prototype.toPlaintext = function() {
  5176. return this.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' ).escapeFormatting();
  5177. };
  5178. String.prototype.escapeFormatting = function(isMarkdown) {
  5179. var text = this;
  5180. if ( !isMarkdown ) text = text.replace( /[\(\)\\]/g, '\\$&' );
  5181. return text.replace( /[`_\*~:<>{}@\|]|\/\//g, '\\$&' );
  5182. };
  5183. String.prototype.replaceSave = function(pattern, replacement) {
  5184. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  5185. };
  5186. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  5187. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  5188. var emoji = '440871715938238494';
  5189. switch ( name ) {
  5190. case 'nowiki':
  5191. emoji = '505884572001763348';
  5192. break;
  5193. case 'error':
  5194. emoji = '440871715938238494';
  5195. break;
  5196. case 'support':
  5197. emoji = '448222377009086465';
  5198. break;
  5199. case 'oppose':
  5200. emoji = '448222455425794059';
  5201. break;
  5202. default:
  5203. emoji = name;
  5204. }
  5205. return this.react(emoji).catch(log_error);
  5206. } else {
  5207. console.log( '- Aborted, paused.' );
  5208. return Promise.resolve();
  5209. }
  5210. };
  5211. Discord.MessageReaction.prototype.removeEmoji = function() {
  5212. return this.users.remove().catch(log_error);
  5213. };
  5214. Discord.Message.prototype.sendChannel = function(content, options = {}, ignorePause = false) {
  5215. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  5216. if ( !options.allowedMentions ) options.allowedMentions = {parse:[]};
  5217. return this.channel.send(content, options).then( msg => {
  5218. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  5219. else msg.allowDelete(this.author.id);
  5220. return msg;
  5221. }, log_error );
  5222. } else {
  5223. console.log( '- Aborted, paused.' );
  5224. return Promise.resolve();
  5225. }
  5226. };
  5227. Discord.Message.prototype.sendChannelError = function(content, options = {}) {
  5228. if ( !options.allowedMentions ) options.allowedMentions = {parse:[]};
  5229. return this.channel.send(content, options).then( msg => {
  5230. if ( msg.length ) msg.forEach( message => {
  5231. message.reactEmoji('error');
  5232. message.allowDelete(this.author.id);
  5233. } );
  5234. else {
  5235. msg.reactEmoji('error');
  5236. msg.allowDelete(this.author.id);
  5237. }
  5238. return msg;
  5239. }, log_error );
  5240. };
  5241. Discord.Message.prototype.replyMsg = function(content, options = {}, ignorePause = false, allowDelete = true) {
  5242. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  5243. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  5244. return this.reply(content, options).then( msg => {
  5245. if ( allowDelete ) {
  5246. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  5247. else msg.allowDelete(this.author.id);
  5248. }
  5249. return msg;
  5250. }, log_error );
  5251. } else {
  5252. console.log( '- Aborted, paused.' );
  5253. return Promise.resolve();
  5254. }
  5255. };
  5256. Discord.Message.prototype.deleteMsg = function(timeout = 0) {
  5257. return this.delete({timeout}).catch(log_error);
  5258. };
  5259. Discord.Message.prototype.allowDelete = function(author) {
  5260. return this.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:120000} ).then( reaction => {
  5261. if ( reaction.size ) {
  5262. this.deleteMsg();
  5263. }
  5264. } );
  5265. };
  5266. String.prototype.hasPrefix = function(prefix, flags = '') {
  5267. return new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + '(?: |$)', flags ).test(this.replace( /\u200b/g, '' ).toLowerCase());
  5268. };
  5269. client.on( 'message', msg => {
  5270. if ( stop || msg.type !== 'DEFAULT' || msg.system || msg.webhookID || msg.author.id === client.user.id ) return;
  5271. if ( !msg.content.hasPrefix(( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  5272. if ( msg.content === process.env.prefix + ' help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  5273. if ( msg.channel.permissionsFor(client.user).has('SEND_MESSAGES') ) {
  5274. console.log( msg.guild.name + ': ' + msg.content );
  5275. 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) => {
  5276. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  5277. msg.replyMsg( i18n[( row || defaultSettings ).lang].prefix.replaceSave( /%s/g, patreons[msg.guild.id] ), {}, true );
  5278. } );
  5279. }
  5280. }
  5281. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  5282. }
  5283. if ( !ready.allSites && !allSites.length ) getAllSites();
  5284. if ( msg.channel.type === 'text' ) {
  5285. var permissions = msg.channel.permissionsFor(client.user);
  5286. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  5287. if ( missing.length ) {
  5288. if ( msg.isAdmin() || msg.isOwner() ) {
  5289. console.log( msg.guild.id + ': Missing permissions - ' + missing.join(', ') );
  5290. if ( !missing.includes( 'SEND_MESSAGES' ) ) {
  5291. 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) => {
  5292. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  5293. if ( msg.content.hasPrefix(( patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  5294. msg.replyMsg( i18n[( row || defaultSettings ).lang].missingperm + ' `' + missing.join('`, `') + '`', {}, true );
  5295. }
  5296. } );
  5297. }
  5298. }
  5299. return;
  5300. }
  5301. 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) => {
  5302. if ( dberror ) {
  5303. console.log( '- Error while getting the wiki: ' + dberror );
  5304. if ( permissions.has('SEND_MESSAGES') ) {
  5305. msg.sendChannel( '⚠️ **Limited Functionality** ⚠️\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  5306. newMessage(msg);
  5307. }
  5308. return dberror;
  5309. }
  5310. if ( row ) newMessage(msg, row.wiki, i18n[row.lang], patreons[msg.guild.id], row.inline);
  5311. else {
  5312. msg.defaultSettings = true;
  5313. newMessage(msg);
  5314. }
  5315. } );
  5316. }
  5317. else newMessage(msg);
  5318. } );
  5319. function newMessage(msg, wiki = defaultSettings.wiki, lang = i18n[defaultSettings.lang], prefix = process.env.prefix, noInline = null, content) {
  5320. msg.noInline = noInline;
  5321. var cont = ( content || msg.content );
  5322. var cleanCont = ( content || msg.cleanContent );
  5323. var author = msg.author;
  5324. var channel = msg.channel;
  5325. var invoke = ( cont.split(' ')[1] ? cont.split(' ')[1].split('\n')[0].toLowerCase() : '' );
  5326. var aliasInvoke = ( lang.aliase[invoke] || invoke );
  5327. var ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  5328. if ( cont.hasPrefix(prefix) && ownercmd ) {
  5329. var args = cont.split(' ').slice(2);
  5330. if ( cont.split(' ')[1].split('\n')[1] ) args.unshift( '', cont.split(' ')[1].split('\n')[1] );
  5331. else console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + cont );
  5332. ownercmdmap[aliasInvoke](lang, msg, args, cont, wiki);
  5333. } else {
  5334. var count = 0;
  5335. var maxcount = ( channel.type === 'text' && msg.guild.id in patreons ? 15 : 10 );
  5336. cleanCont.replace( /\u200b/g, '' ).split('\n').forEach( line => {
  5337. if ( line.hasPrefix(prefix) && count < maxcount ) {
  5338. count++;
  5339. invoke = ( line.split(' ')[1] ? line.split(' ')[1].toLowerCase() : '' );
  5340. var args = line.split(' ').slice(2);
  5341. aliasInvoke = ( lang.aliase[invoke] || invoke );
  5342. ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  5343. if ( channel.type === 'text' && pause[msg.guild.id] && !( ( msg.isAdmin() && aliasInvoke in pausecmdmap ) || ownercmd ) ) console.log( msg.guild.id + ': Paused' );
  5344. else console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + line );
  5345. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, line, wiki);
  5346. else if ( channel.type !== 'text' || !pause[msg.guild.id] || ( msg.isAdmin() && aliasInvoke in pausecmdmap ) ) {
  5347. if ( aliasInvoke in cmdmap ) cmdmap[aliasInvoke](lang, msg, args, line, wiki);
  5348. else if ( /^![a-z\d-]{1,50}$/.test(invoke) ) {
  5349. cmd_link(lang, msg, args.join(' '), 'https://' + invoke.substring(1) + '.gamepedia.com/', ' ' + invoke + ' ');
  5350. }
  5351. else if ( /^\?(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  5352. var invokeWiki = wiki;
  5353. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.fandom.com/' + invoke.substring(1).split('.')[0] + '/';
  5354. else invokeWiki = 'https://' + invoke.substring(1) + '.fandom.com/';
  5355. cmd_link(lang, msg, args.join(' '), invokeWiki, ' ' + invoke + ' ');
  5356. }
  5357. else if ( /^\?\?(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  5358. var invokeWiki = wiki;
  5359. if ( invoke.includes( '.' ) ) invokeWiki = 'https://' + invoke.split('.')[1] + '.wikia.org/' + invoke.substring(2).split('.')[0] + '/';
  5360. else invokeWiki = 'https://' + invoke.substring(2) + '.wikia.org/';
  5361. cmd_link(lang, msg, args.join(' '), invokeWiki, ' ' + invoke + ' ');
  5362. }
  5363. else cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  5364. }
  5365. } else if ( line.hasPrefix(prefix) && count === maxcount ) {
  5366. count++;
  5367. console.log( '- Message contains too many commands!' );
  5368. msg.reactEmoji('⚠️');
  5369. msg.sendChannelError( lang.limit.replaceSave( '%s', '<@' + author.id + '>' ), {allowedMentions:{users:[author.id]}} );
  5370. }
  5371. } );
  5372. if ( ( channel.type !== 'text' || !pause[msg.guild.id] ) && !noInline && ( cont.includes( '[[' ) || cont.includes( '{{' ) ) ) {
  5373. var links = [];
  5374. var embeds = [];
  5375. var linkcount = 0;
  5376. var linkmaxcount = maxcount + 5;
  5377. msg.cleanContent.replace( /\u200b/g, '' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).replace( /(?<!\\)`.+?`/gs, '<code>' ).split('\n').forEach( line => {
  5378. if ( line.hasPrefix(prefix) || !( line.includes( '[[' ) || line.includes( '{{' ) ) ) return;
  5379. if ( line.includes( '[[' ) && line.includes( ']]' ) && linkcount <= linkmaxcount ) {
  5380. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)\\[\\[([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\]\\]\\1', 'g' );
  5381. let entry = null;
  5382. while ( ( entry = regex.exec(line) ) !== null ) {
  5383. if ( linkcount < linkmaxcount ) {
  5384. linkcount++;
  5385. console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  5386. let title = entry[2].split('#')[0];
  5387. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  5388. links.push({title,section,spoiler:entry[1]});
  5389. }
  5390. else if ( linkcount === linkmaxcount ) {
  5391. linkcount++;
  5392. console.log( '- Message contains too many links!' );
  5393. msg.reactEmoji('⚠️');
  5394. break;
  5395. }
  5396. }
  5397. }
  5398. if ( line.includes( '{{' ) && line.includes( '}}' ) && count <= maxcount ) {
  5399. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)(?<!\\{)\\{\\{([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\}\\}\\1', 'g' );
  5400. let entry = null;
  5401. while ( ( entry = regex.exec(line) ) !== null ) {
  5402. if ( count < maxcount ) {
  5403. count++;
  5404. console.log( ( channel.type === 'text' ? msg.guild.id : '@' + author.id ) + ': ' + entry[0] );
  5405. let title = entry[2].split('#')[0];
  5406. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  5407. embeds.push({title,section,spoiler:entry[1]});
  5408. }
  5409. else if ( count === maxcount ) {
  5410. count++;
  5411. console.log( '- Message contains too many links!' );
  5412. msg.reactEmoji('⚠️');
  5413. break;
  5414. }
  5415. }
  5416. }
  5417. } );
  5418. 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', {
  5419. responseType: 'json'
  5420. } ).then( response => {
  5421. var body = response.body;
  5422. if ( response.statusCode !== 200 || !body || !body.query ) {
  5423. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  5424. console.log( '- This wiki doesn\'t exist!' );
  5425. msg.reactEmoji('nowiki');
  5426. return;
  5427. }
  5428. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  5429. return;
  5430. }
  5431. if ( body.query.normalized ) {
  5432. body.query.normalized.forEach( title => links.filter( link => link.title === title.from ).forEach( link => link.title = title.to ) );
  5433. }
  5434. if ( body.query.interwiki ) {
  5435. body.query.interwiki.forEach( interwiki => links.filter( link => link.title === interwiki.title ).forEach( link => {
  5436. link.url = interwiki.url + ( link.section ? '#' + link.section.toSection() : '' );
  5437. } ) );
  5438. }
  5439. if ( body.query.pages ) {
  5440. var querypages = Object.values(body.query.pages);
  5441. querypages.filter( page => page.invalid !== undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  5442. links.splice(links.indexOf(link), 1);
  5443. } ) );
  5444. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  5445. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  5446. link.url = wiki.toLink(link.title, 'action=edit&redlink=1', '', body.query.general);
  5447. } ) );
  5448. }
  5449. 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} );
  5450. }, error => {
  5451. if ( wiki.noWiki(error.message) ) {
  5452. console.log( '- This wiki doesn\'t exist!' );
  5453. msg.reactEmoji('nowiki');
  5454. }
  5455. else {
  5456. console.log( '- Error while following the links: ' + error );
  5457. }
  5458. } );
  5459. 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', {
  5460. responseType: 'json'
  5461. } ).then( response => {
  5462. var body = response.body;
  5463. if ( response.statusCode !== 200 || !body || !body.query ) {
  5464. if ( wiki.noWiki(response.url) || response.statusCode === 410 ) {
  5465. console.log( '- This wiki doesn\'t exist!' );
  5466. msg.reactEmoji('nowiki');
  5467. return;
  5468. }
  5469. console.log( '- ' + response.statusCode + ': Error while following the links: ' + ( body && body.error && body.error.info ) );
  5470. return;
  5471. }
  5472. if ( body.query.normalized ) {
  5473. body.query.normalized.forEach( title => embeds.filter( embed => embed.title === title.from ).forEach( embed => embed.title = title.to ) );
  5474. }
  5475. if ( body.query.pages ) {
  5476. var querypages = Object.values(body.query.pages);
  5477. querypages.filter( page => page.invalid !== undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  5478. embeds.splice(embeds.indexOf(embed), 1);
  5479. } ) );
  5480. var missing = [];
  5481. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  5482. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  5483. embeds.splice(embeds.indexOf(embed), 1);
  5484. if ( page.ns === 0 && !embed.section ) {
  5485. var template = querypages.find( template => template.ns === 10 && template.title.split(':').slice(1).join(':') === embed.title );
  5486. if ( template && template.missing === undefined ) embed.template = wiki.toLink(template.title, '', '', body.query.general);
  5487. }
  5488. if ( embed.template || !body.query.variables || !body.query.variables.some( variable => variable.toUpperCase() === embed.title ) ) missing.push(embed);
  5489. } ) );
  5490. if ( missing.length ) {
  5491. 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} );
  5492. }
  5493. }
  5494. if ( embeds.length ) {
  5495. if ( wiki.isFandom() ) embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  5496. fandom_check_wiki(lang, msg, embed.title, wiki, ' ', reaction, embed.spoiler, '', embed.section);
  5497. } ) );
  5498. else embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  5499. gamepedia_check_wiki(lang, msg, embed.title, wiki, ' ', reaction, embed.spoiler, '', embed.section);
  5500. } ) );
  5501. }
  5502. }, error => {
  5503. if ( wiki.noWiki(error.message) ) {
  5504. console.log( '- This wiki doesn\'t exist!' );
  5505. msg.reactEmoji('nowiki');
  5506. }
  5507. else {
  5508. console.log( '- Error while following the links: ' + error );
  5509. }
  5510. } );
  5511. }
  5512. }
  5513. }
  5514. client.on( 'voiceStateUpdate', (olds, news) => {
  5515. if ( stop || !( olds.guild.id in voice ) || !olds.guild.me.permissions.has('MANAGE_ROLES') || olds.channelID === news.channelID ) return;
  5516. if ( !ready.allSites && !allSites.length ) getAllSites();
  5517. var lang = i18n[voice[olds.guild.id]].voice;
  5518. if ( olds.member && olds.channel ) {
  5519. var oldrole = olds.member.roles.cache.find( role => role.name === lang.channel + ' – ' + olds.channel.name );
  5520. if ( oldrole && oldrole.comparePositionTo(olds.guild.me.roles.highest) < 0 ) {
  5521. console.log( olds.guild.id + ': ' + olds.member.id + ' left the voice channel "' + olds.channel.id + '".' );
  5522. olds.member.roles.remove( oldrole, lang.left.replaceSave( '%1$s', olds.member.displayName ).replaceSave( '%2$s', olds.channel.name ) ).catch(log_error);
  5523. }
  5524. }
  5525. if ( news.member && news.channel ) {
  5526. var newrole = news.guild.roles.cache.find( role => role.name === lang.channel + ' – ' + news.channel.name );
  5527. if ( newrole && newrole.comparePositionTo(news.guild.me.roles.highest) < 0 ) {
  5528. console.log( news.guild.id + ': ' + news.member.id + ' joined the voice channel "' + news.channel.id + '".' );
  5529. news.member.roles.add( newrole, lang.join.replaceSave( '%1$s', news.member.displayName ).replaceSave( '%2$s', news.channel.name ) ).catch(log_error);
  5530. }
  5531. }
  5532. } );
  5533. client.on( 'guildCreate', guild => {
  5534. console.log( '- I\'ve been added to a server.' );
  5535. } );
  5536. client.on( 'guildDelete', guild => {
  5537. if ( !guild.available ) {
  5538. console.log( '- ' + guild.id + ': This server isn\'t responding.' );
  5539. return;
  5540. }
  5541. console.log( '- I\'ve been removed from a server.' );
  5542. db.run( 'DELETE FROM discord WHERE guild = ?', [guild.id], function (dberror) {
  5543. if ( dberror ) {
  5544. console.log( '- Error while removing the settings: ' + dberror );
  5545. return dberror;
  5546. }
  5547. if ( guild.id in patreons ) delete patreons[guild.id];
  5548. if ( guild.id in voice ) delete voice[guild.id];
  5549. console.log( '- Settings successfully removed.' );
  5550. } );
  5551. db.run( 'DELETE FROM verification WHERE guild = ?', [guild.id], function (dberror) {
  5552. if ( dberror ) {
  5553. console.log( '- Error while removing the verifications: ' + dberror );
  5554. return dberror;
  5555. }
  5556. console.log( '- Verifications successfully removed.' );
  5557. } );
  5558. } );
  5559. function removePatreons(guild, msg) {
  5560. try {
  5561. if ( !guild ) return 'removePatreons(guild, msg) – No guild provided!';
  5562. db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND channel IS NULL', [guild], (dberror, row) => {
  5563. try {
  5564. if ( dberror ) {
  5565. console.log( '- Error while getting the guild: ' + dberror );
  5566. if ( msg ) msg.replyMsg( 'I got an error while searching for the guild!', {}, true );
  5567. return dberror;
  5568. }
  5569. if ( !row ) {
  5570. if ( msg ) msg.replyMsg( 'that guild doesn\'t exist!', {}, true );
  5571. return;
  5572. }
  5573. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, guild], function (error) {
  5574. try {
  5575. if ( error ) {
  5576. console.log( '- Error while updating the guild: ' + error );
  5577. if ( msg ) msg.replyMsg( 'I got an error while updating the guild!', {}, true );
  5578. return error;
  5579. }
  5580. console.log( '- Guild successfully updated.' );
  5581. delete patreons[guild];
  5582. if ( msg ) msg.replyMsg( 'the patreon features are now disabled on that guild.', {}, true );
  5583. }
  5584. catch ( tryerror ) {
  5585. console.log( '- Error while removing the patreon features: ' + tryerror );
  5586. }
  5587. } );
  5588. }
  5589. catch ( tryerror ) {
  5590. console.log( '- Error while removing the patreon features: ' + tryerror );
  5591. }
  5592. } );
  5593. }
  5594. catch ( tryerror ) {
  5595. console.log( '- Error while removing the patreon features: ' + tryerror );
  5596. return 'removePatreons(guild, msg) – Error while removing the patreon features: ' + tryerror;
  5597. }
  5598. }
  5599. function removeSettings() {
  5600. var guilds = [];
  5601. var channels = [];
  5602. db.each( 'SELECT guild, channel FROM discord', [], (dberror, row) => {
  5603. if ( dberror ) {
  5604. console.log( '- Error while getting the setting: ' + dberror );
  5605. return dberror;
  5606. }
  5607. if ( !row.channel && !client.guilds.cache.has(row.guild) ) {
  5608. if ( row.guild in patreons ) delete patreons[row.guild];
  5609. if ( row.guild in voice ) delete voice[row.guild];
  5610. return guilds.push(row.guild);
  5611. }
  5612. 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);
  5613. }, (error) => {
  5614. if ( error ) {
  5615. console.log( '- Error while getting the settings: ' + error );
  5616. return error;
  5617. }
  5618. if ( guilds.length ) {
  5619. db.run( 'DELETE FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  5620. if ( dberror ) {
  5621. console.log( '- Error while removing the guilds: ' + dberror );
  5622. return dberror;
  5623. }
  5624. console.log( '- Guilds successfully removed.' );
  5625. } );
  5626. db.run( 'DELETE FROM verification WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  5627. if ( dberror ) {
  5628. console.log( '- Error while removing the verifications: ' + dberror );
  5629. return dberror;
  5630. }
  5631. console.log( '- Verifications successfully removed.' );
  5632. } );
  5633. }
  5634. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( channel => '?' ).join(', ') + ')', channels, function (dberror) {
  5635. if ( dberror ) {
  5636. console.log( '- Error while removing the channels: ' + dberror );
  5637. return dberror;
  5638. }
  5639. console.log( '- Channels successfully removed.' );
  5640. } );
  5641. if ( !guilds.length && !channels.length ) console.log( '- Settings successfully removed.' );
  5642. } );
  5643. }
  5644. client.login(process.env.token).catch( error => {
  5645. log_error(error, true, 'LOGIN-');
  5646. client.login(process.env.token).catch( error => {
  5647. log_error(error, true, 'LOGIN-');
  5648. client.login(process.env.token).catch( error => {
  5649. log_error(error, true, 'LOGIN-');
  5650. process.exit(1);
  5651. } );
  5652. } );
  5653. } );
  5654. client.on( 'error', error => log_error(error, true) );
  5655. client.on( 'warn', warning => log_warn(warning, false) );
  5656. if ( isDebug ) client.on( 'debug', debug => {
  5657. if ( isDebug ) console.log( '- Debug: ' + debug );
  5658. } );
  5659. function log_error(error, isBig = false, type = '') {
  5660. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  5661. if ( isDebug ) {
  5662. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  5663. } else {
  5664. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  5665. else console.log( '- ' + error.name + ': ' + error.message );
  5666. }
  5667. }
  5668. function log_warn(warning, api = true) {
  5669. if ( isDebug ) {
  5670. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  5671. } else {
  5672. if ( api ) console.warn( '- Warning: ' + Object.keys(warning).join(', ') );
  5673. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  5674. }
  5675. }
  5676. async function graceful(code = 0) {
  5677. stop = true;
  5678. console.log( '- SIGTERM: Preparing to close...' );
  5679. setTimeout( async () => {
  5680. console.log( '- SIGTERM: Destroying client...' );
  5681. await client.destroy();
  5682. await db.close( dberror => {
  5683. if ( dberror ) {
  5684. console.log( '- SIGTERM: Error while closing the database connection: ' + dberror );
  5685. return dberror;
  5686. }
  5687. console.log( '- SIGTERM: Closed the database connection.' );
  5688. } );
  5689. setTimeout( async () => {
  5690. console.log( '- SIGTERM: Closing takes too long, terminating!' );
  5691. process.exit(code);
  5692. }, 2000 ).unref();
  5693. }, 1000 ).unref();
  5694. }
  5695. process.once( 'SIGINT', graceful );
  5696. process.once( 'SIGTERM', graceful );