main.js 249 KB

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