main.js 253 KB

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