main.js 254 KB

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