main.js 249 KB

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