main.js 254 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169
  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' ) return msg.sendChannelError( '**Sorry, but I don\'t support wikis on UCP yet!**' );
  2437. if ( !title ) {
  2438. var pagelink = wiki + 'f';
  2439. var embed = new Discord.RichEmbed().setAuthor( query.general.sitename ).setTitle( lang.discussion.main ).setURL( pagelink );
  2440. request( {
  2441. uri: wiki + 'f'
  2442. }, function( descerror, descresponse, descbody ) {
  2443. if ( descerror || !descresponse || descresponse.statusCode !== 200 || !descbody ) {
  2444. console.log( '- ' + ( descresponse && descresponse.statusCode ) + ': Error while getting the description: ' + descerror );
  2445. } else {
  2446. var thumbnail = wiki.toLink() + 'Special:FilePath/Wiki-wordmark.png';
  2447. var parser = new htmlparser.Parser( {
  2448. onopentag: (tagname, attribs) => {
  2449. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  2450. var description = attribs.content.escapeFormatting();
  2451. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2452. embed.setDescription( description );
  2453. }
  2454. if ( tagname === 'meta' && attribs.property === 'og:image' ) {
  2455. thumbnail = attribs.content;
  2456. }
  2457. }
  2458. }, {decodeEntities:true} );
  2459. parser.write( descbody );
  2460. parser.end();
  2461. embed.setThumbnail( thumbnail );
  2462. }
  2463. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  2464. if ( reaction ) reaction.removeEmoji();
  2465. } );
  2466. }
  2467. else if ( title.split(' ')[0].toLowerCase() === 'post' || title.split(' ')[0].toLowerCase() === lang.discussion.post ) {
  2468. title = title.split(' ').slice(1).join(' ');
  2469. request( {
  2470. uri: 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/posts?limit=50&format=json'
  2471. }, function( error, response, body ) {
  2472. try {
  2473. if ( body ) body = JSON.parse(body);
  2474. if ( error || !response || response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded['doc:posts'] ) {
  2475. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the posts: ' + ( error || body && body.title ) );
  2476. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2477. if ( reaction ) reaction.removeEmoji();
  2478. }
  2479. else if ( body._embedded['doc:posts'].length ) {
  2480. var posts = body._embedded['doc:posts'];
  2481. var embed = new Discord.RichEmbed().setAuthor( query.general.sitename );
  2482. if ( posts.some( post => post.id === title ) ) {
  2483. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.id === title ), embed, spoiler);
  2484. if ( reaction ) reaction.removeEmoji();
  2485. }
  2486. else if ( /^\d+$/.test(title) ) {
  2487. request( {
  2488. uri: 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/posts/' + title + '?format=json'
  2489. }, function( perror, presponse, pbody ) {
  2490. try {
  2491. if ( pbody ) pbody = JSON.parse(pbody);
  2492. if ( perror || !presponse || presponse.statusCode !== 200 || !pbody || pbody.id !== title ) {
  2493. if ( pbody && pbody.title === 'The requested resource was not found.' ) {
  2494. if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2495. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2496. }
  2497. else msg.reactEmoji('🤷');
  2498. }
  2499. else {
  2500. console.log( '- ' + ( presponse && presponse.statusCode ) + ': Error while getting the post: ' + ( perror || pbody && pbody.title ) );
  2501. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2502. }
  2503. if ( reaction ) reaction.removeEmoji();
  2504. }
  2505. else if ( pbody.title ) {
  2506. fandom_discussionsend(lang, msg, wiki, pbody, embed, spoiler);
  2507. if ( reaction ) reaction.removeEmoji();
  2508. }
  2509. else request( {
  2510. uri: 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads/' + pbody.threadId + '?format=json'
  2511. }, function( therror, thresponse, thbody ) {
  2512. try {
  2513. if ( thbody ) thbody = JSON.parse(thbody);
  2514. if ( therror || !thresponse || thresponse.statusCode !== 200 || !thbody || thbody.id !== pbody.threadId ) {
  2515. console.log( '- ' + ( thresponse && thresponse.statusCode ) + ': Error while getting the thread: ' + ( therror || thbody && thbody.title ) );
  2516. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + pbody.threadId + '>' + spoiler );
  2517. }
  2518. else embed.setTitle( thbody.title.escapeFormatting() );
  2519. }
  2520. catch ( jsonerror ) {
  2521. console.log( '- ' + ( thresponse && thresponse.statusCode ) + ': Error while getting the thread: ' + ( therror || jsonerror ) );
  2522. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + pbody.threadId + '>' + spoiler );
  2523. }
  2524. fandom_discussionsend(lang, msg, wiki, pbody, embed, spoiler);
  2525. if ( reaction ) reaction.removeEmoji();
  2526. } );
  2527. }
  2528. catch ( jsonerror ) {
  2529. console.log( '- ' + ( presponse && presponse.statusCode ) + ': Error while getting the post: ' + ( perror || jsonerror ) );
  2530. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2531. if ( reaction ) reaction.removeEmoji();
  2532. }
  2533. } );
  2534. }
  2535. else if ( posts.some( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2536. fandom_discussionsend(lang, msg, wiki, posts.find( post => post.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2537. if ( reaction ) reaction.removeEmoji();
  2538. }
  2539. else {
  2540. msg.reactEmoji('🤷');
  2541. if ( reaction ) reaction.removeEmoji();
  2542. }
  2543. }
  2544. else {
  2545. msg.reactEmoji('🤷');
  2546. if ( reaction ) reaction.removeEmoji();
  2547. }
  2548. }
  2549. catch ( jsonerror ) {
  2550. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the posts: ' + ( error || jsonerror ) );
  2551. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2552. if ( reaction ) reaction.removeEmoji();
  2553. }
  2554. } );
  2555. }
  2556. else {
  2557. request( {
  2558. uri: 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads?sortKey=trending&limit=50&format=json'
  2559. }, function( error, response, body ) {
  2560. try {
  2561. if ( body ) body = JSON.parse(body);
  2562. if ( error || !response || response.statusCode !== 200 || !body || body.title || !body._embedded || !body._embedded.threads ) {
  2563. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the threads: ' + ( error || body && body.title ) );
  2564. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2565. if ( reaction ) reaction.removeEmoji();
  2566. }
  2567. else if ( body._embedded.threads.length ) {
  2568. var threads = body._embedded.threads;
  2569. var embed = new Discord.RichEmbed().setAuthor( query.general.sitename );
  2570. if ( threads.some( thread => thread.id === title ) ) {
  2571. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.id === title ), embed, spoiler);
  2572. if ( reaction ) reaction.removeEmoji();
  2573. }
  2574. else if ( threads.some( thread => thread.title === title ) ) {
  2575. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title === title ), embed, spoiler);
  2576. if ( reaction ) reaction.removeEmoji();
  2577. }
  2578. else if ( threads.some( thread => thread.title.toLowerCase() === title.toLowerCase() ) ) {
  2579. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase() === title.toLowerCase() ), embed, spoiler);
  2580. if ( reaction ) reaction.removeEmoji();
  2581. }
  2582. else if ( threads.some( thread => thread.title.includes( title ) ) ) {
  2583. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.includes( title ) ), embed, spoiler);
  2584. if ( reaction ) reaction.removeEmoji();
  2585. }
  2586. else if ( threads.some( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2587. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.title.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2588. if ( reaction ) reaction.removeEmoji();
  2589. }
  2590. else if ( /^\d+$/.test(title) ) {
  2591. request( {
  2592. uri: 'https://services.fandom.com/discussion/' + query.wikidesc.id + '/threads/' + title + '?format=json'
  2593. }, function( therror, thresponse, thbody ) {
  2594. try {
  2595. if ( thbody ) thbody = JSON.parse(thbody);
  2596. if ( therror || !thresponse || thresponse.statusCode !== 200 || !thbody || thbody.id !== title ) {
  2597. if ( thbody && thbody.status === 404 ) {
  2598. if (threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2599. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2600. }
  2601. else msg.reactEmoji('🤷');
  2602. }
  2603. else {
  2604. console.log( '- ' + ( thresponse && thresponse.statusCode ) + ': Error while getting the thread: ' + ( therror || thbody && thbody.title ) );
  2605. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  2606. }
  2607. }
  2608. else fandom_discussionsend(lang, msg, wiki, thbody, embed, spoiler);
  2609. }
  2610. catch ( jsonerror ) {
  2611. console.log( '- ' + ( thresponse && thresponse.statusCode ) + ': Error while getting the thread: ' + ( therror || jsonerror ) );
  2612. msg.sendChannelError( spoiler + '<' + wiki + 'f/p/' + title + '>' + spoiler );
  2613. }
  2614. if ( reaction ) reaction.removeEmoji();
  2615. } );
  2616. }
  2617. else if ( threads.some( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ) ) {
  2618. fandom_discussionsend(lang, msg, wiki, threads.find( thread => thread.rawContent.toLowerCase().includes( title.toLowerCase() ) ), embed, spoiler);
  2619. if ( reaction ) reaction.removeEmoji();
  2620. }
  2621. else {
  2622. msg.reactEmoji('🤷');
  2623. if ( reaction ) reaction.removeEmoji();
  2624. }
  2625. }
  2626. else {
  2627. msg.reactEmoji('🤷');
  2628. if ( reaction ) reaction.removeEmoji();
  2629. }
  2630. }
  2631. catch ( jsonerror ) {
  2632. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the threads: ' + ( error || jsonerror ) );
  2633. msg.sendChannelError( spoiler + '<' + wiki + 'f' + '>' + spoiler );
  2634. if ( reaction ) reaction.removeEmoji();
  2635. }
  2636. } );
  2637. }
  2638. }
  2639. function fandom_discussionsend(lang, msg, wiki, discussion, embed, spoiler) {
  2640. if ( discussion.title ) {
  2641. embed.setTitle( discussion.title.escapeFormatting() );
  2642. var pagelink = wiki + 'f/p/' + ( discussion.threadId || discussion.id );
  2643. }
  2644. else {
  2645. if ( discussion._embedded.thread ) embed.setTitle( discussion._embedded.thread[0].title.escapeFormatting() );
  2646. var pagelink = wiki + 'f/p/' + discussion.threadId + '/r/' + discussion.id;
  2647. }
  2648. var text = '<' + pagelink + '>';
  2649. embed.setURL( pagelink ).setFooter( discussion.createdBy.name, discussion.createdBy.avatarUrl ).setTimestamp( discussion.creationDate.epochSecond * 1000 );
  2650. var description = '';
  2651. switch ( discussion.funnel ) {
  2652. case 'IMAGE':
  2653. embed.setImage( discussion._embedded.contentImages[0].url );
  2654. break;
  2655. case 'POLL':
  2656. 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 ) );
  2657. break;
  2658. case 'QUIZ':
  2659. description = discussion.quiz.title.escapeFormatting();
  2660. if ( discussion._embedded.openGraph ) embed.setThumbnail( discussion._embedded.openGraph[0].imageUrl );
  2661. break;
  2662. default:
  2663. if ( discussion.jsonModel ) {
  2664. try {
  2665. description = discussion_formatting(JSON.parse(discussion.jsonModel)).replace( /(?:\*\*\*\*|(?<!\\)\_\_)/g, '' ).replace( /{@wiki}/g, wiki );
  2666. if ( discussion._embedded.contentImages.length ) {
  2667. if ( description.trim() === '{@0}' ) {
  2668. embed.setImage( discussion._embedded.contentImages[0].url );
  2669. description = '';
  2670. }
  2671. else {
  2672. description = description.replace( /\{\@(\d+)\}/g, (match, n) => {
  2673. return '[__' + lang.discussion.image.escapeFormatting() + '__](' + discussion._embedded.contentImages[n].url + ')';
  2674. } );
  2675. embed.setThumbnail( discussion._embedded.contentImages[0].url );
  2676. }
  2677. }
  2678. else embed.setThumbnail( wiki.toLink() + 'Special:FilePath/Wiki-wordmark.png' );
  2679. }
  2680. catch ( jsonerror ) {
  2681. console.log( '- Error while getting the formatting: ' + jsonerror );
  2682. description = discussion.rawContent.escapeFormatting();
  2683. }
  2684. }
  2685. else if ( discussion.renderedContent ) {
  2686. var parser = new htmlparser.Parser( {
  2687. ontext: (htmltext) => {
  2688. description += htmltext.escapeFormatting();
  2689. },
  2690. onclosetag: (tagname) => {
  2691. if ( tagname === 'p' ) description += '\n';
  2692. }
  2693. }, {decodeEntities:true} );
  2694. parser.write( discussion.renderedContent );
  2695. parser.end();
  2696. }
  2697. else {
  2698. description = discussion.rawContent.escapeFormatting();
  2699. }
  2700. }
  2701. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  2702. embed.setDescription( description );
  2703. msg.sendChannel( spoiler + text + spoiler, embed );
  2704. }
  2705. function gamepedia_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  2706. if ( args[0] ) {
  2707. var error = false;
  2708. var title = '';
  2709. var revision = 0;
  2710. var diff = 0;
  2711. var relative = 'prev';
  2712. if ( /^\d+$/.test(args[0]) ) {
  2713. revision = parseInt(args[0], 10);
  2714. if ( args[1] ) {
  2715. if ( /^\d+$/.test(args[1]) ) {
  2716. diff = parseInt(args[1], 10);
  2717. }
  2718. else if ( args[1] === 'prev' || args[1] === 'next' || args[1] === 'cur' ) {
  2719. relative = args[1];
  2720. }
  2721. else error = true;
  2722. }
  2723. }
  2724. else if ( args[0] === 'prev' || args[0] === 'next' || args[0] === 'cur' ) {
  2725. relative = args[0];
  2726. if ( args[1] ) {
  2727. if ( /^\d+$/.test(args[1]) ) {
  2728. revision = parseInt(args[1], 10);
  2729. }
  2730. else error = true;
  2731. }
  2732. else error = true;
  2733. }
  2734. else title = args.join(' ');
  2735. if ( error ) {
  2736. msg.reactEmoji('error');
  2737. if ( reaction ) reaction.removeEmoji();
  2738. }
  2739. else if ( diff ) {
  2740. gamepedia_diffsend(lang, msg, [diff, revision], wiki, reaction, spoiler);
  2741. }
  2742. else {
  2743. request( {
  2744. uri: wiki + 'api.php?action=compare&prop=ids|diff' + ( title ? '&fromtitle=' + encodeURIComponent( title ) : '&fromrev=' + revision ) + '&torelative=' + relative + '&format=json',
  2745. json: true
  2746. }, function( error, response, body ) {
  2747. if ( body && body.warnings ) log_warn(body.warnings);
  2748. if ( error || !response || response.statusCode !== 200 || !body || !body.compare ) {
  2749. var noerror = false;
  2750. if ( body && body.error ) {
  2751. switch ( body.error.code ) {
  2752. case 'nosuchrevid':
  2753. noerror = true;
  2754. break;
  2755. case 'missingtitle':
  2756. noerror = true;
  2757. break;
  2758. case 'invalidtitle':
  2759. noerror = true;
  2760. break;
  2761. case 'missingcontent':
  2762. noerror = true;
  2763. break;
  2764. default:
  2765. noerror = false;
  2766. }
  2767. }
  2768. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  2769. console.log( '- This wiki doesn\'t exist!' );
  2770. msg.reactEmoji('nowiki');
  2771. }
  2772. else if ( noerror ) {
  2773. msg.replyMsg( lang.diff.badrev );
  2774. }
  2775. else {
  2776. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  2777. msg.sendChannelError( spoiler + '<' + wiki.toLink() + title.toTitle() + '?diff=' + relative + ( title ? '' : '&oldid=' + revision ) + '>' + spoiler );
  2778. }
  2779. if ( reaction ) reaction.removeEmoji();
  2780. }
  2781. else {
  2782. if ( body.compare.fromarchive !== undefined || body.compare.toarchive !== undefined ) {
  2783. msg.reactEmoji('error');
  2784. if ( reaction ) reaction.removeEmoji();
  2785. } else {
  2786. var argids = [];
  2787. var ids = body.compare;
  2788. if ( ids.fromrevid && !ids.torevid ) argids = [ids.fromrevid];
  2789. else if ( !ids.fromrevid && ids.torevid ) argids = [ids.torevid];
  2790. else {
  2791. argids = [ids.torevid, ids.fromrevid];
  2792. var compare = ['', ''];
  2793. if ( ids.fromtexthidden === undefined && ids.totexthidden === undefined && ids['*'] !== undefined ) {
  2794. var more = '\n__' + lang.diff.info.more + '__';
  2795. var current_tag = '';
  2796. var small_prev_ins = '';
  2797. var small_prev_del = '';
  2798. var ins_length = more.length;
  2799. var del_length = more.length;
  2800. var added = false;
  2801. var parser = new htmlparser.Parser( {
  2802. onopentag: (tagname, attribs) => {
  2803. if ( tagname === 'ins' || tagname == 'del' ) {
  2804. current_tag = tagname;
  2805. }
  2806. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  2807. current_tag = tagname+'a';
  2808. }
  2809. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  2810. current_tag = tagname+"d";
  2811. }
  2812. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  2813. added = true;
  2814. }
  2815. },
  2816. ontext: (htmltext) => {
  2817. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  2818. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  2819. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  2820. else small_prev_ins += more;
  2821. }
  2822. if ( current_tag === 'del' && del_length <= 1000 ) {
  2823. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  2824. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  2825. else small_prev_del += more;
  2826. }
  2827. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  2828. ins_length += htmltext.escapeFormatting().length;
  2829. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  2830. else small_prev_ins += more;
  2831. }
  2832. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  2833. del_length += htmltext.escapeFormatting().length;
  2834. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  2835. else small_prev_del += more;
  2836. }
  2837. if ( added ) {
  2838. if ( htmltext === '+' && ins_length <= 1000 ) {
  2839. ins_length++;
  2840. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  2841. else small_prev_ins += more;
  2842. }
  2843. if ( htmltext === '−' && del_length <= 1000 ) {
  2844. del_length++;
  2845. if ( del_length <= 1000 ) small_prev_del += '\n';
  2846. else small_prev_del += more;
  2847. }
  2848. added = false;
  2849. }
  2850. },
  2851. onclosetag: (tagname) => {
  2852. if ( tagname === 'ins' ) {
  2853. current_tag = 'afterins';
  2854. } else if ( tagname === 'del' ) {
  2855. current_tag = 'afterdel';
  2856. } else {
  2857. current_tag = '';
  2858. }
  2859. }
  2860. }, {decodeEntities:true} );
  2861. parser.write( ids['*'] );
  2862. parser.end();
  2863. if ( small_prev_del.length ) {
  2864. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  2865. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  2866. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  2867. }
  2868. if ( small_prev_ins.length ) {
  2869. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  2870. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  2871. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  2872. }
  2873. }
  2874. else if ( ids.fromtexthidden !== undefined ) compare[0] = '__' + lang.diff.hidden + '__';
  2875. else if ( ids.totexthidden !== undefined ) compare[1] = '__' + lang.diff.hidden + '__';
  2876. }
  2877. gamepedia_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  2878. }
  2879. }
  2880. } );
  2881. }
  2882. }
  2883. else {
  2884. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, embed );
  2885. else msg.reactEmoji('error');
  2886. if ( reaction ) reaction.removeEmoji();
  2887. }
  2888. }
  2889. function gamepedia_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  2890. request( {
  2891. 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',
  2892. json: true
  2893. }, function( error, response, body ) {
  2894. if ( body && body.warnings ) log_warn(body.warnings);
  2895. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  2896. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  2897. console.log( '- This wiki doesn\'t exist!' );
  2898. msg.reactEmoji('nowiki');
  2899. }
  2900. else {
  2901. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  2902. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0] + '>' + spoiler );
  2903. }
  2904. if ( reaction ) reaction.removeEmoji();
  2905. }
  2906. else {
  2907. if ( body.query.badrevids ) {
  2908. msg.replyMsg( lang.diff.badrev );
  2909. if ( reaction ) reaction.removeEmoji();
  2910. }
  2911. else if ( body.query.pages && !body.query.pages['-1'] ) {
  2912. var pages = Object.values(body.query.pages);
  2913. if ( pages.length !== 1 ) {
  2914. msg.sendChannel( spoiler + '<' + wiki.toLink() + 'Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0] + '>' + spoiler );
  2915. if ( reaction ) reaction.removeEmoji();
  2916. }
  2917. else {
  2918. var title = pages[0].title;
  2919. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  2920. var diff = revisions[0].revid;
  2921. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  2922. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  2923. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  2924. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  2925. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  2926. 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 ) )];
  2927. 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(', ')];
  2928. var pagelink = wiki.toLink() + title.toTitle() + '?diff=' + diff + '&oldid=' + oldid;
  2929. if ( msg.showEmbed() ) {
  2930. var text = '<' + pagelink + '>';
  2931. var editorlink = '[' + editor[1] + '](' + wiki.toLink() + 'User:' + editor[1].toTitle(true) + ')';
  2932. if ( revisions[0].anon !== undefined ) {
  2933. editorlink = '[' + editor[1] + '](' + wiki.toLink() + 'Special:Contributions/' + editor[1].toTitle(true) + ')';
  2934. }
  2935. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  2936. 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] );
  2937. if ( tags ) {
  2938. var taglink = '';
  2939. var tagtext = '';
  2940. var tagparser = new htmlparser.Parser( {
  2941. onopentag: (tagname, attribs) => {
  2942. if ( tagname === 'a' ) taglink = attribs.href;
  2943. },
  2944. ontext: (htmltext) => {
  2945. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  2946. else tagtext += htmltext.escapeFormatting();
  2947. },
  2948. onclosetag: (tagname) => {
  2949. if ( tagname === 'a' ) taglink = '';
  2950. }
  2951. }, {decodeEntities:true} );
  2952. tagparser.write( tags[1] );
  2953. tagparser.end();
  2954. embed.addField( tags[0], tagtext );
  2955. }
  2956. var more = '\n__' + lang.diff.info.more + '__';
  2957. if ( !compare && oldid ) request( {
  2958. uri: wiki + 'api.php?action=compare&prop=diff&fromrev=' + oldid + '&torev=' + diff + '&format=json',
  2959. json: true
  2960. }, function( cperror, cpresponse, cpbody ) {
  2961. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  2962. if ( cperror || !cpresponse || cpresponse.statusCode !== 200 || !cpbody || !cpbody.compare || cpbody.compare['*'] === undefined ) {
  2963. var noerror = false;
  2964. if ( cpbody && cpbody.error ) {
  2965. switch ( cpbody.error.code ) {
  2966. case 'nosuchrevid':
  2967. noerror = true;
  2968. break;
  2969. case 'missingcontent':
  2970. noerror = true;
  2971. break;
  2972. default:
  2973. noerror = false;
  2974. }
  2975. }
  2976. if ( !noerror ) console.log( '- ' + ( cpresponse && cpresponse.statusCode ) + ': Error while getting the diff: ' + ( cperror || cpbody && cpbody.error && cpbody.error.info ) );
  2977. }
  2978. else if ( cpbody.compare.fromtexthidden === undefined && cpbody.compare.totexthidden === undefined && cpbody.compare.fromarchive === undefined && cpbody.compare.toarchive === undefined ) {
  2979. var current_tag = '';
  2980. var small_prev_ins = '';
  2981. var small_prev_del = '';
  2982. var ins_length = more.length;
  2983. var del_length = more.length;
  2984. var added = false;
  2985. var parser = new htmlparser.Parser( {
  2986. onopentag: (tagname, attribs) => {
  2987. if ( tagname === 'ins' || tagname == 'del' ) {
  2988. current_tag = tagname;
  2989. }
  2990. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  2991. current_tag = tagname+'a';
  2992. }
  2993. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  2994. current_tag = tagname+"d";
  2995. }
  2996. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  2997. added = true;
  2998. }
  2999. },
  3000. ontext: (htmltext) => {
  3001. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3002. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3003. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3004. else small_prev_ins += more;
  3005. }
  3006. if ( current_tag === 'del' && del_length <= 1000 ) {
  3007. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3008. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3009. else small_prev_del += more;
  3010. }
  3011. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3012. ins_length += htmltext.escapeFormatting().length;
  3013. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3014. else small_prev_ins += more;
  3015. }
  3016. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3017. del_length += htmltext.escapeFormatting().length;
  3018. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3019. else small_prev_del += more;
  3020. }
  3021. if ( added ) {
  3022. if ( htmltext === '+' && ins_length <= 1000 ) {
  3023. ins_length++;
  3024. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3025. else small_prev_ins += more;
  3026. }
  3027. if ( htmltext === '−' && del_length <= 1000 ) {
  3028. del_length++;
  3029. if ( del_length <= 1000 ) small_prev_del += '\n';
  3030. else small_prev_del += more;
  3031. }
  3032. added = false;
  3033. }
  3034. },
  3035. onclosetag: (tagname) => {
  3036. if ( tagname === 'ins' ) {
  3037. current_tag = 'afterins';
  3038. } else if ( tagname === 'del' ) {
  3039. current_tag = 'afterdel';
  3040. } else {
  3041. current_tag = '';
  3042. }
  3043. }
  3044. }, {decodeEntities:true} );
  3045. parser.write( cpbody.compare['*'] );
  3046. parser.end();
  3047. if ( small_prev_del.length ) {
  3048. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3049. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  3050. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  3051. }
  3052. if ( small_prev_ins.length ) {
  3053. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3054. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  3055. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3056. }
  3057. }
  3058. else if ( cpbody.compare.fromtexthidden !== undefined ) {
  3059. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  3060. }
  3061. else if ( cpbody.compare.totexthidden !== undefined ) {
  3062. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  3063. }
  3064. msg.sendChannel( spoiler + text + spoiler, embed );
  3065. if ( reaction ) reaction.removeEmoji();
  3066. } );
  3067. else {
  3068. if ( compare ) {
  3069. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  3070. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  3071. }
  3072. else if ( revisions[0]['*'] ) {
  3073. var content = revisions[0]['*'].escapeFormatting();
  3074. if ( content.trim().length ) {
  3075. if ( content.length <= 1000 ) content = '**' + content + '**';
  3076. else {
  3077. content = content.substring(0, 1000 - more.length);
  3078. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  3079. }
  3080. embed.addField( lang.diff.info.added, content, true );
  3081. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3082. }
  3083. msg.sendChannel( spoiler + text + spoiler, embed );
  3084. if ( reaction ) reaction.removeEmoji();
  3085. }
  3086. }
  3087. else {
  3088. var embed = {};
  3089. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  3090. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  3091. msg.sendChannel( spoiler + text + spoiler, embed );
  3092. if ( reaction ) reaction.removeEmoji();
  3093. }
  3094. }
  3095. }
  3096. else {
  3097. msg.reactEmoji('error');
  3098. if ( reaction ) reaction.removeEmoji();
  3099. }
  3100. }
  3101. } );
  3102. }
  3103. function fandom_diff(lang, msg, args, wiki, reaction, spoiler, embed) {
  3104. if ( args[0] ) {
  3105. var error = false;
  3106. var title = '';
  3107. var revision = 0;
  3108. var diff = 'prev';
  3109. if ( /^\d+$/.test(args[0]) ) {
  3110. revision = args[0];
  3111. if ( args[1] ) {
  3112. if ( /^\d+$/.test(args[1]) ) {
  3113. diff = args[1];
  3114. }
  3115. else if ( args[1] === 'prev' || args[1] === 'next' ) {
  3116. diff = args[1];
  3117. }
  3118. else error = true;
  3119. }
  3120. }
  3121. else if ( args[0] === 'prev' || args[0] === 'next' ) {
  3122. diff = args[0];
  3123. if ( args[1] ) {
  3124. if ( /^\d+$/.test(args[1]) ) {
  3125. revision = args[1];
  3126. }
  3127. else error = true;
  3128. }
  3129. else error = true;
  3130. }
  3131. else title = args.join(' ');
  3132. if ( error ) msg.reactEmoji('error');
  3133. else if ( /^\d+$/.test(diff) ) {
  3134. var argids = [];
  3135. if ( parseInt(revision, 10) > parseInt(diff, 10) ) argids = [revision, diff];
  3136. else if ( parseInt(revision, 10) === parseInt(diff, 10) ) argids = [revision];
  3137. else argids = [diff, revision];
  3138. fandom_diffsend(lang, msg, argids, wiki, reaction, spoiler);
  3139. }
  3140. else {
  3141. request( {
  3142. uri: wiki + 'api.php?action=query&prop=revisions&rvprop=' + ( title ? '&titles=' + encodeURIComponent( title ) : '&revids=' + revision ) + '&rvdiffto=' + diff + '&format=json',
  3143. json: true
  3144. }, function( error, response, body ) {
  3145. if ( body && body.warnings ) log_warn(body.warnings);
  3146. if ( error || !response || response.statusCode !== 200 || !body || !body.query ) {
  3147. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  3148. console.log( '- This wiki doesn\'t exist!' );
  3149. msg.reactEmoji('nowiki');
  3150. }
  3151. else {
  3152. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  3153. msg.sendChannelError( spoiler + '<' + wiki.toLink() + title.toTitle() + '?diff=' + diff + ( title ? '' : '&oldid=' + revision ) + '>' + spoiler );
  3154. }
  3155. if ( reaction ) reaction.removeEmoji();
  3156. }
  3157. else {
  3158. if ( body.query.badrevids ) {
  3159. msg.replyMsg( lang.diff.badrev );
  3160. if ( reaction ) reaction.removeEmoji();
  3161. } else if ( body.query.pages && !body.query.pages[-1] ) {
  3162. var revisions = Object.values(body.query.pages)[0].revisions[0];
  3163. if ( revisions.texthidden === undefined ) {
  3164. var argids = [];
  3165. var ids = revisions.diff;
  3166. if ( !ids.from ) argids = [ids.to];
  3167. else {
  3168. argids = [ids.to, ids.from];
  3169. var compare = ['', ''];
  3170. if ( ids['*'] !== undefined ) {
  3171. var more = '\n__' + lang.diff.info.more + '__';
  3172. var current_tag = '';
  3173. var small_prev_ins = '';
  3174. var small_prev_del = '';
  3175. var ins_length = more.length;
  3176. var del_length = more.length;
  3177. var added = false;
  3178. var parser = new htmlparser.Parser( {
  3179. onopentag: (tagname, attribs) => {
  3180. if ( tagname === 'ins' || tagname == 'del' ) {
  3181. current_tag = tagname;
  3182. }
  3183. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3184. current_tag = tagname+'a';
  3185. }
  3186. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3187. current_tag = tagname+"d";
  3188. }
  3189. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3190. added = true;
  3191. }
  3192. },
  3193. ontext: (htmltext) => {
  3194. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3195. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3196. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3197. else small_prev_ins += more;
  3198. }
  3199. if ( current_tag === 'del' && del_length <= 1000 ) {
  3200. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3201. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3202. else small_prev_del += more;
  3203. }
  3204. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3205. ins_length += htmltext.escapeFormatting().length;
  3206. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3207. else small_prev_ins += more;
  3208. }
  3209. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3210. del_length += htmltext.escapeFormatting().length;
  3211. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3212. else small_prev_del += more;
  3213. }
  3214. if ( added ) {
  3215. if ( htmltext === '+' && ins_length <= 1000 ) {
  3216. ins_length++;
  3217. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3218. else small_prev_ins += more;
  3219. }
  3220. if ( htmltext === '−' && del_length <= 1000 ) {
  3221. del_length++;
  3222. if ( del_length <= 1000 ) small_prev_del += '\n';
  3223. else small_prev_del += more;
  3224. }
  3225. added = false;
  3226. }
  3227. },
  3228. onclosetag: (tagname) => {
  3229. if ( tagname === 'ins' ) {
  3230. current_tag = 'afterins';
  3231. } else if ( tagname === 'del' ) {
  3232. current_tag = 'afterdel';
  3233. } else {
  3234. current_tag = '';
  3235. }
  3236. }
  3237. }, {decodeEntities:true} );
  3238. parser.write( ids['*'] );
  3239. parser.end();
  3240. if ( small_prev_del.length ) {
  3241. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3242. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  3243. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  3244. }
  3245. if ( small_prev_ins.length ) {
  3246. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3247. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  3248. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  3249. }
  3250. }
  3251. }
  3252. fandom_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  3253. } else {
  3254. msg.replyMsg( lang.diff.badrev );
  3255. if ( reaction ) reaction.removeEmoji();
  3256. }
  3257. } else {
  3258. if ( body.query.pages && body.query.pages[-1] ) msg.replyMsg( lang.diff.badrev );
  3259. else msg.reactEmoji('error');
  3260. if ( reaction ) reaction.removeEmoji();
  3261. }
  3262. }
  3263. } );
  3264. }
  3265. }
  3266. else {
  3267. if ( embed ) msg.sendChannel( spoiler + '<' + embed.url + '>' + spoiler, embed );
  3268. else msg.reactEmoji('error');
  3269. if ( reaction ) reaction.removeEmoji();
  3270. }
  3271. }
  3272. function fandom_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  3273. request( {
  3274. 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',
  3275. json: true
  3276. }, function( error, response, body ) {
  3277. if ( body && body.warnings ) log_warn(body.warnings);
  3278. if ( error || !response || response.statusCode !== 200 || !body || !body.query ) {
  3279. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  3280. console.log( '- This wiki doesn\'t exist!' );
  3281. msg.reactEmoji('nowiki');
  3282. }
  3283. else {
  3284. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  3285. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0] + '>' + spoiler );
  3286. }
  3287. if ( reaction ) reaction.removeEmoji();
  3288. }
  3289. else {
  3290. if ( body.query.badrevids ) {
  3291. msg.replyMsg( lang.diff.badrev );
  3292. if ( reaction ) reaction.removeEmoji();
  3293. }
  3294. else if ( body.query.pages && !body.query.pages['-1'] ) {
  3295. var pages = Object.values(body.query.pages);
  3296. if ( pages.length !== 1 ) {
  3297. msg.sendChannel( spoiler + '<' + wiki.toLink() + 'Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0] + '>' + spoiler );
  3298. if ( reaction ) reaction.removeEmoji();
  3299. }
  3300. else {
  3301. var title = pages[0].title;
  3302. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  3303. var diff = revisions[0].revid;
  3304. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  3305. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  3306. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.dateformat, timeoptions)];
  3307. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  3308. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  3309. 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 ) )];
  3310. 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(', ')];
  3311. var pagelink = wiki.toLink() + title.toTitle() + '?diff=' + diff + '&oldid=' + oldid;
  3312. if ( msg.showEmbed() ) {
  3313. var text = '<' + pagelink + '>';
  3314. var editorlink = '[' + editor[1] + '](' + wiki.toLink() + 'User:' + editor[1].toTitle(true) + ')';
  3315. if ( revisions[0].anon !== undefined ) {
  3316. editorlink = '[' + editor[1] + '](' + wiki.toLink() + 'Special:Contributions/' + editor[1].toTitle(true) + ')';
  3317. }
  3318. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  3319. 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] );
  3320. if ( tags ) {
  3321. var taglink = '';
  3322. var tagtext = '';
  3323. var tagparser = new htmlparser.Parser( {
  3324. onopentag: (tagname, attribs) => {
  3325. if ( tagname === 'a' ) taglink = attribs.href;
  3326. },
  3327. ontext: (htmltext) => {
  3328. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  3329. else tagtext += htmltext.escapeFormatting();
  3330. },
  3331. onclosetag: (tagname) => {
  3332. if ( tagname === 'a' ) taglink = '';
  3333. }
  3334. }, {decodeEntities:true} );
  3335. tagparser.write( tags[1] );
  3336. tagparser.end();
  3337. embed.addField( tags[0], tagtext );
  3338. }
  3339. var more = '\n__' + lang.diff.info.more + '__';
  3340. if ( !compare && oldid ) request( {
  3341. uri: wiki + 'api.php?action=query&prop=revisions&rvprop=&revids=' + oldid + '&rvdiffto=' + diff + '&format=json',
  3342. json: true
  3343. }, function( cperror, cpresponse, cpbody ) {
  3344. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  3345. if ( cperror || !cpresponse || cpresponse.statusCode !== 200 || !cpbody || !cpbody.query || cpbody.query.badrevids || !cpbody.query.pages && cpbody.query.pages[-1] ) {
  3346. console.log( '- ' + ( cpresponse && cpresponse.statusCode ) + ': Error while getting the diff: ' + ( cperror || cpbody && cpbody.error && cpbody.error.info ) );
  3347. }
  3348. else {
  3349. var revision = Object.values(cpbody.query.pages)[0].revisions[0];
  3350. if ( revision.texthidden === undefined && revision.diff && revision.diff['*'] !== undefined ) {
  3351. var current_tag = '';
  3352. var small_prev_ins = '';
  3353. var small_prev_del = '';
  3354. var ins_length = more.length;
  3355. var del_length = more.length;
  3356. var added = false;
  3357. var parser = new htmlparser.Parser( {
  3358. onopentag: (tagname, attribs) => {
  3359. if ( tagname === 'ins' || tagname == 'del' ) {
  3360. current_tag = tagname;
  3361. }
  3362. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  3363. current_tag = tagname+'a';
  3364. }
  3365. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  3366. current_tag = tagname+"d";
  3367. }
  3368. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  3369. added = true;
  3370. }
  3371. },
  3372. ontext: (htmltext) => {
  3373. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  3374. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  3375. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  3376. else small_prev_ins += more;
  3377. }
  3378. if ( current_tag === 'del' && del_length <= 1000 ) {
  3379. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  3380. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  3381. else small_prev_del += more;
  3382. }
  3383. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  3384. ins_length += htmltext.escapeFormatting().length;
  3385. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  3386. else small_prev_ins += more;
  3387. }
  3388. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  3389. del_length += htmltext.escapeFormatting().length;
  3390. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  3391. else small_prev_del += more;
  3392. }
  3393. if ( added ) {
  3394. if ( htmltext === '+' && ins_length <= 1000 ) {
  3395. ins_length++;
  3396. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  3397. else small_prev_ins += more;
  3398. }
  3399. if ( htmltext === '−' && del_length <= 1000 ) {
  3400. del_length++;
  3401. if ( del_length <= 1000 ) small_prev_del += '\n';
  3402. else small_prev_del += more;
  3403. }
  3404. added = false;
  3405. }
  3406. },
  3407. onclosetag: (tagname) => {
  3408. if ( tagname === 'ins' ) {
  3409. current_tag = 'afterins';
  3410. } else if ( tagname === 'del' ) {
  3411. current_tag = 'afterdel';
  3412. } else {
  3413. current_tag = '';
  3414. }
  3415. }
  3416. }, {decodeEntities:true} );
  3417. parser.write( revision.diff['*'] );
  3418. parser.end();
  3419. if ( small_prev_del.length ) {
  3420. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  3421. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  3422. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  3423. }
  3424. if ( small_prev_ins.length ) {
  3425. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  3426. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  3427. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3428. }
  3429. }
  3430. else if ( revision.texthidden !== undefined ) {
  3431. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  3432. }
  3433. else if ( revision.diff && revision.diff['*'] === undefined ) {
  3434. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  3435. }
  3436. }
  3437. msg.sendChannel( spoiler + text + spoiler, embed );
  3438. if ( reaction ) reaction.removeEmoji();
  3439. } );
  3440. else {
  3441. if ( compare ) {
  3442. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  3443. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  3444. }
  3445. else if ( revisions[0]['*'] ) {
  3446. var content = revisions[0]['*'].escapeFormatting();
  3447. if ( content.trim().length ) {
  3448. if ( content.length <= 1000 ) content = '**' + content + '**';
  3449. else {
  3450. content = content.substring(0, 1000 - more.length);
  3451. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  3452. }
  3453. embed.addField( lang.diff.info.added, content, true );
  3454. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  3455. }
  3456. msg.sendChannel( spoiler + text + spoiler, embed );
  3457. if ( reaction ) reaction.removeEmoji();
  3458. }
  3459. }
  3460. else {
  3461. var embed = {};
  3462. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  3463. if ( tags ) text += htmlToPlain( '\n' + tags.join(' ') );
  3464. msg.sendChannel( spoiler + text + spoiler, embed );
  3465. if ( reaction ) reaction.removeEmoji();
  3466. }
  3467. }
  3468. }
  3469. else {
  3470. msg.reactEmoji('error');
  3471. if ( reaction ) reaction.removeEmoji();
  3472. }
  3473. }
  3474. if ( reaction ) reaction.removeEmoji();
  3475. } );
  3476. }
  3477. function gamepedia_random(lang, msg, wiki, reaction, spoiler) {
  3478. request( {
  3479. 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',
  3480. json: true
  3481. }, function( error, response, body ) {
  3482. if ( body && body.warnings ) log_warn(body.warnings);
  3483. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  3484. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  3485. console.log( '- This wiki doesn\'t exist!' );
  3486. msg.reactEmoji('nowiki');
  3487. }
  3488. else {
  3489. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  3490. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Random>' + spoiler );
  3491. }
  3492. }
  3493. else {
  3494. var querypage = Object.values(body.query.pages)[0];
  3495. var pagelink = wiki.toLink() + querypage.title.toTitle();
  3496. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  3497. if ( querypage.pageprops && querypage.pageprops.displaytitle ) {
  3498. var displaytitle = htmlToDiscord( querypage.pageprops.displaytitle );
  3499. if ( displaytitle.length > 250 ) displaytitle = displaytitle.substring(0, 250) + '\u2026';
  3500. embed.setTitle( displaytitle );
  3501. }
  3502. if ( querypage.pageprops && querypage.pageprops.description ) {
  3503. var description = htmlToPlain( querypage.pageprops.description );
  3504. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  3505. embed.setDescription( description );
  3506. }
  3507. else if ( querypage.extract ) {
  3508. var extract = querypage.extract.escapeFormatting();
  3509. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  3510. embed.setDescription( extract );
  3511. }
  3512. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  3513. embed.setThumbnail( querypage.original.source );
  3514. }
  3515. else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  3516. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, embed );
  3517. }
  3518. if ( reaction ) reaction.removeEmoji();
  3519. } );
  3520. }
  3521. function fandom_random(lang, msg, wiki, reaction, spoiler) {
  3522. request( {
  3523. uri: wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=description&siprop=general&generator=random&grnnamespace=0&format=json',
  3524. json: true
  3525. }, function( error, response, body ) {
  3526. if ( body && body.warnings ) log_warn(body.warnings);
  3527. if ( error || !response || response.statusCode !== 200 || !body || !body.query || !body.query.pages ) {
  3528. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  3529. console.log( '- This wiki doesn\'t exist!' );
  3530. msg.reactEmoji('nowiki');
  3531. }
  3532. else {
  3533. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  3534. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Random>' + spoiler );
  3535. }
  3536. if ( reaction ) reaction.removeEmoji();
  3537. }
  3538. else {
  3539. var querypage = Object.values(body.query.pages)[0];
  3540. var pagelink = wiki.toLink() + querypage.title.toTitle();
  3541. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  3542. if ( querypage.title === body.query.general.mainpage && body.query.allmessages[0]['*'] ) {
  3543. embed.setDescription( body.query.allmessages[0]['*'] );
  3544. embed.setThumbnail( wiki.toLink() + 'Special:FilePath/Wiki-wordmark.png' );
  3545. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  3546. if ( reaction ) reaction.removeEmoji();
  3547. }
  3548. else request( {
  3549. uri: wiki.toLink() + encodeURIComponent( querypage.title.replace( / /g, '_' ) )
  3550. }, function( descerror, descresponse, descbody ) {
  3551. if ( descerror || !descresponse || descresponse.statusCode !== 200 || !descbody ) {
  3552. console.log( '- ' + ( descresponse && descresponse.statusCode ) + ': Error while getting the description: ' + descerror );
  3553. } else {
  3554. var thumbnail = wiki.toLink() + 'Special:FilePath/Wiki-wordmark.png';
  3555. var parser = new htmlparser.Parser( {
  3556. onopentag: (tagname, attribs) => {
  3557. if ( tagname === 'meta' && attribs.property === 'og:description' ) {
  3558. var description = attribs.content.escapeFormatting();
  3559. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  3560. embed.setDescription( description );
  3561. }
  3562. if ( tagname === 'meta' && attribs.property === 'og:image' && querypage.title !== body.query.general.mainpage ) {
  3563. thumbnail = attribs.content;
  3564. }
  3565. }
  3566. }, {decodeEntities:true} );
  3567. parser.write( descbody );
  3568. parser.end();
  3569. embed.setThumbnail( thumbnail );
  3570. }
  3571. msg.sendChannel( '🎲 ' + spoiler + '<' + pagelink + '>' + spoiler, embed );
  3572. if ( reaction ) reaction.removeEmoji();
  3573. } );
  3574. }
  3575. } );
  3576. }
  3577. function gamepedia_overview(lang, msg, wiki, reaction, spoiler) {
  3578. request( {
  3579. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general|statistics&titles=Special:Statistics&format=json',
  3580. json: true
  3581. }, function( error, response, body ) {
  3582. if ( body && body.warnings ) log_warn(body.warnings);
  3583. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  3584. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  3585. console.log( '- This wiki doesn\'t exist!' );
  3586. msg.reactEmoji('nowiki');
  3587. }
  3588. else {
  3589. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  3590. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Statistics>' + spoiler );
  3591. }
  3592. }
  3593. else {
  3594. var site = false;
  3595. if ( allSites.some( site => site.wiki_domain === body.query.general.servername ) ) {
  3596. site = allSites.find( site => site.wiki_domain === body.query.general.servername );
  3597. var name = [lang.overview.name, site.wiki_display_name];
  3598. var created = [lang.overview.created, new Date(parseInt(site.created + '000', 10)).toLocaleString(lang.dateformat, timeoptions)];
  3599. var manager = [lang.overview.manager, site.wiki_managers];
  3600. var official = [lang.overview.official, ( site.official_wiki ? lang.overview.yes : lang.overview.no )];
  3601. var crossover = [lang.overview.crossover, ( site.wiki_crossover ? 'https://' + site.wiki_crossover + '/' : '' )];
  3602. var description = [lang.overview.description, site.wiki_description];
  3603. var image = [lang.overview.image, site.wiki_image];
  3604. if ( description[1] ) {
  3605. description[1] = description[1].escapeFormatting();
  3606. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  3607. }
  3608. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  3609. }
  3610. var articles = [lang.overview.articles, body.query.statistics.articles];
  3611. var pages = [lang.overview.pages, body.query.statistics.pages];
  3612. var edits = [lang.overview.edits, body.query.statistics.edits];
  3613. var users = [lang.overview.users, body.query.statistics.activeusers];
  3614. var title = body.query.pages['-1'].title;
  3615. var pagelink = wiki.toLink() + title.toTitle();
  3616. if ( msg.showEmbed() ) {
  3617. var text = '<' + pagelink + '>';
  3618. 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 );
  3619. if ( site ) {
  3620. 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');
  3621. 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 );
  3622. }
  3623. 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 );
  3624. if ( site ) {
  3625. if ( crossover[1] ) embed.addField( crossover[0], crossover[1], true );
  3626. if ( description[1] ) embed.addField( description[0], description[1] );
  3627. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  3628. }
  3629. }
  3630. else {
  3631. var embed = {};
  3632. var text = '<' + pagelink + '>\n\n';
  3633. if ( site ) text += name.join(' ') + '\n' + created.join(' ') + '\n' + manager[0] + ' ' + ( manager[1].join(', ') || lang.overview.none ) + '\n' + official.join(' ') + '\n';
  3634. text += articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  3635. if ( site ) {
  3636. if ( crossover[1] ) text += '\n' + crossover.join(' ');
  3637. if ( description[1] ) text += '\n' + description.join(' ');
  3638. if ( image[1] ) {
  3639. text += '\n' + image.join(' ');
  3640. if ( msg.uploadFiles() ) embed.files = [{attachment:image[1],name:( spoiler ? 'SPOILER ' : '' ) + name[1] + image[1].substring(image[1].lastIndexOf('.'))}];
  3641. }
  3642. }
  3643. text += '\n\n*' + lang.overview.inaccurate + '*';
  3644. }
  3645. msg.sendChannel( spoiler + text + spoiler, embed );
  3646. }
  3647. if ( reaction ) reaction.removeEmoji();
  3648. } );
  3649. }
  3650. function fandom_overview(lang, msg, wiki, reaction, spoiler) {
  3651. request( {
  3652. uri: wiki + 'api.php?action=query&meta=allmessages|siteinfo&ammessages=custom-Wiki_Manager&amenableparser=true&siprop=general|statistics|wikidesc&titles=Special:Statistics&format=json',
  3653. json: true
  3654. }, function( error, response, body ) {
  3655. if ( body && body.query && body.query.general && body.general.generator === 'MediaWiki 1.33.2' ) return msg.sendChannelError( '**Sorry, but I don\'t support wikis on UCP yet!**' );
  3656. if ( body && body.warnings ) log_warn(body.warnings);
  3657. if ( error || !response || response.statusCode !== 200 || !body || !body.query || !body.query.pages ) {
  3658. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  3659. console.log( '- This wiki doesn\'t exist!' );
  3660. msg.reactEmoji('nowiki');
  3661. }
  3662. else {
  3663. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  3664. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Statistics>' + spoiler );
  3665. }
  3666. if ( reaction ) reaction.removeEmoji();
  3667. }
  3668. else request( {
  3669. uri: 'https://community.fandom.com/api/v1/Wikis/Details?ids=' + body.query.wikidesc.id + '&format=json',
  3670. json: true
  3671. }, function( overror, ovresponse, ovbody ) {
  3672. if ( overror || !ovresponse || ovresponse.statusCode !== 200 || !ovbody || ovbody.exception || !ovbody.items || !ovbody.items[body.query.wikidesc.id] ) {
  3673. console.log( '- ' + ( ovresponse && ovresponse.statusCode ) + ': Error while getting the wiki details: ' + ( overror || ovbody && ovbody.exception && ovbody.exception.details ) );
  3674. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Statistics>' + spoiler );
  3675. if ( reaction ) reaction.removeEmoji();
  3676. }
  3677. else {
  3678. var site = ovbody.items[body.query.wikidesc.id];
  3679. var vertical = [lang.overview.vertical, site.hub];
  3680. var topic = [lang.overview.topic, site.topic];
  3681. var founder = [lang.overview.founder, site.founding_user_id];
  3682. var manager = [lang.overview.manager, body.query.allmessages[0]['*']];
  3683. var created = [lang.overview.created, new Date(site.creation_date).toLocaleString(lang.dateformat, timeoptions)];
  3684. var articles = [lang.overview.articles, body.query.statistics.articles];
  3685. var pages = [lang.overview.pages, body.query.statistics.pages];
  3686. var edits = [lang.overview.edits, body.query.statistics.edits];
  3687. var users = [lang.overview.users, body.query.statistics.activeusers];
  3688. var description = [lang.overview.description, site.desc];
  3689. var image = [lang.overview.image, site.image];
  3690. if ( description[1] ) {
  3691. description[1] = description[1].escapeFormatting();
  3692. if ( description[1].length > 1000 ) description[1] = description[1].substring(0, 1000) + '\u2026';
  3693. }
  3694. if ( image[1] && image[1].startsWith( '/' ) ) image[1] = wiki.substring(0, wiki.length - 1) + image[1];
  3695. var title = body.query.pages['-1'].title;
  3696. var pagelink = wiki.toLink() + title.toTitle();
  3697. if ( msg.showEmbed() ) {
  3698. var text = '<' + pagelink + '>';
  3699. 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 );
  3700. }
  3701. else {
  3702. var embed = {};
  3703. var text = '<' + pagelink + '>\n\n' + vertical.join(' ') + '\n' + topic.join(' ');
  3704. }
  3705. if ( founder[1] > 0 ) request( {
  3706. uri: wiki + 'api.php?action=query&list=users&usprop=&usids=' + founder[1] + '&format=json',
  3707. json: true
  3708. }, function( userror, usresponse, usbody ) {
  3709. if ( usbody && usbody.warnings ) log_warn(usbody.warnings);
  3710. if ( userror || !usresponse || usresponse.statusCode !== 200 || !usbody || !usbody.query || !usbody.query.users || !usbody.query.users[0] ) {
  3711. console.log( '- ' + ( usresponse && usresponse.statusCode ) + ': Error while getting the wiki founder: ' + ( userror || usbody && usbody.error && usbody.error.info ) );
  3712. founder[1] = 'ID: ' + founder[1];
  3713. }
  3714. else {
  3715. var user = usbody.query.users[0].name;
  3716. if ( msg.showEmbed() ) founder[1] = '[' + user + '](' + wiki.toLink() + 'User:' + user.toTitle(true) + ')';
  3717. else founder[1] = user;
  3718. }
  3719. if ( msg.showEmbed() ) {
  3720. embed.addField( founder[0], founder[1], true );
  3721. 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 );
  3722. 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 );
  3723. if ( description[1] ) embed.addField( description[0], description[1] );
  3724. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  3725. }
  3726. else {
  3727. text += '\n' + founder.join(' ') + ( manager[1] ? '\n' + manager.join(' ') : '' ) + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  3728. if ( description[1] ) text += '\n' + description.join(' ');
  3729. if ( image[1] ) {
  3730. text += '\n' + image.join(' ');
  3731. if ( msg.uploadFiles() ) embed.files = [image[1]];
  3732. }
  3733. text += '\n\n*' + lang.overview.inaccurate + '*';
  3734. }
  3735. msg.sendChannel( spoiler + text + spoiler, embed );
  3736. if ( reaction ) reaction.removeEmoji();
  3737. } );
  3738. else {
  3739. founder[1] = lang.overview.none;
  3740. if ( msg.showEmbed() ) {
  3741. 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 );
  3742. if ( description[1] ) embed.addField( description[0], description[1] );
  3743. if ( image[1] ) embed.addField( image[0], image[1] ).setImage( image[1] );
  3744. }
  3745. else {
  3746. text += '\n' + founder.join(' ') + '\n' + created.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ');
  3747. if ( description[1] ) text += '\n' + description.join(' ');
  3748. if ( image[1] ) {
  3749. text += '\n' + image.join(' ');
  3750. if ( msg.uploadFiles() ) embed.files = [image[1]];
  3751. }
  3752. text += '\n\n*' + lang.overview.inaccurate + '*';
  3753. }
  3754. msg.sendChannel( spoiler + text + spoiler, embed );
  3755. if ( reaction ) reaction.removeEmoji();
  3756. }
  3757. }
  3758. } );
  3759. } );
  3760. }
  3761. function minecraft_bug(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  3762. var invoke = args[0];
  3763. args = args.slice(1);
  3764. if ( invoke && /\d+$/.test(invoke) && !args.length ) {
  3765. var project = '';
  3766. if ( /^\d+$/.test(invoke) ) project = 'MC-';
  3767. request( {
  3768. uri: 'https://bugs.mojang.com/rest/api/2/issue/' + encodeURIComponent( project + invoke ) + '?fields=summary,issuelinks,fixVersions,resolution,status',
  3769. json: true
  3770. }, function( error, response, body ) {
  3771. var link = 'https://bugs.mojang.com/browse/';
  3772. if ( error || !response || response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  3773. if ( body && body.errorMessages ) {
  3774. if ( body.errorMessages.includes( 'Issue Does Not Exist' ) ) {
  3775. msg.reactEmoji('🤷');
  3776. }
  3777. else if ( body.errorMessages.includes( 'You do not have the permission to see the specified issue.' ) ) {
  3778. msg.sendChannel( spoiler + mclang.bug.private + '\n<' + link + project + invoke + '>' + spoiler );
  3779. }
  3780. else {
  3781. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + body.errorMessages.join(' - ') );
  3782. msg.reactEmoji('error');
  3783. }
  3784. }
  3785. else {
  3786. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + ( error || body && body.message ) );
  3787. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  3788. else msg.sendChannelError( spoiler + '<' + link + project + invoke + '>' + spoiler );
  3789. }
  3790. }
  3791. else {
  3792. if ( !body.fields ) {
  3793. msg.reactEmoji('error');
  3794. }
  3795. else {
  3796. var bugs = body.fields.issuelinks.filter( bug => bug.outwardIssue || ( bug.inwardIssue && bug.type.name != 'Duplicate' ) );
  3797. if ( bugs.length ) {
  3798. var embed = new Discord.RichEmbed();
  3799. var extrabugs = [];
  3800. bugs.forEach( bug => {
  3801. var ward = ( bug.outwardIssue ? 'outward' : 'inward' );
  3802. var issue = bug[ward + 'Issue'];
  3803. var name = bug.type[ward] + ' ' + issue.key;
  3804. var value = issue.fields.status.name + ': [' + issue.fields.summary.escapeFormatting() + '](' + link + issue.key + ')';
  3805. if ( embed.fields.length < 25 ) embed.addField( name, value );
  3806. else extrabugs.push({name,value,inline:false});
  3807. } );
  3808. if ( extrabugs.length ) embed.setFooter( mclang.bug.more.replaceSave( '%s', extrabugs.length ) );
  3809. }
  3810. var status = '**' + ( body.fields.resolution ? body.fields.resolution.name : body.fields.status.name ) + ':** ';
  3811. var fixed = '';
  3812. if ( body.fields.resolution && body.fields.fixVersions && body.fields.fixVersions.length ) {
  3813. fixed = '\n' + mclang.bug.fixed + ' ' + body.fields.fixVersions.map( v => v.name ).join(', ');
  3814. }
  3815. msg.sendChannel( spoiler + status + body.fields.summary.escapeFormatting() + '\n<' + link + body.key + '>' + fixed + spoiler, embed );
  3816. }
  3817. }
  3818. if ( reaction ) reaction.removeEmoji();
  3819. } );
  3820. }
  3821. else if ( invoke && invoke.toLowerCase() === 'version' && args.length && args.join(' ').length < 100 ) {
  3822. var jql = 'fixVersion="' + args.join(' ').replace( /(["\\])/g, '\\$1' ).toSearch() + '"+order+by+key';
  3823. request( {
  3824. uri: 'https://bugs.mojang.com/rest/api/2/search?fields=summary,resolution,status&jql=' + jql + '&maxResults=25',
  3825. json: true
  3826. }, function( error, response, body ) {
  3827. var link = 'https://bugs.mojang.com/issues/?jql=' + jql;
  3828. if ( error || !response || response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  3829. if ( body && body.errorMessages ) {
  3830. if ( body.errorMessages.includes( 'The value \'' + args.join(' ') + '\' does not exist for the field \'fixVersion\'.' ) ) {
  3831. msg.reactEmoji('🤷');
  3832. }
  3833. else {
  3834. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issues: ' + body.errorMessages.join(' - ') );
  3835. msg.reactEmoji('error');
  3836. }
  3837. }
  3838. else {
  3839. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issues: ' + ( error || body && body.message ) );
  3840. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  3841. else msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  3842. }
  3843. }
  3844. else {
  3845. if ( !body.issues ) {
  3846. msg.reactEmoji('error');
  3847. }
  3848. else {
  3849. if ( body.total > 0 ) {
  3850. var embed = new Discord.RichEmbed();
  3851. body.issues.forEach( bug => {
  3852. var status = ( bug.fields.resolution ? bug.fields.resolution.name : bug.fields.status.name );
  3853. var value = status + ': [' + bug.fields.summary.escapeFormatting() + '](https://bugs.mojang.com/browse/' + bug.key + ')';
  3854. embed.addField( bug.key, value );
  3855. } );
  3856. if ( body.total > 25 ) embed.setFooter( mclang.bug.more.replaceSave( '%s', body.total - 25 ) );
  3857. }
  3858. var total = '**' + args.join(' ') + ':** ' + mclang.bug.total.replaceSave( '%s', body.total );
  3859. msg.sendChannel( spoiler + total + '\n<' + link + '>' + spoiler, embed );
  3860. }
  3861. }
  3862. if ( reaction ) reaction.removeEmoji();
  3863. } );
  3864. }
  3865. else {
  3866. msg.notminecraft = true;
  3867. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  3868. }
  3869. }
  3870. function minecraft_command(lang, mclang, msg, befehl, args, title, cmd, querystring, fragment, reaction, spoiler) {
  3871. befehl = befehl.toLowerCase();
  3872. var aliasCmd = ( minecraft.cmd.aliase[befehl] || befehl );
  3873. if ( aliasCmd in minecraft.cmd.list ) {
  3874. var cmdSyntaxMap = minecraft.cmd.list[aliasCmd].map( command => {
  3875. var cmdargs = command.split(' ');
  3876. if ( cmdargs[0].startsWith( '/' ) ) cmdargs = cmdargs.slice(1);
  3877. var argmatches = cmdargs.map( (arg, i) => {
  3878. if ( arg === args[i] ) return true;
  3879. } );
  3880. var matchCount = 0;
  3881. argmatches.forEach( match => {
  3882. if ( match ) matchCount++;
  3883. } );
  3884. return [argmatches.lastIndexOf(true),matchCount];
  3885. } );
  3886. var lastIndex = Math.max(...cmdSyntaxMap.map( command => command[0] ));
  3887. var matchCount = Math.max(...cmdSyntaxMap.filter( command => command[0] === lastIndex ).map( command => command[1] ));
  3888. var regex = new RegExp('/' + aliasCmd, 'g');
  3889. var cmdSyntax = minecraft.cmd.list[aliasCmd].filter( (command, i) => ( lastIndex === -1 || cmdSyntaxMap[i][0] === lastIndex ) && cmdSyntaxMap[i][1] === matchCount ).join('\n').replaceSave( regex, '/' + befehl );
  3890. msg.sendChannel( spoiler + '```md\n' + cmdSyntax + '```<' + mclang.link + mclang.cmd.page + aliasCmd + '>' + spoiler, {split:{maxLength:2000,prepend:spoiler + '```md\n',append:'```' + spoiler}} );
  3891. if ( reaction ) reaction.removeEmoji();
  3892. }
  3893. else {
  3894. msg.reactEmoji('❓');
  3895. msg.notminecraft = true;
  3896. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  3897. }
  3898. }
  3899. function minecraft_command2(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  3900. if ( args.join('') ) {
  3901. if ( args[0].startsWith( '/' ) ) minecraft_command(lang, mclang, msg, args[0].substring(1), args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  3902. else minecraft_command(lang, mclang, msg, args[0], args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  3903. }
  3904. else {
  3905. msg.notminecraft = true;
  3906. gamepedia_check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  3907. }
  3908. }
  3909. function cmd_multiline(lang, msg, args, line, wiki) {
  3910. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  3911. if ( msg.isAdmin() ) msg.reactEmoji('error', true);
  3912. else msg.reactEmoji('❌');
  3913. }
  3914. }
  3915. function cmd_get(lang, msg, args, line, wiki) {
  3916. var id = args.join().replace( /^\\?<(?:@!?|#)(\d+)>$/, '$1' );
  3917. if ( /^\d+$/.test(id) ) {
  3918. if ( client.guilds.has(id) ) {
  3919. var guild = client.guilds.get(id);
  3920. var guildname = ['Guild:', guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( pause[guild.id] ? '\\*' : '' )];
  3921. var guildowner = ['Owner:', guild.owner.user.tag.escapeFormatting() + ' `' + guild.ownerID + '` ' + guild.owner.toString()];
  3922. var guildsize = ['Size:', guild.memberCount + ' members (' + guild.members.filter( member => member.user.bot ).size + ' bots)'];
  3923. var guildpermissions = ['Missing permissions:', ( guild.me.permissions.has(defaultPermissions) ? '*none*' : '`' + guild.me.permissions.missing(defaultPermissions).join('`, `') + '`' )];
  3924. var guildsettings = ['Settings:', '*unknown*'];
  3925. db.all( 'SELECT channel, prefix, lang, wiki, inline FROM discord WHERE guild = ? ORDER BY channel ASC', [guild.id], (dberror, rows) => {
  3926. if ( dberror ) {
  3927. console.log( '- Error while getting the settings: ' + dberror );
  3928. }
  3929. else if ( rows.length ) {
  3930. row = rows.find( row => !row.channel );
  3931. row.patreon = guild.id in patreons;
  3932. row.voice = guild.id in voice;
  3933. guildsettings[1] = '```json\n' + JSON.stringify( rows, null, '\t' ) + '\n```';
  3934. }
  3935. else guildsettings[1] = '*default*';
  3936. if ( msg.showEmbed() ) {
  3937. 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] );
  3938. var split = Discord.Util.splitMessage( guildsettings[1], {char:',\n',maxLength:1000,prepend:'```json\n',append:',\n```'} );
  3939. if ( split.length < guildsettings[1].length ) {
  3940. if ( split.length > 5 ) {
  3941. msg.sendChannel( '', embed, true );
  3942. msg.sendChannel( guildsettings.join(' '), {split:{char:',\n',prepend:'```json\n',append:',\n```'}}, true );
  3943. return;
  3944. }
  3945. split.forEach( guildsettingspart => embed.addField( guildsettings[0], guildsettingspart ) );
  3946. }
  3947. else embed.addField( guildsettings[0], split );
  3948. msg.sendChannel( '', embed, true );
  3949. }
  3950. else {
  3951. var text = guildname.join(' ') + '\n' + guildowner.join(' ') + '\n' + guildsize.join(' ') + '\n' + guildpermissions.join(' ') + '\n' + guildsettings.join(' ');
  3952. msg.sendChannel( text, {split:{char:',\n',prepend:'```json\n',append:',\n```'}}, true );
  3953. }
  3954. } );
  3955. } else if ( client.guilds.some( guild => guild.members.has(id) ) ) {
  3956. var username = [];
  3957. var guildlist = ['Guilds:'];
  3958. var guilds = client.guilds.filter( guild => guild.members.has(id) );
  3959. guildlist.push('\n' + guilds.map( function(guild) {
  3960. var member = guild.members.get(id);
  3961. if ( !username.length ) username.push('User:', member.user.tag.escapeFormatting() + ' `' + member.id + '` ' + member.toString());
  3962. return guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( member.permissions.has('MANAGE_GUILD') ? '\\*' : '' );
  3963. } ).join('\n'));
  3964. if ( guildlist[1].length > 1000 ) guildlist[1] = guilds.size;
  3965. if ( msg.showEmbed() ) {
  3966. var text = '';
  3967. var embed = new Discord.RichEmbed().addField( username[0], username[1] ).addField( guildlist[0], guildlist[1] );
  3968. }
  3969. else {
  3970. var embed = {};
  3971. var text = username.join(' ') + '\n' + guildlist.join(' ');
  3972. }
  3973. msg.sendChannel( text, embed, true );
  3974. } else if ( client.guilds.some( guild => guild.channels.filter( chat => chat.type === 'text' ).has(id) ) ) {
  3975. var channel = client.guilds.find( guild => guild.channels.filter( chat => chat.type === 'text' ).has(id) ).channels.get(id);
  3976. var channelguild = ['Guild:', channel.guild.name.escapeFormatting() + ' `' + channel.guild.id + '`' + ( pause[channel.guild.id] ? '\\*' : '' )];
  3977. var channelname = ['Channel:', '#' + channel.name.escapeFormatting() + ' `' + channel.id + '` ' + channel.toString()];
  3978. var channelpermissions = ['Missing permissions:', ( channel.memberPermissions(channel.guild.me).has(defaultPermissions) ? '*none*' : '`' + channel.memberPermissions(channel.guild.me).missing(defaultPermissions).join('`, `') + '`' )];
  3979. var channellang = ['Language:', '*unknown*'];
  3980. var channelwiki = ['Default Wiki:', '*unknown*'];
  3981. var channelinline = ['Inline commands:', '*unknown*'];
  3982. 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) => {
  3983. if ( dberror ) {
  3984. console.log( '- Error while getting the settings: ' + dberror );
  3985. }
  3986. else if ( row ) {
  3987. channellang[1] = row.lang;
  3988. channelwiki[1] = row.wiki;
  3989. channelinline[1] = ( row.inline ? 'disabled' : 'enabled' );
  3990. }
  3991. else {
  3992. channellang[1] = defaultSettings.lang;
  3993. channelwiki[1] = defaultSettings.wiki;
  3994. channelinline[1] = 'enabled';
  3995. }
  3996. if ( msg.showEmbed() ) {
  3997. var text = '';
  3998. 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] );
  3999. }
  4000. else {
  4001. var embed = {};
  4002. var text = channelguild.join(' ') + '\n' + channelname.join(' ') + '\n' + channelpermissions.join(' ') + '\n' + channellang.join(' ') + '\n' + channelwiki[0] + ' <' + channelwiki[1] + '>\n' + channelinline.join(' ');
  4003. }
  4004. msg.sendChannel( text, embed, true );
  4005. } );
  4006. } else msg.replyMsg( 'I couldn\'t find a result for `' + id + '`', {}, true );
  4007. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4008. }
  4009. function cmd_patreon(lang, msg, args, line, wiki) {
  4010. if ( msg.channel.id !== process.env.channel || !args.join('') ) {
  4011. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4012. return;
  4013. }
  4014. if ( args[0] === 'enable' && /^\d+$/.test(args.slice(1).join(' ')) ) {
  4015. if ( !client.guilds.has(args[1]) ) return msg.replyMsg( 'I\'m not on a server with the id `' + args[1] + '`.', {}, true );
  4016. if ( args[1] in patreons ) return msg.replyMsg( '"' + client.guilds.get(args[1]) + '" has the patreon features already enabled.', {}, true );
  4017. 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) => {
  4018. if ( dberror ) {
  4019. console.log( '- Error while getting the patreon: ' + dberror );
  4020. msg.replyMsg( 'I got an error while searching for you, please try again later.', {}, true );
  4021. return dberror;
  4022. }
  4023. if ( !row ) return msg.replyMsg( 'you can\'t have any server.', {}, true );
  4024. if ( row.count <= row.guilds ) return msg.replyMsg( 'you already reached your maximal server count.', {}, true );
  4025. db.run( 'UPDATE discord SET patreon = ? WHERE guild = ? AND channel IS NULL', [msg.author.id, args[1]], function (error) {
  4026. if ( error ) {
  4027. console.log( '- Error while updating the guild: ' + error );
  4028. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4029. return error;
  4030. }
  4031. if ( !this.changes ) return db.run( 'INSERT INTO discord(guild, patreon) VALUES(?, ?)', [args[1], msg.author.id], function (inserror) {
  4032. if ( inserror ) {
  4033. console.log( '- Error while adding the guild: ' + inserror );
  4034. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4035. return inserror;
  4036. }
  4037. console.log( '- Guild successfully added.' );
  4038. patreons[args[1]] = process.env.prefix;
  4039. msg.replyMsg( 'the patreon features are now enabled on "' + client.guilds.get(args[1]) + '".', {}, true );
  4040. } );
  4041. console.log( '- Guild successfully updated.' );
  4042. patreons[args[1]] = process.env.prefix;
  4043. msg.replyMsg( 'the patreon features are now enabled on "' + client.guilds.get(args[1]) + '".', {}, true );
  4044. } );
  4045. } );
  4046. }
  4047. if ( args[0] === 'disable' && /^\d+$/.test(args.slice(1).join(' ')) ) {
  4048. if ( !client.guilds.has(args[1]) ) return msg.replyMsg( 'I\'m not on a server with the id `' + args[1] + '`.', {}, true );
  4049. if ( !( args[1] in patreons ) ) return msg.replyMsg( '"' + client.guilds.get(args[1]) + '" doesn\'t have the patreon features enabled.', {}, true );
  4050. return db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND patreon = ?', [args[1], msg.author.id], (dberror, row) => {
  4051. if ( dberror ) {
  4052. console.log( '- Error while getting the guild: ' + dberror );
  4053. msg.replyMsg( 'I got an error while searching for the server, please try again later.', {}, true );
  4054. return dberror;
  4055. }
  4056. if ( !row ) return msg.replyMsg( 'you didn\'t enable the patreon features for "' + client.guilds.get(args[1]) + '"!', {}, true );
  4057. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, args[1]], function (error) {
  4058. if ( error ) {
  4059. console.log( '- Error while updating the guild: ' + error );
  4060. msg.replyMsg( 'I got an error while updating the server, please try again later.', {}, true );
  4061. return error;
  4062. }
  4063. console.log( '- Guild successfully updated.' );
  4064. delete patreons[args[1]];
  4065. msg.replyMsg( 'the patreon features are now disabled on "' + client.guilds.get(args[1]) + '".', {}, true );
  4066. } );
  4067. } );
  4068. }
  4069. if ( args[1] ) args[1] = args[1].replace( /^\\?<@!?(\d+)>$/, '$1' );
  4070. if ( args[0] === 'check' ) {
  4071. 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) => {
  4072. if ( dberror ) {
  4073. console.log( '- Error while getting the patreon: ' + dberror );
  4074. msg.replyMsg( 'I got an error while searching for you, please try again later.', {}, true );
  4075. return dberror;
  4076. }
  4077. if ( !row ) return msg.replyMsg( 'you can\'t have any server.', {}, true );
  4078. var text = 'you can have up to ' + row.count + ' server.\n\n';
  4079. if ( row.guilds ) {
  4080. var guilds = row.guilds.split(',').map( guild => '`' + guild + '` ' + client.guilds.get(guild) );
  4081. text += 'Currently you have ' + guilds.length + ' server:\n' + guilds.join('\n');
  4082. }
  4083. else text += '*You don\'t have any server yet.*';
  4084. msg.replyMsg( text, {}, true );
  4085. } );
  4086. 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) => {
  4087. if ( dberror ) {
  4088. console.log( '- Error while getting the patreon: ' + dberror );
  4089. msg.replyMsg( 'I got an error while searching for <@' + args[1] + '>, please try again later.', {}, true );
  4090. return dberror;
  4091. }
  4092. if ( !row ) return msg.replyMsg( '<@' + args[1] + '> can\'t have any server.', {}, true );
  4093. var text = '<@' + args[1] + '> can have up to ' + row.count + ' server.\n\n';
  4094. if ( row.guilds ) {
  4095. var guilds = row.guilds.split(',').map( guild => '`' + guild + '` ' + client.guilds.get(guild) );
  4096. text += 'Currently they have ' + guilds.length + ' server:\n' + guilds.join('\n');
  4097. }
  4098. else text += '*They don\'t have any server yet.*';
  4099. msg.replyMsg( text, {}, true );
  4100. } );
  4101. }
  4102. 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) => {
  4103. if ( dberror ) {
  4104. console.log( '- Error while getting the patreon: ' + dberror );
  4105. msg.replyMsg( 'I got an error while searching for <@' + args[1] + '>, please try again later.', {}, true );
  4106. return dberror;
  4107. }
  4108. var value = parseInt(args[1], 10);
  4109. var count = ( row ? row.count : 0 );
  4110. var guilds = ( row && row.guilds ? row.guilds.split(',') : [] );
  4111. if ( args[1].startsWith( '+' ) || args[1].startsWith( '-' ) ) count += value;
  4112. else count = value;
  4113. if ( count <= 0 ) return db.run( 'DELETE FROM patreons WHERE patreon = ?', [args[1]], function (error) {
  4114. if ( error ) {
  4115. console.log( '- Error while deleting the patreon: ' + error );
  4116. msg.replyMsg( 'I got an error while deleting <@' + args[1] + '>, please try again later.', {}, true );
  4117. return error;
  4118. }
  4119. console.log( '- Patreon successfully deleted.' );
  4120. if ( !guilds.length ) return msg.replyMsg( '<@' + args[1] + '> is no longer a patreon.', {}, true );
  4121. db.each( 'SELECT guild, lang, inline FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ') AND channel IS NULL', guilds, (eacherror, eachrow) => {
  4122. if ( eacherror ) {
  4123. console.log( '- Error while getting the guild: ' + eacherror );
  4124. msg.replyMsg( 'I couldn\'t disable the patreon features.', {}, true );
  4125. return eacherror;
  4126. }
  4127. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ? WHERE guild = ?', [eachrow.lang, eachrow.inline, process.env.prefix, eachrow.guild], function (uperror) {
  4128. if ( uperror ) {
  4129. console.log( '- Error while updating the guild: ' + uperror );
  4130. msg.replyMsg( 'I couldn\'t disable the patreon features for `' + eachrow.guild + '`.', {}, true );
  4131. return uperror;
  4132. }
  4133. console.log( '- Guild successfully updated.' );
  4134. delete patreons[eachrow.guild];
  4135. } );
  4136. }, (eacherror) => {
  4137. if ( eacherror ) {
  4138. console.log( '- Error while getting the guilds: ' + eacherror );
  4139. msg.replyMsg( 'I couldn\'t disable the patreon features for `' + guilds.join('`, `') + '`.', {}, true );
  4140. return eacherror;
  4141. }
  4142. msg.replyMsg( '<@' + args[1] + '> is no longer a patreon.', {}, true );
  4143. } );
  4144. } );
  4145. if ( !row ) return db.run( 'INSERT INTO patreons(patreon, count) VALUES(?, ?)', [args[1], count], function (error) {
  4146. if ( error ) {
  4147. console.log( '- Error while adding the patreon: ' + error );
  4148. msg.replyMsg( 'I got an error while adding <@' + args[1] + '>, please try again later.', {}, true );
  4149. return error;
  4150. }
  4151. console.log( '- Patreon successfully added.' );
  4152. msg.replyMsg( '<@' + args[1] + '> can now have up to ' + count + ' server.', {}, true );
  4153. } );
  4154. db.run( 'UPDATE patreons SET count = ? WHERE patreon = ?', [count, args[1]], function (error) {
  4155. if ( error ) {
  4156. console.log( '- Error while updating the patreon: ' + error );
  4157. msg.replyMsg( 'I got an error while updating <@' + args[1] + '>, please try again later.', {}, true );
  4158. return error;
  4159. }
  4160. console.log( '- Patreon successfully updated.' );
  4161. var text = '<@' + args[1] + '> can now have up to ' + count + ' server.';
  4162. if ( count < guilds.length ) text += '\n\n**They are now above their server limit!**';
  4163. msg.replyMsg( text, {}, true );
  4164. } );
  4165. } );
  4166. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4167. }
  4168. function discussion_formatting(jsonModel) {
  4169. var description = '';
  4170. switch ( jsonModel.type ) {
  4171. case 'doc':
  4172. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  4173. break;
  4174. case 'paragraph':
  4175. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  4176. description += '\n';
  4177. break;
  4178. case 'text':
  4179. var prepend = '';
  4180. var append = '';
  4181. if ( jsonModel.marks ) {
  4182. jsonModel.marks.forEach( mark => {
  4183. switch ( mark.type ) {
  4184. case 'mention':
  4185. prepend += '[';
  4186. append = ']({@wiki}f/u/' + mark.attrs.userId + ')' + append;
  4187. break;
  4188. case 'link':
  4189. prepend += '[';
  4190. append = '](' + mark.attrs.href + ')' + append;
  4191. break;
  4192. case 'strong':
  4193. prepend += '**';
  4194. append = '**' + append;
  4195. break;
  4196. case 'em':
  4197. prepend += '_';
  4198. append = '_' + append;
  4199. break;
  4200. }
  4201. } );
  4202. }
  4203. description += prepend + jsonModel.text.escapeFormatting() + append;
  4204. break;
  4205. case 'image':
  4206. description += '{@' + jsonModel.attrs.id + '}\n';
  4207. break;
  4208. case 'code_block':
  4209. description += '```\n';
  4210. if ( jsonModel.content ) jsonModel.content.forEach( content => description += discussion_formatting(content) );
  4211. description += '\n```\n';
  4212. break;
  4213. case 'bulletList':
  4214. jsonModel.content.forEach( listItem => {
  4215. description += ' • ';
  4216. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  4217. } );
  4218. break;
  4219. case 'orderedList':
  4220. var n = 1;
  4221. jsonModel.content.forEach( listItem => {
  4222. description += ' ' + n + '. ';
  4223. n++;
  4224. if ( listItem.content ) listItem.content.forEach( content => description += discussion_formatting(content) );
  4225. } );
  4226. break;
  4227. }
  4228. return description;
  4229. }
  4230. function htmlToPlain(html) {
  4231. var text = '';
  4232. var parser = new htmlparser.Parser( {
  4233. ontext: (htmltext) => {
  4234. text += htmltext.escapeFormatting();
  4235. }
  4236. }, {decodeEntities:true} );
  4237. parser.write( html );
  4238. parser.end();
  4239. return text;
  4240. };
  4241. function htmlToDiscord(html) {
  4242. var text = '';
  4243. var parser = new htmlparser.Parser( {
  4244. onopentag: (tagname, attribs) => {
  4245. switch (tagname) {
  4246. case 'b':
  4247. text += '**';
  4248. break;
  4249. case 'i':
  4250. text += '*';
  4251. break;
  4252. case 's':
  4253. text += '~~';
  4254. break;
  4255. case 'u':
  4256. text += '__';
  4257. break;
  4258. }
  4259. },
  4260. ontext: (htmltext) => {
  4261. text += htmltext.escapeFormatting();
  4262. },
  4263. onclosetag: (tagname) => {
  4264. switch (tagname) {
  4265. case 'b':
  4266. text += '**';
  4267. break;
  4268. case 'i':
  4269. text += '*';
  4270. break;
  4271. case 's':
  4272. text += '~~';
  4273. break;
  4274. case 'u':
  4275. text += '__';
  4276. break;
  4277. }
  4278. }
  4279. }, {decodeEntities:true} );
  4280. parser.write( html );
  4281. parser.end();
  4282. return text;
  4283. };
  4284. String.prototype.noWiki = function(href) {
  4285. if ( !href ) return false;
  4286. else if ( this.endsWith( '.gamepedia.com/' ) ) return 'https://www.gamepedia.com/' === href;
  4287. else return [
  4288. 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' ),
  4289. this + 'language-wikis'
  4290. ].includes( href );
  4291. };
  4292. String.prototype.isFandom = function() {
  4293. return /^https:\/\/[a-z\d-]{1,50}\.(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?$/.test(this);
  4294. };
  4295. String.prototype.toLink = function() {
  4296. if ( this.endsWith( '.org/w/' ) ) return this.substring(0, this.length - 2) + 'wiki/';
  4297. else return this;
  4298. };
  4299. String.prototype.toLink = function() {
  4300. if ( this.endsWith( '.gamepedia.com/' ) ) return this;
  4301. else if ( this.isFandom() ) return this + 'wiki/';
  4302. else if ( this.endsWith( '.org/w/' ) ) return this.substring(0, this.length - 2) + 'wiki/';
  4303. else return this;
  4304. };
  4305. String.prototype.isMention = function(guild) {
  4306. var text = this.trim();
  4307. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  4308. };
  4309. Discord.Message.prototype.isAdmin = function() {
  4310. return this.channel.type === 'text' && this.member && ( this.member.permissions.has('MANAGE_GUILD') || ( this.isOwner() && this.evalUsed ) );
  4311. };
  4312. Discord.Message.prototype.isOwner = function() {
  4313. return this.author.id === process.env.owner;
  4314. };
  4315. Discord.Message.prototype.showEmbed = function() {
  4316. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  4317. };
  4318. Discord.Message.prototype.uploadFiles = function() {
  4319. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  4320. };
  4321. Array.prototype.toEmojis = function() {
  4322. var text = this.join(' ');
  4323. var regex = /(<a?:)(\d+)(>)/g;
  4324. if ( regex.test(text) ) {
  4325. regex.lastIndex = 0;
  4326. var emojis = client.emojis;
  4327. var entry = null;
  4328. while ( ( entry = regex.exec(text) ) !== null ) {
  4329. if ( emojis.has(entry[2]) ) {
  4330. text = text.replaceSave(entry[0], emojis.get(entry[2]).toString());
  4331. } else {
  4332. text = text.replaceSave(entry[0], entry[1] + 'unknown_emoji:' + entry[2] + entry[3]);
  4333. }
  4334. }
  4335. return text.split(' ');
  4336. }
  4337. else return this;
  4338. };
  4339. String.prototype.toTitle = function(isMarkdown = false) {
  4340. var title = this.replace( / /g, '_' ).replace( /\%/g, '%25' ).replace( /\\/g, '%5C' ).replace( /\?/g, '%3F' ).replace( /@(here|everyone)/g, '%40$1' );
  4341. if ( isMarkdown ) title = title.replace( /([\(\)])/g, '\\$1' );
  4342. return title;
  4343. };
  4344. String.prototype.toSearch = function() {
  4345. return encodeURIComponent( this ).replace( /%20/g, '+' );
  4346. };
  4347. String.prototype.toSection = function() {
  4348. return encodeURIComponent( this.replace( / /g, '_' ) ).replace( /\'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\%/g, '.' );
  4349. };
  4350. String.prototype.toFormatting = function(showEmbed = false, ...args) {
  4351. if ( showEmbed ) return this.toMarkdown(...args);
  4352. else return this.toPlaintext();
  4353. };
  4354. String.prototype.toMarkdown = function(wiki, title = '') {
  4355. var text = this.replace( /[\(\)\\]/g, '\\$&' );
  4356. var link = null;
  4357. while ( ( link = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g.exec(text) ) !== null ) {
  4358. if ( link[1] ) {
  4359. var page = ( /^[#\/]/.test(link[1]) ? title.toTitle(true) + ( /^#/.test(link[1]) ? '#' + link[1].substring(1).toSection() : link[1].toTitle(true) ) : link[1].toTitle(true) );
  4360. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + wiki.toLink() + page + ')' );
  4361. } else {
  4362. var page = ( /^[#\/]/.test(link[2]) ? title.toTitle(true) + ( /^#/.test(link[2]) ? '#' + link[2].substring(1).toSection() : link[2].toTitle(true) ) : link[2].toTitle(true) );
  4363. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + wiki.toLink() + page + ')' );
  4364. }
  4365. }
  4366. while ( title !== '' && ( link = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g.exec(text) ) !== null ) {
  4367. var page = title.toTitle(true) + '#' + link[1].toSection();
  4368. text = text.replaceSave( link[0], '[→' + link[1] + '](' + wiki.toLink() + page + ')' + ( link[2] ? ': ' + link[2] : '' ) );
  4369. }
  4370. return text.escapeFormatting(true);
  4371. };
  4372. String.prototype.toPlaintext = function() {
  4373. return this.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' ).escapeFormatting();
  4374. };
  4375. String.prototype.escapeFormatting = function(isMarkdown) {
  4376. var text = this;
  4377. if ( !isMarkdown ) text = text.replace( /[\(\)\\]/g, '\\$&' );
  4378. return text.replace( /[`_\*~:<>{}@\|]|\/\//g, '\\$&' );
  4379. };
  4380. String.prototype.replaceSave = function(pattern, replacement) {
  4381. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  4382. };
  4383. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  4384. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  4385. var emoji = '440871715938238494';
  4386. switch ( name ) {
  4387. case 'nowiki':
  4388. emoji = '505884572001763348';
  4389. break;
  4390. case 'error':
  4391. emoji = '440871715938238494';
  4392. break;
  4393. case 'support':
  4394. emoji = '448222377009086465';
  4395. break;
  4396. case 'oppose':
  4397. emoji = '448222455425794059';
  4398. break;
  4399. default:
  4400. emoji = name;
  4401. }
  4402. return this.react(emoji).catch(log_error);
  4403. } else {
  4404. console.log( '- Aborted, paused.' );
  4405. return Promise.resolve();
  4406. }
  4407. };
  4408. Discord.MessageReaction.prototype.removeEmoji = function() {
  4409. return this.remove().catch(log_error);
  4410. };
  4411. Discord.Message.prototype.sendChannel = function(content, options, ignorePause = false) {
  4412. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  4413. return this.channel.send(content, options).then( msg => {
  4414. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  4415. else msg.allowDelete(this.author.id);
  4416. return msg;
  4417. }, log_error );
  4418. } else {
  4419. console.log( '- Aborted, paused.' );
  4420. return Promise.resolve();
  4421. }
  4422. };
  4423. Discord.Message.prototype.sendChannelError = function(content, options) {
  4424. return this.channel.send(content, options).then( msg => {
  4425. if ( msg.length ) msg.forEach( message => {
  4426. message.reactEmoji('error');
  4427. message.allowDelete(this.author.id);
  4428. } );
  4429. else {
  4430. msg.reactEmoji('error');
  4431. msg.allowDelete(this.author.id);
  4432. }
  4433. return msg;
  4434. }, log_error );
  4435. };
  4436. Discord.Message.prototype.replyMsg = function(content, options, ignorePause = false) {
  4437. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  4438. return this.reply(content, options).then( msg => {
  4439. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  4440. else msg.allowDelete(this.author.id);
  4441. return msg;
  4442. }, log_error );
  4443. } else {
  4444. console.log( '- Aborted, paused.' );
  4445. return Promise.resolve();
  4446. }
  4447. };
  4448. Discord.Message.prototype.deleteMsg = function(timeout = 0) {
  4449. return this.delete(timeout).catch(log_error);
  4450. };
  4451. Discord.Message.prototype.allowDelete = function(author) {
  4452. return this.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:120000} ).then( reaction => {
  4453. if ( reaction.size ) {
  4454. this.deleteMsg();
  4455. }
  4456. } );
  4457. };
  4458. String.prototype.hasPrefix = function(prefix, flags = '') {
  4459. return new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + '(?: |$)', flags ).test(this.replace( /\u200b/g, '' ).toLowerCase());
  4460. };
  4461. client.on( 'message', msg => {
  4462. if ( stop || msg.type !== 'DEFAULT' || msg.system || msg.webhookID || msg.author.id === client.user.id ) return;
  4463. if ( !msg.content.hasPrefix(( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  4464. if ( msg.content === process.env.prefix + ' help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  4465. if ( msg.channel.permissionsFor(client.user).has('SEND_MESSAGES') ) {
  4466. console.log( msg.guild.name + ': ' + msg.content );
  4467. 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) => {
  4468. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  4469. msg.replyMsg( i18n[( row || defaultSettings ).lang].prefix.replaceSave( /%s/g, patreons[msg.guild.id] ), {}, true );
  4470. } );
  4471. }
  4472. }
  4473. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  4474. }
  4475. if ( !ready.allSites && !allSites.length ) getAllSites();
  4476. if ( msg.channel.type === 'text' ) {
  4477. var permissions = msg.channel.permissionsFor(client.user);
  4478. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  4479. if ( missing.length ) {
  4480. if ( msg.isAdmin() || msg.isOwner() ) {
  4481. console.log( msg.guild.name + ': Missing permissions - ' + missing.join(', ') );
  4482. if ( !missing.includes( 'SEND_MESSAGES' ) ) {
  4483. 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) => {
  4484. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  4485. if ( msg.content.hasPrefix(( patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  4486. msg.replyMsg( i18n[( row || defaultSettings ).lang].missingperm + ' `' + missing.join('`, `') + '`', {}, true );
  4487. }
  4488. } );
  4489. }
  4490. }
  4491. return;
  4492. }
  4493. 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) => {
  4494. if ( dberror ) {
  4495. console.log( '- Error while getting the wiki: ' + dberror );
  4496. if ( permissions.has('SEND_MESSAGES') ) {
  4497. msg.sendChannel( '⚠️ **Limited Functionality** ⚠️\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  4498. newMessage(msg);
  4499. }
  4500. return dberror;
  4501. }
  4502. if ( row ) newMessage(msg, row.wiki, i18n[row.lang], patreons[msg.guild.id], row.inline);
  4503. else {
  4504. msg.defaultSettings = true;
  4505. newMessage(msg);
  4506. }
  4507. } );
  4508. }
  4509. else newMessage(msg);
  4510. } );
  4511. function newMessage(msg, wiki = defaultSettings.wiki, lang = i18n[defaultSettings.lang], prefix = process.env.prefix, noInline = null, content) {
  4512. msg.noInline = noInline;
  4513. var cont = ( content || msg.content );
  4514. var cleanCont = ( content || msg.cleanContent );
  4515. var author = msg.author;
  4516. var channel = msg.channel;
  4517. var invoke = ( cont.split(' ')[1] ? cont.split(' ')[1].split('\n')[0].toLowerCase() : '' );
  4518. var aliasInvoke = ( lang.aliase[invoke] || invoke );
  4519. var ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  4520. if ( cont.hasPrefix(prefix) && ( ( msg.isAdmin() && aliasInvoke in multilinecmdmap ) || ownercmd ) ) {
  4521. if ( ownercmd || channel.permissionsFor(client.user).has('MANAGE_MESSAGES') ) {
  4522. var args = cont.split(' ').slice(2);
  4523. if ( cont.split(' ')[1].split('\n')[1] ) args.unshift( '', cont.split(' ')[1].split('\n')[1] );
  4524. if ( !( ownercmd || aliasInvoke in pausecmdmap ) && pause[msg.guild.id] ) console.log( msg.guild.name + ': Paused' );
  4525. else console.log( ( channel.type === 'text' ? msg.guild.name : '@' + author.username ) + ': ' + cont );
  4526. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, cont, wiki);
  4527. else if ( !pause[msg.guild.id] || aliasInvoke in pausecmdmap ) multilinecmdmap[aliasInvoke](lang, msg, args, cont, wiki);
  4528. } else {
  4529. console.log( msg.guild.name + ': Missing permissions - MANAGE_MESSAGES' );
  4530. msg.replyMsg( lang.missingperm + ' `MANAGE_MESSAGES`' );
  4531. }
  4532. } else {
  4533. var count = 0;
  4534. var maxcount = ( channel.type === 'text' && msg.guild.id in patreons ? 15 : 10 );
  4535. cleanCont.replace( /\u200b/g, '' ).split('\n').forEach( line => {
  4536. if ( line.hasPrefix(prefix) && count < maxcount ) {
  4537. count++;
  4538. invoke = ( line.split(' ')[1] ? line.split(' ')[1].toLowerCase() : '' );
  4539. var args = line.split(' ').slice(2);
  4540. aliasInvoke = ( lang.aliase[invoke] || invoke );
  4541. ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  4542. if ( channel.type === 'text' && pause[msg.guild.id] && !( ( msg.isAdmin() && aliasInvoke in pausecmdmap ) || ownercmd ) ) console.log( msg.guild.name + ': Paused' );
  4543. else console.log( ( channel.type === 'text' ? msg.guild.name : '@' + author.username ) + ': ' + line );
  4544. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, line, wiki);
  4545. else if ( channel.type !== 'text' || !pause[msg.guild.id] || ( msg.isAdmin() && aliasInvoke in pausecmdmap ) ) {
  4546. if ( aliasInvoke in cmdmap ) cmdmap[aliasInvoke](lang, msg, args, line, wiki);
  4547. else if ( /^![a-z\d-]{1,50}$/.test(invoke) ) {
  4548. cmd_link(lang, msg, args.join(' '), 'https://' + invoke.substring(1) + '.gamepedia.com/', ' ' + invoke + ' ');
  4549. }
  4550. else if ( /^\?(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  4551. if ( invoke.includes( '.' ) ) wiki = 'https://' + invoke.split('.')[1] + '.fandom.com/' + invoke.substring(1).split('.')[0] + '/';
  4552. else wiki = 'https://' + invoke.substring(1) + '.fandom.com/';
  4553. cmd_link(lang, msg, args.join(' '), wiki, ' ' + invoke + ' ');
  4554. }
  4555. else if ( /^\?\?(?:[a-z-]{1,8}\.)?[a-z\d-]{1,50}$/.test(invoke) ) {
  4556. if ( invoke.includes( '.' ) ) wiki = 'https://' + invoke.split('.')[1] + '.wikia.org/' + invoke.substring(2).split('.')[0] + '/';
  4557. else wiki = 'https://' + invoke.substring(2) + '.wikia.org/';
  4558. cmd_link(lang, msg, args.join(' '), wiki, ' ' + invoke + ' ');
  4559. }
  4560. else cmd_link(lang, msg, line.split(' ').slice(1).join(' '), wiki);
  4561. }
  4562. } else if ( line.hasPrefix(prefix) && count === maxcount ) {
  4563. count++;
  4564. console.log( '- Message contains too many commands!' );
  4565. msg.reactEmoji('⚠️');
  4566. msg.sendChannelError( lang.limit.replaceSave( '%s', author ) );
  4567. }
  4568. } );
  4569. if ( ( channel.type !== 'text' || !pause[msg.guild.id] ) && !noInline && ( cont.includes( '[[' ) || cont.includes( '{{' ) ) ) {
  4570. var links = [];
  4571. var embeds = [];
  4572. var linkcount = 0;
  4573. var linkmaxcount = maxcount + 5;
  4574. msg.cleanContent.replace( /\u200b/g, '' ).replace( /(?<!\\)```.+?```/gs, '<codeblock>' ).replace( /(?<!\\)`.+?`/gs, '<code>' ).split('\n').forEach( line => {
  4575. if ( line.hasPrefix(prefix) || !( line.includes( '[[' ) || line.includes( '{{' ) ) ) return;
  4576. if ( line.includes( '[[' ) && line.includes( ']]' ) && linkcount <= linkmaxcount ) {
  4577. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)\\[\\[([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\]\\]\\1', 'g' );
  4578. let entry = null;
  4579. while ( ( entry = regex.exec(line) ) !== null ) {
  4580. if ( linkcount < linkmaxcount ) {
  4581. linkcount++;
  4582. console.log( ( channel.type === 'text' ? msg.guild.name : '@' + author.username ) + ': ' + entry[0] );
  4583. let title = entry[2].split('#')[0];
  4584. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  4585. links.push({title,section,spoiler:entry[1]});
  4586. }
  4587. else if ( linkcount === linkmaxcount ) {
  4588. linkcount++;
  4589. console.log( '- Message contains too many links!' );
  4590. msg.reactEmoji('⚠️');
  4591. break;
  4592. }
  4593. }
  4594. }
  4595. if ( line.includes( '{{' ) && line.includes( '}}' ) && count <= maxcount ) {
  4596. let regex = new RegExp( '(?<!\\\\)(|\\|\\|)(?<!\\{)\\{\\{([^' + "<>\\[\\]\\|{}\\x01-\\x1F\\x7F" + ']+)(?<!\\\\)\\}\\}\\1', 'g' );
  4597. let entry = null;
  4598. while ( ( entry = regex.exec(line) ) !== null ) {
  4599. if ( count < maxcount ) {
  4600. count++;
  4601. console.log( ( channel.type === 'text' ? msg.guild.name : '@' + author.username ) + ': ' + entry[0] );
  4602. let title = entry[2].split('#')[0];
  4603. let section = ( entry[2].includes( '#' ) ? entry[2].split('#').slice(1).join('#') : '' )
  4604. embeds.push({title,section,spoiler:entry[1]});
  4605. }
  4606. else if ( count === maxcount ) {
  4607. count++;
  4608. console.log( '- Message contains too many links!' );
  4609. msg.reactEmoji('⚠️');
  4610. break;
  4611. }
  4612. }
  4613. }
  4614. } );
  4615. if ( links.length ) request( {
  4616. uri: wiki + 'api.php?action=query&iwurl=true&titles=' + encodeURIComponent( links.map( link => link.title ).join('|') ) + '&format=json',
  4617. json: true
  4618. }, function( error, response, body ) {
  4619. if ( error || !response || response.statusCode !== 200 || !body || !body.query ) {
  4620. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  4621. console.log( '- This wiki doesn\'t exist!' );
  4622. msg.reactEmoji('nowiki');
  4623. return;
  4624. }
  4625. console.log( '- ' + ( response && response.statusCode ) + ': Error while following the links: ' + ( error || body && body.error && body.error.info ) );
  4626. return;
  4627. }
  4628. if ( body.query.normalized ) {
  4629. body.query.normalized.forEach( title => links.filter( link => link.title === title.from ).forEach( link => link.title = title.to ) );
  4630. }
  4631. if ( body.query.interwiki ) {
  4632. body.query.interwiki.forEach( interwiki => links.filter( link => link.title === interwiki.title ).forEach( link => {
  4633. link.url = interwiki.url + ( link.section ? '#' + link.section.toSection() : '' );
  4634. } ) );
  4635. }
  4636. if ( body.query.pages ) {
  4637. var querypages = Object.values(body.query.pages);
  4638. querypages.filter( page => page.invalid !== undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  4639. links.splice(links.indexOf(link), 1);
  4640. } ) );
  4641. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => links.filter( link => link.title === page.title ).forEach( link => {
  4642. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  4643. link.url = wiki.toLink() + link.title.toTitle() + '?action=edit&redlink=1';
  4644. } ) );
  4645. }
  4646. 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} );
  4647. } );
  4648. if ( embeds.length ) request( {
  4649. 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',
  4650. json: true
  4651. }, function( error, response, body ) {
  4652. if ( error || !response || response.statusCode !== 200 || !body || !body.query ) {
  4653. if ( response && ( response.request && response.request.uri && wiki.noWiki(response.request.uri.href) || response.statusCode === 410 ) ) {
  4654. console.log( '- This wiki doesn\'t exist!' );
  4655. msg.reactEmoji('nowiki');
  4656. return;
  4657. }
  4658. console.log( '- ' + ( response && response.statusCode ) + ': Error while following the links: ' + ( error || body && body.error && body.error.info ) );
  4659. return;
  4660. }
  4661. if ( body.query.normalized ) {
  4662. body.query.normalized.forEach( title => embeds.filter( embed => embed.title === title.from ).forEach( embed => embed.title = title.to ) );
  4663. }
  4664. if ( body.query.pages ) {
  4665. var querypages = Object.values(body.query.pages);
  4666. querypages.filter( page => page.invalid !== undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  4667. embeds.splice(embeds.indexOf(embed), 1);
  4668. } ) );
  4669. var missing = [];
  4670. querypages.filter( page => page.missing !== undefined && page.known === undefined ).forEach( page => embeds.filter( embed => embed.title === page.title ).forEach( embed => {
  4671. if ( ( page.ns === 2 || page.ns === 202 ) && !page.title.includes( '/' ) ) return;
  4672. embeds.splice(embeds.indexOf(embed), 1);
  4673. if ( page.ns === 0 && !embed.section ) {
  4674. var template = querypages.find( template => template.ns === 10 && template.title.split(':').slice(1).join(':') === embed.title );
  4675. if ( template && template.missing === undefined ) embed.template = template.title.toTitle();
  4676. }
  4677. if ( embed.template || !body.query.variables || !body.query.variables.some( variable => variable.toUpperCase() === embed.title ) ) missing.push(embed);
  4678. } ) );
  4679. if ( missing.length ) {
  4680. msg.sendChannel( missing.map( embed => embed.spoiler + '<' + wiki.toLink() + ( embed.template || embed.title.toTitle() + '?action=edit&redlink=1' ) + '>' + embed.spoiler ).join('\n'), {split:true} );
  4681. }
  4682. }
  4683. if ( embeds.length ) {
  4684. if ( wiki.isFandom() ) embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  4685. fandom_check_wiki(lang, msg, embed.title, wiki, ' ', reaction, embed.spoiler, '', embed.section);
  4686. } ) );
  4687. else embeds.forEach( embed => msg.reactEmoji('⏳').then( reaction => {
  4688. gamepedia_check_wiki(lang, msg, embed.title, wiki, ' ', reaction, embed.spoiler, '', embed.section);
  4689. } ) );
  4690. }
  4691. } );
  4692. }
  4693. }
  4694. }
  4695. client.on( 'voiceStateUpdate', (oldm, newm) => {
  4696. if ( stop || !( oldm.guild.id in voice ) || !oldm.guild.me.permissions.has('MANAGE_ROLES') || oldm.voiceChannelID === newm.voiceChannelID ) return;
  4697. if ( !ready.allSites && !allSites.length ) getAllSites();
  4698. var lang = i18n[voice[oldm.guild.id]].voice;
  4699. if ( oldm.voiceChannel ) {
  4700. var oldrole = oldm.roles.find( role => role.name === lang.channel + ' – ' + oldm.voiceChannel.name );
  4701. if ( oldrole && oldrole.comparePositionTo(oldm.guild.me.highestRole) < 0 ) {
  4702. console.log( oldm.guild.name + ': ' + oldm.displayName + ' left the voice channel "' + oldm.voiceChannel.name + '".' );
  4703. oldm.removeRole( oldrole, lang.left.replaceSave( '%1$s', oldm.displayName ).replaceSave( '%2$s', oldm.voiceChannel.name ) ).catch(log_error);
  4704. }
  4705. }
  4706. if ( newm.voiceChannel ) {
  4707. var newrole = newm.guild.roles.find( role => role.name === lang.channel + ' – ' + newm.voiceChannel.name );
  4708. if ( newrole && newrole.comparePositionTo(newm.guild.me.highestRole) < 0 ) {
  4709. console.log( newm.guild.name + ': ' + newm.displayName + ' joined the voice channel "' + newm.voiceChannel.name + '".' );
  4710. newm.addRole( newrole, lang.join.replaceSave( '%1$s', newm.displayName ).replaceSave( '%2$s', newm.voiceChannel.name ) ).catch(log_error);
  4711. }
  4712. }
  4713. } );
  4714. client.on( 'guildCreate', guild => {
  4715. console.log( '- I\'ve been added to a server.' );
  4716. } );
  4717. client.on( 'guildDelete', guild => {
  4718. if ( !guild.available ) {
  4719. console.log( '- ' + guild.name + ': This server isn\'t responding.' );
  4720. return;
  4721. }
  4722. console.log( '- I\'ve been removed from a server.' );
  4723. db.run( 'DELETE FROM discord WHERE guild = ?', [guild.id], function (dberror) {
  4724. if ( dberror ) {
  4725. console.log( '- Error while removing the settings: ' + dberror );
  4726. return dberror;
  4727. }
  4728. if ( guild.id in patreons ) delete patreons[guild.id];
  4729. if ( guild.id in voice ) delete voice[guild.id];
  4730. console.log( '- Settings successfully removed.' );
  4731. } );
  4732. } );
  4733. function removePatreons(guild, msg) {
  4734. try {
  4735. if ( !guild ) return 'removePatreons(guild, msg) – No guild provided!';
  4736. db.get( 'SELECT lang, inline FROM discord WHERE guild = ? AND channel IS NULL', [guild], (dberror, row) => {
  4737. try {
  4738. if ( dberror ) {
  4739. console.log( '- Error while getting the guild: ' + dberror );
  4740. if ( msg ) msg.replyMsg( 'I got an error while searching for the guild!', {}, true );
  4741. return dberror;
  4742. }
  4743. if ( !row ) {
  4744. if ( msg ) msg.replyMsg( 'that guild doesn\'t exist!', {}, true );
  4745. return;
  4746. }
  4747. db.run( 'UPDATE discord SET lang = ?, inline = ?, prefix = ?, patreon = NULL WHERE guild = ?', [row.lang, row.inline, process.env.prefix, guild], function (error) {
  4748. try {
  4749. if ( error ) {
  4750. console.log( '- Error while updating the guild: ' + error );
  4751. if ( msg ) msg.replyMsg( 'I got an error while updating the guild!', {}, true );
  4752. return error;
  4753. }
  4754. console.log( '- Guild successfully updated.' );
  4755. delete patreons[guild];
  4756. if ( msg ) msg.replyMsg( 'the patreon features are now disabled on that guild.', {}, true );
  4757. }
  4758. catch ( tryerror ) {
  4759. console.log( '- Error while removing the patreon features: ' + tryerror );
  4760. }
  4761. } );
  4762. }
  4763. catch ( tryerror ) {
  4764. console.log( '- Error while removing the patreon features: ' + tryerror );
  4765. }
  4766. } );
  4767. }
  4768. catch ( tryerror ) {
  4769. console.log( '- Error while removing the patreon features: ' + tryerror );
  4770. return 'removePatreons(guild, msg) – Error while removing the patreon features: ' + tryerror;
  4771. }
  4772. }
  4773. function removeSettings() {
  4774. var guilds = [];
  4775. var channels = [];
  4776. db.each( 'SELECT guild, channel FROM discord', [], (dberror, row) => {
  4777. if ( dberror ) {
  4778. console.log( '- Error while getting the setting: ' + dberror );
  4779. return dberror;
  4780. }
  4781. if ( !row.channel && !client.guilds.has(row.guild) ) {
  4782. if ( row.guild in patreons ) delete patreons[row.guild];
  4783. if ( row.guild in voice ) delete voice[row.guild];
  4784. return guilds.push(row.guild);
  4785. }
  4786. if ( row.channel && client.guilds.has(row.guild) && !client.channels.filter( channel => channel.type === 'text' ).has(row.channel) ) return channels.push(row.channel);
  4787. }, (error) => {
  4788. if ( error ) {
  4789. console.log( '- Error while getting the settings: ' + error );
  4790. return error;
  4791. }
  4792. if ( guilds.length ) db.run( 'DELETE FROM discord WHERE guild IN (' + guilds.map( guild => '?' ).join(', ') + ')', guilds, function (dberror) {
  4793. if ( dberror ) {
  4794. console.log( '- Error while removing the guilds: ' + dberror );
  4795. return dberror;
  4796. }
  4797. console.log( '- Guilds successfully removed.' );
  4798. } );
  4799. if ( channels.length ) db.run( 'DELETE FROM discord WHERE channel IN (' + channels.map( channel => '?' ).join(', ') + ')', channels, function (dberror) {
  4800. if ( dberror ) {
  4801. console.log( '- Error while removing the channels: ' + dberror );
  4802. return dberror;
  4803. }
  4804. console.log( '- Channels successfully removed.' );
  4805. } );
  4806. if ( !guilds.length && !channels.length ) console.log( '- Settings successfully removed.' );
  4807. } );
  4808. }
  4809. client.login(process.env.token).catch( error => {
  4810. log_error(error, true, 'LOGIN-');
  4811. client.login(process.env.token).catch( error => {
  4812. log_error(error, true, 'LOGIN-');
  4813. client.login(process.env.token).catch( error => {
  4814. log_error(error, true, 'LOGIN-');
  4815. process.exit(1);
  4816. } );
  4817. } );
  4818. } );
  4819. client.on( 'error', error => log_error(error, true) );
  4820. client.on( 'warn', warning => log_warn(warning, false) );
  4821. if ( isDebug ) client.on( 'debug', debug => {
  4822. if ( isDebug ) console.log( '- Debug: ' + debug );
  4823. } );
  4824. function log_error(error, isBig = false, type = '') {
  4825. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  4826. if ( isDebug ) {
  4827. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  4828. } else {
  4829. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  4830. else console.log( '- ' + error.name + ': ' + error.message );
  4831. }
  4832. }
  4833. function log_warn(warning, api = true) {
  4834. if ( isDebug ) {
  4835. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  4836. } else {
  4837. if ( api ) console.warn( '- Warning: ' + Object.keys(warning).join(', ') );
  4838. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  4839. }
  4840. }
  4841. async function graceful(code = 0) {
  4842. stop = true;
  4843. console.log( '- SIGTERM: Preparing to close...' );
  4844. setTimeout( async () => {
  4845. console.log( '- SIGTERM: Destroying client...' );
  4846. await client.destroy();
  4847. await db.close( dberror => {
  4848. if ( dberror ) {
  4849. console.log( '- SIGTERM: Error while closing the database connection: ' + dberror );
  4850. return dberror;
  4851. }
  4852. console.log( '- SIGTERM: Closed the database connection.' );
  4853. } );
  4854. setTimeout( async () => {
  4855. console.log( '- SIGTERM: Closing takes too long, terminating!' );
  4856. process.exit(code);
  4857. }, 2000 ).unref();
  4858. }, 1000 ).unref();
  4859. }
  4860. process.once( 'SIGINT', graceful );
  4861. process.once( 'SIGTERM', graceful );