main.js 254 KB

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