main.js 252 KB

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