main.js 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247
  1. require('dotenv').config();
  2. const util = require('util');
  3. util.inspect.defaultOptions = {compact:false,breakLength:Infinity};
  4. const Discord = require('discord.js');
  5. const DBL = require('dblapi.js');
  6. var request = require('request');
  7. var htmlparser = require('htmlparser2');
  8. var client = new Discord.Client( {
  9. messageCacheLifetime: 600,
  10. messageSweepInterval: 6000,
  11. disableEveryone: true,
  12. disabledEvents: ["TYPING_START"]
  13. } );
  14. const dbl = new DBL(process.env.dbltoken);
  15. var i18n = require('./i18n/allLangs.json');
  16. Object.keys(i18n.allLangs[1]).forEach( lang => i18n[lang] = require('./i18n/' + lang + '.json') );
  17. var minecraft = require('./minecraft.json');
  18. var multiManager = require('./wiki_manager.json');
  19. var pause = {};
  20. var stop = false;
  21. var isDebug = ( process.argv[2] === 'debug' );
  22. const access = {'PRIVATE-TOKEN': process.env.access};
  23. const defaultPermissions = new Discord.Permissions(268954688).toArray();
  24. const timeoptions = {
  25. year: 'numeric',
  26. month: 'short',
  27. day: 'numeric',
  28. hour: '2-digit',
  29. minute: '2-digit',
  30. timeZone: 'UTC',
  31. timeZoneName: 'short'
  32. }
  33. var ready = {
  34. settings: true,
  35. allSites: true
  36. }
  37. const defaultSettings = {
  38. "default": {
  39. "lang": "en",
  40. "wiki": "https://help.gamepedia.com/"
  41. }
  42. }
  43. var settings = defaultSettings;
  44. function getSettings() {
  45. ready.settings = true;
  46. request( {
  47. uri: process.env.read + process.env.file + process.env.raw,
  48. headers: access,
  49. json: true
  50. }, function( error, response, body ) {
  51. if ( error || !response || response.statusCode !== 200 || !body || body.message || body.error ) {
  52. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the settings: ' + ( error || body && ( body.message || body.error ) ) );
  53. ready.settings = false;
  54. }
  55. else {
  56. console.log( '- Settings successfully loaded.' );
  57. if ( body.default ) settings = JSON.parse(JSON.stringify(body));
  58. else if ( settings === defaultSettings ) settings = JSON.parse(JSON.stringify(defaultSettings));
  59. }
  60. setStatus();
  61. } );
  62. }
  63. function setStatus() {
  64. if ( settings === defaultSettings ) client.user.setStatus('invisible').catch(log_error);
  65. else {
  66. client.user.setStatus('online').catch(log_error);
  67. client.user.setActivity( process.env.prefix + ' help' ).catch(log_error);
  68. }
  69. }
  70. var allSites = [];
  71. function getAllSites() {
  72. ready.allSites = true;
  73. request( {
  74. uri: 'https://help.gamepedia.com/api.php?action=allsites&formatversion=2&do=getSiteStats&filter=wikis|wiki_domain,wiki_display_name,wiki_managers,official_wiki,created,ss_good_articles,ss_total_pages,ss_total_edits,ss_active_users&format=json',
  75. json: true
  76. }, function( error, response, body ) {
  77. if ( error || !response || response.statusCode !== 200 || !body || body.status !== 'okay' || !body.data || !body.data.wikis ) {
  78. console.log( '- ' + ( response && response.statusCode ) + ': Error while gettings all sites: ' + ( error || body && body.error && body.error.info ) );
  79. ready.allSites = false;
  80. }
  81. else {
  82. console.log( '- Sites successfully loaded.' );
  83. allSites = JSON.parse(JSON.stringify(body.data.wikis.filter( site => /^[a-z\d-]{1,50}\.gamepedia\.com$/.test(site.wiki_domain) )));
  84. allSites.filter( site => site.wiki_domain in multiManager ).forEach( function(site) {
  85. site.wiki_managers = multiManager[site.wiki_domain].concat(site.wiki_managers).filter( (value, index, self) => self.indexOf(value) === index );
  86. } );
  87. allSites.filter( site => site.wiki_managers.length === 0 ).forEach( site => site.wiki_managers.push('MediaWiki default') );
  88. }
  89. } );
  90. }
  91. client.on( 'ready', () => {
  92. console.log( '- Successfully logged in as ' + client.user.username + '!' );
  93. getSettings();
  94. getAllSites();
  95. if ( !isDebug ) client.setInterval( () => {
  96. console.log( '- Current server count: ' + client.guilds.size );
  97. dbl.postStats(client.guilds.size).catch( () => {} );
  98. request.post( {
  99. uri: 'https://discord.bots.gg/api/v1/bots/' + client.user.id + '/stats',
  100. headers: {Authorization: process.env.dbggtoken},
  101. body: {guildCount: client.guilds.size},
  102. json: true
  103. } );
  104. }, 10800000 ).unref();
  105. } );
  106. var cmdmap = {
  107. help: cmd_help,
  108. test: cmd_test,
  109. pause: cmd_pause,
  110. invite: cmd_invite,
  111. say: cmd_multiline,
  112. delete: cmd_multiline,
  113. poll: cmd_multiline,
  114. voice: cmd_voice,
  115. settings: cmd_settings,
  116. info: cmd_info
  117. }
  118. var multilinecmdmap = {
  119. say: cmd_say,
  120. delete: cmd_delete,
  121. poll: cmd_umfrage
  122. }
  123. var ownercmdmap = {
  124. stop: cmd_stop,
  125. pause: cmd_pause,
  126. eval: cmd_eval,
  127. get: cmd_get
  128. }
  129. var pausecmdmap = {
  130. help: cmd_help,
  131. test: cmd_test,
  132. pause: cmd_pause,
  133. say: cmd_multiline,
  134. delete: cmd_multiline,
  135. settings: cmd_settings
  136. }
  137. var minecraftcmdmap = {
  138. command: cmd_befehl2,
  139. bug: cmd_bug
  140. }
  141. function cmd_settings(lang, msg, args, line) {
  142. if ( msg.isAdmin() ) {
  143. if ( msg.guild.id in settings ) {
  144. var text = lang.settings.current.replaceSave( '%1$s', '- `' + process.env.prefix + ' settings lang`' ).replaceSave( '%2$s', settings[msg.guild.id].wiki + ' - `' + process.env.prefix + ' settings wiki`' ) + ' - `' + process.env.prefix + ' settings channel`\n';
  145. if ( settings[msg.guild.id].channels ) {
  146. Object.keys(settings[msg.guild.id].channels).forEach( function(channel) {
  147. text += '<#' + channel + '>: <' + settings[msg.guild.id].channels[channel] + '>\n';
  148. } );
  149. } else text += lang.settings.nochannels;
  150. } else {
  151. var text = lang.settings.missing.replaceSave( '%1$s', '`' + process.env.prefix + ' settings lang`' ).replaceSave( '%2$s', '`' + process.env.prefix + ' settings wiki`' );
  152. }
  153. if ( args.length ) {
  154. if ( args[0] ) args[0] = args[0].toLowerCase();
  155. args[1] = args.slice(1).join(' ').toLowerCase().trim().replace( /^<(.*)>$/, '$1' );
  156. if ( args[1] && ( args[0] === 'wiki' || args[0] === 'channel' ) ) {
  157. var regex = args[1].match( /^(?:(?:https?:)?\/\/)?([a-z\d-]{1,50})\.gamepedia\.com(?:\/|$)/ );
  158. }
  159. var langs = '\n' + lang.settings.langhelp.replaceSave( '%s', process.env.prefix + ' settings lang' ) + ' `' + Object.values(i18n.allLangs[1]).join(', ') + '`';
  160. var wikis = '\n' + lang.settings.wikihelp.replaceSave( '%s', process.env.prefix + ' settings wiki' );
  161. var channels = '\n' + lang.settings.wikihelp.replaceSave( '%s', process.env.prefix + ' settings channel' );
  162. var nolangs = lang.settings.langinvalid + langs;
  163. var nowikis = lang.settings.wikiinvalid + wikis;
  164. var nochannels = lang.settings.wikiinvalid + channels;
  165. if ( msg.guild.id in settings ) {
  166. var current = args[0] + ( line === 'changed' ? line : '' );
  167. if ( args[0] === 'lang' ) {
  168. if ( args[1] ) {
  169. if ( args[1] in i18n.allLangs[0] ) edit_settings(lang, msg, 'lang', i18n.allLangs[0][args[1]]);
  170. else msg.replyMsg( nolangs, {}, true );
  171. } else msg.replyMsg( lang.settings[current] + langs, {}, true );
  172. } else if ( args[0] === 'wiki' ) {
  173. if ( args[1] ) {
  174. if ( regex !== null ) edit_settings(lang, msg, 'wiki', 'https://' + regex[1] + '.gamepedia.com/');
  175. else find_wikis(lang, msg, 'wiki', args[1].split(' '), nowikis);
  176. } else msg.replyMsg( lang.settings[current] + ' ' + settings[msg.guild.id].wiki + wikis, {}, true );
  177. } else if ( args[0] === 'channel' ) {
  178. if ( args[1] ) {
  179. if ( regex !== null ) edit_settings(lang, msg, 'channel', 'https://' + regex[1] + '.gamepedia.com/');
  180. else find_wikis(lang, msg, 'channel', args[1].split(' '), nochannels);
  181. } else if ( settings[msg.guild.id].channels && msg.channel.id in settings[msg.guild.id].channels ) {
  182. msg.replyMsg( lang.settings[current] + ' ' + settings[msg.guild.id].channels[msg.channel.id] + channels, {}, true );
  183. } else msg.replyMsg( lang.settings[current] + ' ' + settings[msg.guild.id].wiki + channels, {}, true );
  184. } else msg.replyMsg( text, {}, true );
  185. } else {
  186. if ( args[0] === 'lang' ) {
  187. if ( args[1] ) {
  188. if ( args[1] in i18n.allLangs[0] ) edit_settings(lang, msg, 'lang', i18n.allLangs[0][args[1]]);
  189. else msg.replyMsg( nolangs, {}, true );
  190. } else msg.replyMsg( lang.settings.lang + langs, {}, true );
  191. } else if ( args[0] === 'wiki' || args[0] === 'channel' ) {
  192. if ( args[1] ) {
  193. if ( regex !== null ) edit_settings(lang, msg, 'wiki', 'https://' + regex[1] + '.gamepedia.com/');
  194. else find_wikis(lang, msg, 'wiki', args[1].split(' '), nowikis);
  195. } else msg.replyMsg( lang.settings.wikimissing + wikis, {}, true );
  196. } else msg.replyMsg( text, {}, true );
  197. }
  198. } else msg.replyMsg( text, {}, true );
  199. } else {
  200. msg.reactEmoji('❌');
  201. }
  202. }
  203. function find_wikis(lang, msg, key, value, text) {
  204. if ( value.length === 2 && value[1] === '--force' ) {
  205. msg.reactEmoji('⏳', true).then( function( reaction ) {
  206. request( {
  207. uri: value[0] + 'api.php?action=query&format=json',
  208. json: true
  209. }, function( error, response, body ) {
  210. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !( body instanceof Object ) ) {
  211. console.log( '- ' + ( response && response.statusCode ) + ': Error while reaching the wiki: ' + ( error || body && body.error && body.error.info ) );
  212. msg.reactEmoji('nowiki', true);
  213. if ( reaction ) reaction.removeEmoji();
  214. }
  215. else edit_settings(lang, msg, key, value[0]);
  216. } );
  217. } );
  218. } else if ( allSites.some( site => site.wiki_domain === value.join('') + '.gamepedia.com' ) ) {
  219. edit_settings(lang, msg, key, 'https://' + value.join('') + '.gamepedia.com/');
  220. } else {
  221. var sites = allSites.filter( site => site.wiki_display_name.toLowerCase().includes( value.join(' ') ) );
  222. if ( 0 < sites.length && sites.length < 21 ) {
  223. text += '\n\n' + lang.settings.foundwikis + '\n' + sites.map( site => site.wiki_display_name + ': `' + site.wiki_domain + '`' ).join('\n');
  224. }
  225. msg.replyMsg( text, {split:true}, true );
  226. }
  227. }
  228. function edit_settings(lang, msg, key, value) {
  229. msg.reactEmoji('⏳', true).then( function( reaction ) {
  230. if ( settings === defaultSettings ) {
  231. console.log( '- Error while getting current settings.' );
  232. msg.replyMsg( lang.settings.save_failed, {}, true );
  233. if ( reaction ) reaction.removeEmoji();
  234. }
  235. else {
  236. var temp_settings = JSON.parse(JSON.stringify(settings));
  237. var save = false;
  238. if ( !( msg.guild.id in temp_settings ) ) {
  239. temp_settings[msg.guild.id] = Object.assign({}, settings.default);
  240. save = true;
  241. }
  242. if ( key === 'channel' ) {
  243. if ( !temp_settings[msg.guild.id].channels ) temp_settings[msg.guild.id].channels = {};
  244. if ( temp_settings[msg.guild.id].channels[msg.channel.id] !== value ) {
  245. temp_settings[msg.guild.id].channels[msg.channel.id] = value;
  246. save = true;
  247. }
  248. } else if ( temp_settings[msg.guild.id][key] !== value ) {
  249. temp_settings[msg.guild.id][key] = value;
  250. save = true;
  251. }
  252. Object.keys(temp_settings).forEach( function(guild) {
  253. if ( !client.guilds.has(guild) && guild !== 'default' ) {
  254. delete temp_settings[guild];
  255. save = true;
  256. } else {
  257. var channels = temp_settings[guild].channels;
  258. if ( channels ) {
  259. Object.keys(channels).forEach( function(channel) {
  260. if ( channels[channel] === temp_settings[guild].wiki || !client.guilds.get(guild).channels.has(channel) ) {
  261. delete channels[channel];
  262. save = true;
  263. }
  264. } );
  265. if ( !Object.keys(channels).length ) {
  266. delete temp_settings[guild].channels;
  267. save = true;
  268. }
  269. }
  270. }
  271. } );
  272. if ( save ) request.post( {
  273. uri: process.env.save,
  274. headers: access,
  275. body: {
  276. branch: 'master',
  277. commit_message: client.user.username + ': Settings updated.',
  278. actions: [
  279. {
  280. action: 'update',
  281. file_path: process.env.file,
  282. content: JSON.stringify( temp_settings, null, '\t' )
  283. }
  284. ]
  285. },
  286. json: true
  287. }, function( error, response, body ) {
  288. if ( error || !response || response.statusCode !== 201 || !body || body.error ) {
  289. console.log( '- ' + ( response || response.statusCode ) + ': Error while editing the settings: ' + ( error || body && ( body.message || body.error ) ) );
  290. msg.replyMsg( lang.settings.save_failed, {}, true );
  291. }
  292. else {
  293. settings = JSON.parse(JSON.stringify(temp_settings));
  294. if ( key === 'lang' ) lang = i18n[value];
  295. cmd_settings(lang, msg, [key], 'changed');
  296. console.log( '- Settings successfully updated.' );
  297. }
  298. if ( reaction ) reaction.removeEmoji();
  299. } );
  300. else {
  301. cmd_settings(lang, msg, [key], 'changed');
  302. if ( reaction ) reaction.removeEmoji();
  303. }
  304. }
  305. } );
  306. }
  307. function cmd_info(lang, msg, args, line) {
  308. if ( args.join('') ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  309. else {
  310. msg.sendChannel( lang.disclaimer.replaceSave( '%s', ( msg.channel.type === 'text' && msg.guild.members.get(process.env.owner) || '*MarkusRost*' ) ) );
  311. cmd_helpserver(lang, msg);
  312. cmd_invite(lang, msg, args, line);
  313. }
  314. }
  315. function cmd_helpserver(lang, msg) {
  316. msg.sendChannel( lang.helpserver + '\n' + process.env.invite );
  317. }
  318. function cmd_help(lang, msg, args, line) {
  319. if ( msg.channel.type === 'text' && pause[msg.guild.id] && ( args.join('') || !msg.isAdmin() ) ) return;
  320. if ( msg.isAdmin() && !( msg.guild.id in settings ) && settings !== defaultSettings ) {
  321. cmd_settings(lang, msg, [], line);
  322. cmd_helpserver(lang, msg);
  323. }
  324. var cmds = lang.help.list;
  325. var isMinecraft = ( msg.channel.getWiki() === minecraft[lang.lang].link );
  326. var cmdintro = '🔹 `' + process.env.prefix + ' ';
  327. if ( args.join('') ) {
  328. if ( args.join(' ').isMention(msg.guild) ) cmd_helpserver(lang, msg);
  329. else if ( args[0].toLowerCase() === 'admin' ) {
  330. if ( msg.channel.type !== 'text' || msg.isAdmin() ) {
  331. var cmdlist = lang.help.admin + '\n' + cmds.filter( cmd => cmd.admin && !cmd.hide ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  332. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  333. msg.sendChannel( cmdlist, {split:true} );
  334. }
  335. else {
  336. msg.replyMsg( lang.help.noadmin );
  337. }
  338. }
  339. else {
  340. var cmdlist = cmds.filter( cmd => cmd.cmd.split(' ')[0] === args[0].toLowerCase() && !cmd.unsearchable && ( msg.channel.type !== 'text' || !cmd.admin || msg.isAdmin() ) && ( !cmd.minecraft || isMinecraft ) ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  341. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  342. if ( cmdlist === '' ) msg.reactEmoji('❓');
  343. else msg.sendChannel( cmdlist, {split:true} );
  344. }
  345. }
  346. else if ( msg.isAdmin() && pause[msg.guild.id] ) {
  347. var cmdlist = lang.help.pause + '\n' + cmds.filter( cmd => cmd.pause ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n');
  348. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  349. msg.sendChannel( cmdlist, {split:true}, true );
  350. }
  351. else {
  352. var cmdlist = lang.help.all + '\n' + cmds.filter( cmd => !cmd.hide && !cmd.admin && ( !cmd.minecraft || isMinecraft ) ).map( cmd => cmdintro + cmd.cmd + '`\n\t' + cmd.desc ).join('\n') + '\n\n🔸 ' + lang.help.footer;
  353. cmdlist = cmdlist.replaceSave( /@mention/g, '@' + ( msg.channel.type === 'text' ? msg.guild.me.displayName : client.user.username ) );
  354. msg.sendChannel( cmdlist, {split:true} );
  355. }
  356. }
  357. function cmd_say(lang, msg, args, line) {
  358. args = args.toEmojis();
  359. var text = args.join(' ');
  360. if ( args[0] === 'alarm' ) text = '🚨 **' + args.slice(1).join(' ') + '** 🚨';
  361. var imgs = [];
  362. if ( msg.uploadFiles() ) imgs = msg.attachments.map( function(img) {
  363. return {attachment:img.url,name:img.filename};
  364. } );
  365. if ( msg.isOwner() ) {
  366. try {
  367. text = eval( '`' + text + '`' );
  368. } catch ( error ) {
  369. log_error(error);
  370. }
  371. }
  372. if ( text || imgs.length ) {
  373. msg.channel.send( text, {disableEveryone:!msg.member.hasPermission(['MENTION_EVERYONE']),files:imgs} ).then( () => msg.deleteMsg(), error => {
  374. log_error(error);
  375. msg.reactEmoji('error', true);
  376. } );
  377. } else {
  378. args[0] = line.split(' ')[1];
  379. cmd_help(lang, msg, args, line);
  380. }
  381. }
  382. function cmd_umfrage(lang, msg, args, line) {
  383. var imgs = [];
  384. if ( msg.uploadFiles() ) imgs = msg.attachments.map( function(img) {
  385. return {attachment:img.url,name:img.filename};
  386. } );
  387. if ( args.length || imgs.length ) {
  388. var text = args.join(' ').split('\n');
  389. args = text.shift().split(' ');
  390. if ( text.length ) args.push('\n' + text.join('\n'));
  391. var reactions = [];
  392. args = args.toEmojis();
  393. for ( var i = 0; ( i < args.length || imgs.length ); i++ ) {
  394. var reaction = args[i];
  395. var custom = /^<a?:/;
  396. var pattern = /^[\u0000-\u1FFF]{1,4}$/;
  397. if ( !custom.test(reaction) && ( reaction.length > 4 || pattern.test(reaction) ) ) {
  398. cmd_sendumfrage(lang, msg, args.slice(i).join(' ').replace( /^\n| (\n)/, '$1' ), reactions, imgs);
  399. break;
  400. } else if ( reaction !== '' ) {
  401. if ( custom.test(reaction) ) {
  402. reaction = reaction.substring(reaction.lastIndexOf(':') + 1, reaction.length - 1);
  403. }
  404. reactions[i] = reaction;
  405. if ( i === args.length - 1 ) {
  406. cmd_sendumfrage(lang, msg, args.slice(i + 1).join(' ').replace( /^\n| (\n)/, '$1' ), reactions, imgs);
  407. break;
  408. }
  409. }
  410. }
  411. } else {
  412. args[0] = line.split(' ')[1];
  413. cmd_help(lang, msg, args, line);
  414. }
  415. }
  416. function cmd_sendumfrage(lang, msg, text, reactions, imgs) {
  417. msg.channel.send( lang.poll.title + text, {disableEveryone:!msg.member.hasPermission(['MENTION_EVERYONE']),files:imgs} ).then( poll => {
  418. msg.deleteMsg();
  419. if ( reactions.length ) {
  420. reactions.forEach( function(entry) {
  421. poll.react(entry).catch( error => {
  422. log_error(error);
  423. poll.reactEmoji('error');
  424. } );
  425. } );
  426. } else {
  427. poll.reactEmoji('support');
  428. poll.reactEmoji('oppose');
  429. }
  430. }, error => {
  431. log_error(error);
  432. msg.reactEmoji('error');
  433. } );
  434. }
  435. function cmd_test(lang, msg, args, line) {
  436. if ( args.join('') ) {
  437. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  438. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  439. var text = lang.test.text[Math.floor(Math.random() * lang.test.random)] || lang.test.default;
  440. console.log( '- Test: Fully functioning!' );
  441. var now = Date.now();
  442. msg.replyMsg( text ).then( edit => {
  443. var then = Date.now();
  444. var embed = new Discord.RichEmbed().setTitle( lang.test.time ).addField( 'Discord', ( then - now ) + 'ms' );
  445. now = Date.now();
  446. request( {
  447. uri: msg.channel.getWiki() + 'api.php?action=query&format=json',
  448. json: true
  449. }, function( error, response, body ) {
  450. then = Date.now();
  451. if ( body && body.warnings ) log_warn(body.warnings);
  452. var ping = ( then - now ) + 'ms';
  453. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !( body instanceof Object ) ) {
  454. if ( response && response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' ) {
  455. console.log( '- This wiki doesn\'t exist! ' + ( error || body && body.error && body.error.info || '' ) );
  456. ping += ' <:unknown_wiki:505887262077353984>';
  457. }
  458. else {
  459. console.log( '- ' + ( response && response.statusCode ) + ': Error while reaching the wiki: ' + ( error || body && body.error && body.error.info ) );
  460. ping += ' <:error:505887261200613376>';
  461. }
  462. }
  463. embed.addField( msg.channel.getWiki(), ping );
  464. if ( edit ) edit.edit( edit.content, embed ).catch(log_error);
  465. } );
  466. } );
  467. } else {
  468. console.log( '- Test: Paused!' );
  469. msg.replyMsg( lang.test.pause, {}, true );
  470. }
  471. }
  472. function cmd_invite(lang, msg, args, line) {
  473. if ( args.join('') ) {
  474. cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  475. } else {
  476. client.generateInvite(defaultPermissions).then( invite => msg.sendChannel( lang.invite.bot + '\n<' + invite + '>' ), log_error );
  477. }
  478. }
  479. async function cmd_eval(lang, msg, args, line) {
  480. try {
  481. var text = util.inspect( await eval( args.join(' ') ) );
  482. } catch ( error ) {
  483. var text = error.name + ': ' + error.message;
  484. }
  485. if ( isDebug ) console.log( '--- EVAL START ---\n' + text + '\n--- EVAL END ---' );
  486. if ( text.length > 2000 ) msg.reactEmoji('✅', true);
  487. else msg.sendChannel( '```js\n' + text + '\n```', {split:{prepend:'```js\n',append:'\n```'}}, true );
  488. }
  489. async function cmd_stop(lang, msg, args, line) {
  490. if ( args.join(' ').split('\n')[0].isMention(msg.guild) ) {
  491. await msg.replyMsg( 'I\'ll destroy myself now!', {}, true );
  492. await client.destroy();
  493. console.log( '- I\'m now shutting down!' );
  494. setTimeout( async () => {
  495. console.log( '- I need to long to close, terminating!' );
  496. process.exit(1);
  497. }, 1000 ).unref();
  498. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  499. cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  500. }
  501. }
  502. function cmd_pause(lang, msg, args, line) {
  503. if ( msg.channel.type === 'text' && args.join(' ').split('\n')[0].isMention(msg.guild) && ( msg.isAdmin() || msg.isOwner() ) ) {
  504. if ( pause[msg.guild.id] ) {
  505. delete pause[msg.guild.id];
  506. console.log( '- Pause ended.' );
  507. msg.replyMsg( lang.pause.off, {}, true );
  508. } else {
  509. msg.replyMsg( lang.pause.on, {}, true );
  510. console.log( '- Pause started.' );
  511. pause[msg.guild.id] = true;
  512. }
  513. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  514. cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  515. }
  516. }
  517. function cmd_delete(lang, msg, args, line) {
  518. if ( msg.channel.memberPermissions(msg.member).has('MANAGE_MESSAGES') ) {
  519. if ( /^\d+$/.test(args[0]) && parseInt(args[0], 10) + 1 > 0 ) {
  520. if ( parseInt(args[0], 10) > 99 ) {
  521. msg.replyMsg( lang.delete.big.replace( '%s', '`99`' ), {}, true );
  522. }
  523. else {
  524. msg.channel.bulkDelete(parseInt(args[0], 10) + 1, true).then( messages => {
  525. msg.reply( lang.delete.success.replace( '%s', messages.size - 1 ) ).then( antwort => antwort.deleteMsg(5000), log_error );
  526. console.log( '- The last ' + ( messages.size - 1 ) + ' messages in #' + msg.channel.name + ' were deleted by @' + msg.member.displayName + '!' );
  527. }, log_error );
  528. }
  529. }
  530. else {
  531. msg.replyMsg( lang.delete.invalid, {}, true );
  532. }
  533. }
  534. else {
  535. msg.reactEmoji('❌');
  536. }
  537. }
  538. function cmd_link(lang, msg, title, wiki = msg.channel.getWiki(), cmd = ' ') {
  539. if ( cmd === ' ' && msg.isAdmin() && !( msg.guild.id in settings ) && settings !== defaultSettings ) {
  540. cmd_settings(lang, msg, [], '');
  541. }
  542. if ( /^\|\|(?:(?!\|\|).)+\|\|$/.test(title) ) {
  543. title = title.substring( 2, title.length - 2);
  544. var spoiler = '||';
  545. }
  546. msg.reactEmoji('⏳').then( reaction => check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler) );
  547. }
  548. function check_wiki(lang, msg, title, wiki, cmd, reaction, spoiler = '', querystring = '', fragment = '', selfcall = 0) {
  549. if ( title.includes( '#' ) ) {
  550. fragment = title.split('#').slice(1).join('#');
  551. title = title.split('#')[0];
  552. }
  553. if ( /\?\w+=/.test(title) ) {
  554. var querystart = title.search(/\?\w+=/);
  555. querystring = title.substring(querystart + 1) + ( querystring ? '&' + querystring : '' );
  556. title = title.substring(0, querystart);
  557. }
  558. var linksuffix = ( querystring ? '?' + querystring.toTitle() : '' ) + ( fragment ? '#' + fragment.toSection() : '' );
  559. if ( title.length > 300 ) {
  560. title = title.substring(0, 300);
  561. msg.reactEmoji('⚠');
  562. }
  563. var invoke = title.split(' ')[0].toLowerCase();
  564. var args = title.split(' ').slice(1);
  565. var mclang = minecraft[lang.lang];
  566. var aliasInvoke = ( mclang.aliase[invoke] || invoke );
  567. if ( !msg.notminecraft && wiki === mclang.link && ( aliasInvoke in minecraftcmdmap || invoke.startsWith( '/' ) ) ) {
  568. if ( aliasInvoke in minecraftcmdmap ) minecraftcmdmap[aliasInvoke](lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler);
  569. else cmd_befehl(lang, mclang, msg, invoke.substring(1), args, title, cmd, querystring, fragment, reaction, spoiler);
  570. }
  571. else if ( ( invoke === 'random' || invoke === '🎲' || invoke === lang.search.random ) && !args.join('') && !linksuffix ) cmd_random(lang, msg, wiki, reaction, spoiler);
  572. else if ( ( invoke === 'overview' || invoke === lang.search.overview ) && !args.join('') && !linksuffix && wiki.endsWith( '.gamepedia.com/' ) ) cmd_overview(lang, msg, wiki, reaction, spoiler);
  573. else if ( invoke === 'page' || invoke === lang.search.page ) {
  574. msg.sendChannel( spoiler + '<' + wiki.toLink() + args.join('_').toTitle() + linksuffix + '>' + spoiler );
  575. if ( reaction ) reaction.removeEmoji();
  576. }
  577. else if ( invoke === 'search' || invoke === lang.search.search ) {
  578. linksuffix = ( linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  579. msg.sendChannel( spoiler + '<' + wiki.toLink() + 'Special:Search?search=' + args.join(' ').toSearch() + linksuffix + '>' + spoiler );
  580. if ( reaction ) reaction.removeEmoji();
  581. }
  582. else if ( invoke === 'diff' && args.join('') ) cmd_diff(lang, msg, args, wiki, reaction, spoiler);
  583. else {
  584. var noRedirect = ( /(?:^|&)redirect=no(?:&|$)/.test(querystring) || /(?:^|&)action=(?!view(?:&|$))/.test(querystring) );
  585. request( {
  586. 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',
  587. json: true
  588. }, function( error, response, body ) {
  589. if ( body && body.warnings ) log_warn(body.warnings);
  590. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  591. if ( response && response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' ) {
  592. console.log( '- This wiki doesn\'t exist! ' + ( error || body && body.error && body.error.info ) );
  593. msg.reactEmoji('nowiki');
  594. }
  595. else {
  596. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  597. msg.sendChannelError( spoiler + '<' + wiki.toLink() + ( linksuffix || !title ? title.toTitle() + linksuffix : 'Special:Search?search=' + title.toSearch() ) + '>' + spoiler );
  598. }
  599. if ( reaction ) reaction.removeEmoji();
  600. }
  601. else {
  602. if ( body.query.pages ) {
  603. var querypages = Object.values(body.query.pages);
  604. var querypage = querypages[0];
  605. 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, '_' ) ) ) {
  606. querypage.title = body.query.redirects[0].from;
  607. delete body.query.redirects[0].tofragment;
  608. delete querypage.missing;
  609. querypage.ns = -1;
  610. querypage.special = '';
  611. }
  612. if ( querypages.length !== 1 ) querypage = {
  613. title: title,
  614. invalidreason: 'The requested page title contains invalid characters: "|".',
  615. invalid: ''
  616. }
  617. var contribs = body.query.namespaces['-1']['*'] + ':' + body.query.specialpagealiases.find( sp => sp.realname === 'Contributions' ).aliases[0] + '/';
  618. 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) ) ) {
  619. var userparts = querypage.title.split(':');
  620. querypage.noRedirect = noRedirect;
  621. cmd_user(lang, msg, userparts[0].toTitle() + ':', userparts.slice(1).join(':'), wiki, linksuffix, querypage, contribs.toTitle(), reaction, spoiler);
  622. }
  623. else if ( querypage.ns === -1 && querypage.title.startsWith( contribs ) && querypage.title.length > contribs.length ) {
  624. var username = querypage.title.split('/').slice(1).join('/');
  625. request( {
  626. uri: wiki + 'api.php?action=query&titles=User:' + encodeURIComponent( username ) + '&format=json',
  627. json: true
  628. }, function( uerror, uresponse, ubody ) {
  629. if ( uerror || !uresponse || uresponse.statusCode !== 200 || !ubody || ubody.batchcomplete === undefined || !ubody.query ) {
  630. console.log( '- ' + ( uresponse && uresponse.statusCode ) + ': Error while getting the user: ' + ( uerror || ubody && ubody.error && ubody.error.info ) );
  631. msg.sendChannelError( spoiler + '<' + wiki.toLink() + ( contribs + username ).toTitle() + linksuffix + '>' + spoiler );
  632. if ( reaction ) reaction.removeEmoji();
  633. }
  634. else {
  635. querypage = Object.values(ubody.query.pages)[0];
  636. if ( querypage.ns === 2 ) {
  637. username = querypage.title.split(':').slice(1).join(':');
  638. querypage.title = contribs + username;
  639. delete querypage.missing;
  640. querypage.ns = -1;
  641. querypage.special = '';
  642. querypage.noRedirect = noRedirect;
  643. cmd_user(lang, msg, contribs.toTitle(), username, wiki, linksuffix, querypage, contribs.toTitle(), reaction, spoiler);
  644. }
  645. else {
  646. msg.reactEmoji('error');
  647. if ( reaction ) reaction.removeEmoji();
  648. }
  649. }
  650. } );
  651. }
  652. else if ( ( querypage.missing !== undefined && querypage.known === undefined && !( noRedirect || querypage.categoryinfo ) ) || querypage.invalid !== undefined ) {
  653. request( {
  654. 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',
  655. json: true
  656. }, function( srerror, srresponse, srbody ) {
  657. if ( srbody && srbody.warnings ) log_warn(srbody.warnings);
  658. if ( srerror || !srresponse || srresponse.statusCode !== 200 || !srbody || srbody.batchcomplete === undefined ) {
  659. console.log( '- ' + ( srresponse && srresponse.statusCode ) + ': Error while getting the search results: ' + ( srerror || srbody && srbody.error && srbody.error.info ) );
  660. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Search?search=' + title.toSearch() + '>' + spoiler );
  661. }
  662. else {
  663. if ( !srbody.query ) {
  664. msg.reactEmoji('🤷');
  665. }
  666. else {
  667. querypage = Object.values(srbody.query.pages)[0];
  668. var pagelink = wiki.toLink() + querypage.title.toTitle() + linksuffix;
  669. var text = '';
  670. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  671. if ( querypage.pageprops && querypage.pageprops.displaytitle ) embed.setTitle( querypage.pageprops.displaytitle.escapeFormatting() );
  672. if ( querypage.pageprops && querypage.pageprops.description ) {
  673. var description = '';
  674. var parser = new htmlparser.Parser( {
  675. ontext: (htmltext) => {
  676. description += htmltext.escapeFormatting();
  677. }
  678. }, {decodeEntities:true} );
  679. parser.write( querypage.pageprops.description );
  680. parser.end();
  681. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  682. embed.setDescription( description );
  683. }
  684. else if ( querypage.extract ) {
  685. var extract = querypage.extract.escapeFormatting();
  686. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  687. embed.setDescription( extract );
  688. }
  689. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  690. var pageimage = querypage.original.source;
  691. if ( querypage.ns === 6 ) {
  692. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.pageimage.toLowerCase()) ) embed.setImage( pageimage );
  693. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.pageimage}] );
  694. } else embed.setThumbnail( pageimage );
  695. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  696. if ( title.replace( /\-/g, ' ' ).toTitle().toLowerCase() === querypage.title.replace( /\-/g, ' ' ).toTitle().toLowerCase() ) {
  697. text = '';
  698. }
  699. else if ( !srbody.continue ) {
  700. text = '\n' + lang.search.infopage.replaceSave( '%s', '`' + process.env.prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' );
  701. }
  702. else {
  703. text = '\n' + lang.search.infosearch.replaceSave( '%1$s', '`' + process.env.prefix + cmd + lang.search.page + ' ' + title + linksuffix + '`' ).replaceSave( '%2$s', '`' + process.env.prefix + cmd + lang.search.search + ' ' + title + linksuffix + '`' );
  704. }
  705. if ( querypage.categoryinfo ) {
  706. var langCat = lang.search.category;
  707. var category = [langCat.content];
  708. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  709. if ( querypage.categoryinfo.pages > 0 ) {
  710. var pages = querypage.categoryinfo.pages;
  711. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  712. }
  713. if ( querypage.categoryinfo.files > 0 ) {
  714. var files = querypage.categoryinfo.files;
  715. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  716. }
  717. if ( querypage.categoryinfo.subcats > 0 ) {
  718. var subcats = querypage.categoryinfo.subcats;
  719. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  720. }
  721. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  722. else text += '\n\n' + category.join('\n');
  723. }
  724. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, embed );
  725. }
  726. }
  727. if ( reaction ) reaction.removeEmoji();
  728. } );
  729. }
  730. else {
  731. var pagelink = wiki.toLink() + querypage.title.toTitle() + ( querystring ? '?' + querystring.toTitle() : '' ) + ( body.query.redirects && body.query.redirects[0].tofragment ? '#' + body.query.redirects[0].tofragment.toSection() : ( fragment ? '#' + fragment.toSection() : '' ) );
  732. var text = '';
  733. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  734. if ( querypage.pageprops && querypage.pageprops.displaytitle ) embed.setTitle( querypage.pageprops.displaytitle.escapeFormatting() );
  735. if ( querypage.pageprops && querypage.pageprops.description ) {
  736. var description = '';
  737. var parser = new htmlparser.Parser( {
  738. ontext: (htmltext) => {
  739. description += htmltext.escapeFormatting();
  740. }
  741. }, {decodeEntities:true} );
  742. parser.write( querypage.pageprops.description );
  743. parser.end();
  744. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  745. embed.setDescription( description );
  746. }
  747. else if ( querypage.extract ) {
  748. var extract = querypage.extract.escapeFormatting();
  749. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  750. embed.setDescription( extract );
  751. }
  752. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  753. var pageimage = querypage.original.source;
  754. if ( querypage.ns === 6 ) {
  755. if ( msg.showEmbed() && /\.(?:png|jpg|jpeg|gif)$/.test(querypage.pageimage.toLowerCase()) ) embed.setImage( pageimage );
  756. else if ( msg.uploadFiles() ) embed.attachFiles( [{attachment:pageimage,name:( spoiler ? 'SPOILER ' : '' ) + querypage.pageimage}] );
  757. } else embed.setThumbnail( pageimage );
  758. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  759. if ( querypage.categoryinfo ) {
  760. var langCat = lang.search.category;
  761. var category = [langCat.content];
  762. if ( querypage.categoryinfo.size === 0 ) category.push(langCat.empty);
  763. if ( querypage.categoryinfo.pages > 0 ) {
  764. var pages = querypage.categoryinfo.pages;
  765. category.push(( langCat.pages[pages] || langCat.pages['*' + pages % 100] || langCat.pages['*' + pages % 10] || langCat.pages.default ).replaceSave( '%s', pages ));
  766. }
  767. if ( querypage.categoryinfo.files > 0 ) {
  768. var files = querypage.categoryinfo.files;
  769. category.push(( langCat.files[files] || langCat.files['*' + files % 100] || langCat.files['*' + files % 10] || langCat.files.default ).replaceSave( '%s', files ));
  770. }
  771. if ( querypage.categoryinfo.subcats > 0 ) {
  772. var subcats = querypage.categoryinfo.subcats;
  773. category.push(( langCat.subcats[subcats] || langCat.subcats['*' + subcats % 100] || langCat.subcats['*' + subcats % 10] || langCat.subcats.default ).replaceSave( '%s', subcats ));
  774. }
  775. if ( msg.showEmbed() ) embed.addField( category[0], category.slice(1).join('\n') );
  776. else text += '\n\n' + category.join('\n');
  777. }
  778. msg.sendChannel( spoiler + '<' + pagelink + '>' + text + spoiler, embed );
  779. if ( reaction ) reaction.removeEmoji();
  780. }
  781. }
  782. else if ( body.query.interwiki ) {
  783. var inter = body.query.interwiki[0];
  784. var intertitle = inter.title.substring(inter.iw.length + 1);
  785. var regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50})\.gamepedia\.com\// );
  786. if ( regex !== null && selfcall < 5 ) {
  787. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  788. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  789. selfcall++;
  790. check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + '.gamepedia.com/', ' !' + regex[1] + ' ', reaction, spoiler, querystring, fragment, selfcall);
  791. } else {
  792. if ( reaction ) reaction.removeEmoji();
  793. console.log( '- Aborted, paused.' );
  794. }
  795. } else {
  796. regex = inter.url.match( /^(?:https?:)?\/\/([a-z\d-]{1,50}\.(?:wikipedia|mediawiki|wiktionary|wikimedia|wikibooks|wikisource|wikidata|wikiversity|wikiquote|wikinews|wikivoyage)\.org\/)wiki\// );
  797. if ( regex !== null && selfcall < 5 ) {
  798. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  799. var iwtitle = decodeURIComponent( inter.url.replace( regex[0], '' ) ).replace( /\_/g, ' ' ).replaceSave( intertitle.replace( /\_/g, ' ' ), intertitle );
  800. selfcall++;
  801. check_wiki(lang, msg, iwtitle, 'https://' + regex[1] + 'w/', cmd + inter.iw + ':', reaction, spoiler, querystring, fragment, selfcall);
  802. } else {
  803. if ( reaction ) reaction.removeEmoji();
  804. console.log( '- Aborted, paused.' );
  805. }
  806. } else {
  807. if ( fragment ) fragment = '#' + fragment.toSection();
  808. if ( inter.url.includes( '#' ) ) {
  809. if ( !fragment ) fragment = '#' + inter.url.split('#').slice(1).join('#');
  810. inter.url = inter.url.split('#')[0];
  811. }
  812. if ( querystring ) inter.url += ( inter.url.includes( '?' ) ? '&' : '?' ) + querystring.toTitle();
  813. msg.sendChannel( spoiler + ' ' + inter.url.replace( /@(here|everyone)/g, '%40$1' ) + fragment + ' ' + spoiler ).then( message => {
  814. if ( message && selfcall === 5 ) message.reactEmoji('⚠');
  815. } );
  816. if ( reaction ) reaction.removeEmoji();
  817. }
  818. }
  819. }
  820. else {
  821. var pagelink = wiki.toLink() + body.query.general.mainpage.toTitle() + linksuffix;
  822. 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 );
  823. request( {
  824. 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',
  825. json: true
  826. }, function( mperror, mpresponse, mpbody ) {
  827. if ( mpbody && mpbody.warnings ) log_warn(body.warnings);
  828. if ( mperror || !mpresponse || mpresponse.statusCode !== 200 || !mpbody || mpbody.batchcomplete === undefined || !mpbody.query ) {
  829. console.log( '- ' + ( mpresponse && mpresponse.statusCode ) + ': Error while getting the main page: ' + ( mperror || mpbody && mpbody.error && mpbody.error.info ) );
  830. } else {
  831. querypage = Object.values(mpbody.query.pages)[0];
  832. if ( querypage.pageprops && querypage.pageprops.displaytitle ) embed.setTitle( querypage.pageprops.displaytitle.escapeFormatting() );
  833. if ( querypage.pageprops && querypage.pageprops.description ) {
  834. var description = '';
  835. var parser = new htmlparser.Parser( {
  836. ontext: (htmltext) => {
  837. description += htmltext.escapeFormatting();
  838. }
  839. }, {decodeEntities:true} );
  840. parser.write( querypage.pageprops.description );
  841. parser.end();
  842. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  843. embed.setDescription( description );
  844. }
  845. else if ( querypage.extract ) {
  846. var extract = querypage.extract.escapeFormatting();
  847. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  848. embed.setDescription( extract );
  849. }
  850. }
  851. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  852. if ( reaction ) reaction.removeEmoji();
  853. } );
  854. }
  855. }
  856. } );
  857. }
  858. }
  859. function cmd_user(lang, msg, namespace, username, wiki, linksuffix, querypage, contribs, reaction, spoiler) {
  860. if ( /^(?:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{2})?|(?:[\dA-F]{1,4}:){7}[\dA-F]{1,4}(?:\/\d{2,3})?)$/.test(username) ) {
  861. request( {
  862. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=blocks&bkprop=user|by|timestamp|expiry|reason&bkip=' + encodeURIComponent( username ) + '&format=json',
  863. json: true
  864. }, function( error, response, body ) {
  865. if ( body && body.warnings ) log_warn(body.warnings);
  866. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.blocks ) {
  867. if ( response && response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' ) {
  868. console.log( '- This wiki doesn\'t exist! ' + ( error || body && body.error && body.error.info ) );
  869. msg.reactEmoji('nowiki');
  870. }
  871. else if ( body && body.error && ( body.error.code === 'param_ip' || body.error.code === 'cidrtoobroad' ) ) {
  872. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('error');
  873. else {
  874. var pagelink = wiki.toLink() + querypage.title.toTitle() + linksuffix;
  875. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  876. if ( querypage.pageprops && querypage.pageprops.displaytitle ) embed.setTitle( querypage.pageprops.displaytitle.escapeFormatting() );
  877. if ( querypage.extract ) {
  878. var extract = querypage.extract.escapeFormatting();
  879. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  880. embed.setDescription( extract );
  881. }
  882. if ( querypage.pageimage && querypage.original ) {
  883. var pageimage = querypage.original.source;
  884. embed.setThumbnail( pageimage );
  885. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  886. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  887. }
  888. }
  889. else {
  890. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  891. msg.sendChannelError( spoiler + '<' + wiki.toLink() + ( querypage.noRedirect ? namespace : contribs ) + username.toTitle() + linksuffix + '>' + spoiler );
  892. }
  893. if ( reaction ) reaction.removeEmoji();
  894. }
  895. else {
  896. if ( !querypage.noRedirect || ( querypage.missing === undefined && querypage.ns !== -1 ) ) namespace = contribs;
  897. var blocks = body.query.blocks.map( function(block) {
  898. var isBlocked = false;
  899. var blockedtimestamp = new Date(block.timestamp).toLocaleString(lang.user.dateformat, timeoptions);
  900. var blockexpiry = block.expiry;
  901. if ( blockexpiry === 'infinity' ) {
  902. blockexpiry = lang.user.block.until_infinity;
  903. isBlocked = true;
  904. } else if ( blockexpiry ) {
  905. if ( Date.parse(blockexpiry) > Date.now() ) isBlocked = true;
  906. blockexpiry = new Date(blockexpiry).toLocaleString(lang.user.dateformat, timeoptions);
  907. }
  908. if ( isBlocked ) return [lang.user.block.header.replaceSave( '%s', block.user ), lang.user.block.text.replaceSave( '%1$s', blockedtimestamp ).replaceSave( '%2$s', blockexpiry ).replaceSave( '%3$s', '[[User:' + block.by + '|' + block.by + ']]' ).replaceSave( '%4$s', block.reason )];
  909. } ).filter( block => block !== undefined );
  910. if ( username.includes( '/' ) ) {
  911. var rangeprefix = username;
  912. if ( username.includes( ':' ) ) {
  913. var range = parseInt(username.replace( /^.+\/(\d{2,3})$/, '$1' ), 10);
  914. if ( range === 128 ) username = username.replace( /^(.+)\/\d{2,3}$/, '$1' );
  915. else if ( range >= 112 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){7}).+$/, '$1' );
  916. else if ( range >= 96 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){6}).+$/, '$1' );
  917. else if ( range >= 80 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){5}).+$/, '$1' );
  918. else if ( range >= 64 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){4}).+$/, '$1' );
  919. else if ( range >= 48 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){3}).+$/, '$1' );
  920. else if ( range >= 32 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){2}).+$/, '$1' );
  921. else if ( range >= 19 ) rangeprefix = username.replace( /^((?:[\dA-F]{1,4}:){1}).+$/, '$1' );
  922. }
  923. else {
  924. var range = parseInt(username.substring(username.length - 2), 10);
  925. if ( range === 32 ) username = username.replace( /^(.+)\/\d{2}$/, '$1' );
  926. else if ( range >= 24 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){3}).+$/, '$1' );
  927. else if ( range >= 16 ) rangeprefix = username.replace( /^((?:\d{1,3}\.){2}).+$/, '$1' );
  928. }
  929. }
  930. request( {
  931. uri: wiki + 'api.php?action=query&list=usercontribs&ucprop=&uclimit=50' + ( username.includes( '/' ) ? '&ucuserprefix=' + encodeURIComponent( rangeprefix ) : '&ucuser=' + encodeURIComponent( username ) ) + '&format=json',
  932. json: true
  933. }, function( ucerror, ucresponse, ucbody ) {
  934. if ( rangeprefix && !username.includes( '/' ) ) username = rangeprefix;
  935. if ( ucbody && ucbody.warnings ) log_warn(ucbody.warnings);
  936. if ( ucerror || !ucresponse || ucresponse.statusCode !== 200 || !ucbody || ucbody.batchcomplete === undefined || !ucbody.query || !ucbody.query.usercontribs ) {
  937. if ( ucbody && ucbody.error && ucbody.error.code === 'baduser_ucuser' ) {
  938. msg.reactEmoji('error');
  939. }
  940. else {
  941. console.log( '- ' + ( ucresponse && ucresponse.statusCode ) + ': Error while getting the search results: ' + ( ucerror || ucbody && ucbody.error && ucbody.error.info ) );
  942. msg.sendChannelError( spoiler + '<' + wiki.toLink() + namespace + username.toTitle() + linksuffix + '>' + spoiler );
  943. }
  944. }
  945. else {
  946. var editcount = [lang.user.info.editcount, ( username.includes( '/' ) && ( ( username.includes( ':' ) && range % 16 ) || range % 8 ) ? '~' : '' ) + ucbody.query.usercontribs.length + ( ucbody.continue ? '+' : '' )];
  947. var pagelink = wiki.toLink() + namespace + username.toTitle() + linksuffix;
  948. if ( msg.showEmbed() ) {
  949. var text = '<' + pagelink + '>';
  950. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( username ).setURL( pagelink ).addField( editcount[0], '[' + editcount[1] + '](' + wiki.toLink() + contribs + username.toTitle() + ')' );
  951. if ( blocks.length ) blocks.forEach( block => embed.addField( block[0], block[1].toMarkdown(wiki) ) );
  952. }
  953. else {
  954. var embed = {};
  955. var text = '<' + pagelink + '>\n\n' + editcount.join(' ');
  956. if ( blocks.length ) blocks.forEach( block => text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext() );
  957. }
  958. msg.sendChannel( spoiler + text + spoiler, embed );
  959. }
  960. if ( reaction ) reaction.removeEmoji();
  961. } );
  962. }
  963. } );
  964. } else {
  965. request( {
  966. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general&list=users&usprop=blockinfo|groups|editcount|registration|gender&ususers=' + encodeURIComponent( username ) + '&format=json',
  967. json: true
  968. }, function( error, response, body ) {
  969. if ( body && body.warnings ) log_warn(body.warnings);
  970. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.users[0] ) {
  971. if ( response && response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' ) {
  972. console.log( '- This wiki doesn\'t exist! ' + ( error || body && body.error && body.error.info ) );
  973. msg.reactEmoji('nowiki');
  974. }
  975. else {
  976. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  977. msg.sendChannelError( spoiler + '<' + wiki.toLink() + namespace + username.toTitle() + linksuffix + '>' + spoiler );
  978. }
  979. }
  980. else {
  981. if ( body.query.users[0].missing !== undefined || body.query.users[0].invalid !== undefined ) {
  982. if ( querypage.missing !== undefined || querypage.ns === -1 ) msg.reactEmoji('🤷');
  983. else {
  984. var pagelink = wiki.toLink() + querypage.title.toTitle() + linksuffix;
  985. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  986. if ( querypage.pageprops && querypage.pageprops.displaytitle ) embed.setTitle( querypage.pageprops.displaytitle.escapeFormatting() );
  987. if ( querypage.extract ) {
  988. var extract = querypage.extract.escapeFormatting();
  989. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  990. embed.setDescription( extract );
  991. }
  992. if ( querypage.pageimage && querypage.original ) {
  993. var pageimage = querypage.original.source;
  994. embed.setThumbnail( pageimage );
  995. } else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  996. msg.sendChannel( spoiler + '<' + pagelink + '>' + spoiler, embed );
  997. }
  998. if ( reaction ) reaction.removeEmoji();
  999. }
  1000. else {
  1001. username = body.query.users[0].name;
  1002. var gender = [lang.user.info.gender];
  1003. switch (body.query.users[0].gender) {
  1004. case 'male':
  1005. gender.push(lang.user.gender.male);
  1006. break;
  1007. case 'female':
  1008. gender.push(lang.user.gender.female);
  1009. break;
  1010. default:
  1011. gender.push(lang.user.gender.unknown);
  1012. }
  1013. var registration = [lang.user.info.registration, new Date(body.query.users[0].registration).toLocaleString(lang.user.dateformat, timeoptions)];
  1014. var editcount = [lang.user.info.editcount, body.query.users[0].editcount];
  1015. var groups = body.query.users[0].groups;
  1016. var group = [lang.user.info.group];
  1017. for ( var i = 0; i < lang.user.groups.length; i++ ) {
  1018. if ( groups.includes( lang.user.groups[i][0] ) ) {
  1019. var thisSite = allSites.find( site => site.wiki_domain === body.query.general.servername );
  1020. if ( lang.user.groups[i][0] === 'hydra_staff' && thisSite && thisSite.wiki_managers.includes( username ) ) group.push(lang.user.manager);
  1021. else group.push(lang.user.groups[i][1]);
  1022. break;
  1023. }
  1024. }
  1025. var isBlocked = false;
  1026. var blockedtimestamp = new Date(body.query.users[0].blockedtimestamp).toLocaleString(lang.user.dateformat, timeoptions);
  1027. var blockexpiry = body.query.users[0].blockexpiry;
  1028. if ( blockexpiry === 'infinity' ) {
  1029. blockexpiry = lang.user.block.until_infinity;
  1030. isBlocked = true;
  1031. } else if ( blockexpiry ) {
  1032. var blockexpirydate = blockexpiry.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2,3})/, '$1-$2-$3T$4:$5:$6Z');
  1033. blockexpiry = new Date(blockexpirydate).toLocaleString(lang.user.dateformat, timeoptions);
  1034. if ( Date.parse(blockexpirydate) > Date.now() ) isBlocked = true;
  1035. }
  1036. var blockedby = '[[User:' + body.query.users[0].blockedby + '|' + body.query.users[0].blockedby + ']]';
  1037. var blockreason = body.query.users[0].blockreason;
  1038. var block = [lang.user.block.header.replaceSave( '%s', username ), lang.user.block.text.replaceSave( '%1$s', blockedtimestamp ).replaceSave( '%2$s', blockexpiry ).replaceSave( '%3$s', blockedby ).replaceSave( '%4$s', blockreason )];
  1039. var pagelink = wiki.toLink() + namespace + username.toTitle() + linksuffix;
  1040. if ( msg.showEmbed() ) {
  1041. var text = '<' + pagelink + '>';
  1042. 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 ).addField( group[0], group[1], true ).addField( gender[0], gender[1], true ).addField( registration[0], registration[1], true );
  1043. }
  1044. else {
  1045. var embed = {};
  1046. var text = '<' + pagelink + '>\n\n' + gender.join(' ') + '\n' + registration.join(' ') + '\n' + editcount.join(' ') + '\n' + group.join(' ');
  1047. }
  1048. if ( wiki.endsWith( '.gamepedia.com/' ) ) request( {
  1049. uri: wiki + 'api.php?action=profile&do=getPublicProfile&user_name=' + encodeURIComponent( username ) + '&format=json',
  1050. json: true
  1051. }, function( perror, presponse, pbody ) {
  1052. if ( perror || !presponse || presponse.statusCode !== 200 || !pbody || pbody.error || pbody.errormsg || !pbody.profile ) {
  1053. console.log( '- ' + ( presponse && presponse.statusCode ) + ': Error while getting the user profile: ' + ( perror || pbody && ( pbody.error && pbody.error.info || pbody.errormsg ) ) );
  1054. }
  1055. else if ( pbody.profile['link-discord'] ) {
  1056. var discordmember = msg.guild.members.find( member => member.user.tag === pbody.profile['link-discord'] );
  1057. var discordname = [lang.user.info.discord,pbody.profile['link-discord'].escapeFormatting()];
  1058. if ( discordmember ) {
  1059. if ( msg.showEmbed() ) discordname[1] = discordmember.toString();
  1060. else if ( discordmember.nickname ) discordname[1] += ' (' + discordmember.nickname.escapeFormatting() + ')';
  1061. }
  1062. if ( msg.showEmbed() ) embed.addField( discordname[0], discordname[1], true );
  1063. else text += '\n' + discordname.join(' ');
  1064. }
  1065. if ( isBlocked ) {
  1066. if ( msg.showEmbed() ) embed.addField( block[0], block[1].toMarkdown(wiki) );
  1067. else text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  1068. }
  1069. msg.sendChannel( spoiler + text + spoiler, embed );
  1070. if ( reaction ) reaction.removeEmoji();
  1071. } );
  1072. else {
  1073. if ( isBlocked ) {
  1074. if ( msg.showEmbed() ) embed.addField( block[0], block[1].toMarkdown(wiki) );
  1075. else text += '\n\n**' + block[0] + '**\n' + block[1].toPlaintext();
  1076. }
  1077. msg.sendChannel( spoiler + text + spoiler, embed );
  1078. if ( reaction ) reaction.removeEmoji();
  1079. }
  1080. }
  1081. }
  1082. } );
  1083. }
  1084. }
  1085. function cmd_diff(lang, msg, args, wiki, reaction, spoiler) {
  1086. if ( args[0] ) {
  1087. var error = false;
  1088. var title = '';
  1089. var revision = 0;
  1090. var diff = 0;
  1091. var relative = 'prev';
  1092. if ( /^\d+$/.test(args[0]) ) {
  1093. revision = parseInt(args[0], 10);
  1094. if ( args[1] ) {
  1095. if ( /^\d+$/.test(args[1]) ) {
  1096. diff = parseInt(args[1], 10);
  1097. }
  1098. else if ( args[1] === 'prev' || args[1] === 'next' || args[1] === 'cur' ) {
  1099. relative = args[1];
  1100. }
  1101. else error = true;
  1102. }
  1103. }
  1104. else if ( args[0] === 'prev' || args[0] === 'next' || args[0] === 'cur' ) {
  1105. relative = args[0];
  1106. if ( args[1] ) {
  1107. if ( /^\d+$/.test(args[1]) ) {
  1108. revision = parseInt(args[1], 10);
  1109. }
  1110. else error = true;
  1111. }
  1112. else error = true;
  1113. }
  1114. else title = args.join(' ');
  1115. if ( error ) {
  1116. msg.reactEmoji('error');
  1117. if ( reaction ) reaction.removeEmoji();
  1118. }
  1119. else if ( diff ) {
  1120. cmd_diffsend(lang, msg, [diff, revision], wiki, reaction, spoiler);
  1121. }
  1122. else {
  1123. request( {
  1124. uri: wiki + 'api.php?action=compare&prop=ids|diff' + ( title ? '&fromtitle=' + encodeURIComponent( title ) : '&fromrev=' + revision ) + '&torelative=' + relative + '&format=json',
  1125. json: true
  1126. }, function( error, response, body ) {
  1127. if ( body && body.warnings ) log_warn(body.warnings);
  1128. if ( error || !response || response.statusCode !== 200 || !body || !body.compare ) {
  1129. var noerror = false;
  1130. if ( body && body.error ) {
  1131. switch ( body.error.code ) {
  1132. case 'nosuchrevid':
  1133. noerror = true;
  1134. break;
  1135. case 'missingtitle':
  1136. noerror = true;
  1137. break;
  1138. case 'invalidtitle':
  1139. noerror = true;
  1140. break;
  1141. case 'missingcontent':
  1142. noerror = true;
  1143. break;
  1144. default:
  1145. noerror = false;
  1146. }
  1147. }
  1148. if ( response && response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' ) {
  1149. console.log( '- This wiki doesn\'t exist! ' + ( error || body && body.error && body.error.info ) );
  1150. msg.reactEmoji('nowiki');
  1151. }
  1152. else if ( noerror ) {
  1153. msg.replyMsg( lang.diff.badrev );
  1154. }
  1155. else {
  1156. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1157. msg.sendChannelError( spoiler + '<' + wiki.toLink() + title.toTitle() + '?diff=' + relative + ( title ? '' : '&oldid=' + revision ) + '>' + spoiler );
  1158. }
  1159. if ( reaction ) reaction.removeEmoji();
  1160. }
  1161. else {
  1162. if ( body.compare.fromarchive !== undefined || body.compare.toarchive !== undefined ) {
  1163. msg.reactEmoji('error');
  1164. if ( reaction ) reaction.removeEmoji();
  1165. } else {
  1166. var argids = [];
  1167. var ids = body.compare;
  1168. if ( ids.fromrevid && !ids.torevid ) argids = [ids.fromrevid];
  1169. else if ( !ids.fromrevid && ids.torevid ) argids = [ids.torevid];
  1170. else {
  1171. argids = [ids.torevid, ids.fromrevid];
  1172. var compare = ['', ''];
  1173. if ( ids.fromtexthidden === undefined && ids.totexthidden === undefined && ids['*'] !== undefined ) {
  1174. var more = '\n__' + lang.diff.info.more + '__';
  1175. var current_tag = '';
  1176. var small_prev_ins = '';
  1177. var small_prev_del = '';
  1178. var ins_length = more.length;
  1179. var del_length = more.length;
  1180. var added = false;
  1181. var parser = new htmlparser.Parser( {
  1182. onopentag: (tagname, attribs) => {
  1183. if ( tagname === 'ins' || tagname == 'del' ) {
  1184. current_tag = tagname;
  1185. }
  1186. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  1187. current_tag = tagname+'a';
  1188. }
  1189. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  1190. current_tag = tagname+"d";
  1191. }
  1192. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  1193. added = true;
  1194. }
  1195. },
  1196. ontext: (htmltext) => {
  1197. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  1198. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  1199. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  1200. else small_prev_ins += more;
  1201. }
  1202. if ( current_tag === 'del' && del_length <= 1000 ) {
  1203. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  1204. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  1205. else small_prev_del += more;
  1206. }
  1207. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  1208. ins_length += htmltext.escapeFormatting().length;
  1209. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  1210. else small_prev_ins += more;
  1211. }
  1212. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  1213. del_length += htmltext.escapeFormatting().length;
  1214. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  1215. else small_prev_del += more;
  1216. }
  1217. if ( added ) {
  1218. if ( htmltext === '+' && ins_length <= 1000 ) {
  1219. ins_length++;
  1220. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  1221. else small_prev_ins += more;
  1222. }
  1223. if ( htmltext === '−' && del_length <= 1000 ) {
  1224. del_length++;
  1225. if ( del_length <= 1000 ) small_prev_del += '\n';
  1226. else small_prev_del += more;
  1227. }
  1228. added = false;
  1229. }
  1230. },
  1231. onclosetag: (tagname) => {
  1232. if ( tagname === 'ins' ) {
  1233. current_tag = 'afterins';
  1234. } else if ( tagname === 'del' ) {
  1235. current_tag = 'afterdel';
  1236. } else {
  1237. current_tag = '';
  1238. }
  1239. }
  1240. }, {decodeEntities:true} );
  1241. parser.write( ids['*'] );
  1242. parser.end();
  1243. if ( small_prev_del.length ) {
  1244. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  1245. compare[0] = small_prev_del.replace( /\~\~\~\~/g, '' );
  1246. } else compare[0] = '__' + lang.diff.info.whitespace + '__';
  1247. }
  1248. if ( small_prev_ins.length ) {
  1249. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  1250. compare[1] = small_prev_ins.replace( /\*\*\*\*/g, '' );
  1251. } else compare[1] = '__' + lang.diff.info.whitespace + '__';
  1252. }
  1253. }
  1254. else if ( ids.fromtexthidden !== undefined ) compare[0] = '__' + lang.diff.hidden + '__';
  1255. else if ( ids.totexthidden !== undefined ) compare[1] = '__' + lang.diff.hidden + '__';
  1256. }
  1257. cmd_diffsend(lang, msg, argids, wiki, reaction, spoiler, compare);
  1258. }
  1259. }
  1260. } );
  1261. }
  1262. }
  1263. else {
  1264. msg.reactEmoji('error');
  1265. if ( reaction ) reaction.removeEmoji();
  1266. }
  1267. }
  1268. function cmd_diffsend(lang, msg, args, wiki, reaction, spoiler, compare) {
  1269. request( {
  1270. 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',
  1271. json: true
  1272. }, function( error, response, body ) {
  1273. if ( body && body.warnings ) log_warn(body.warnings);
  1274. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query ) {
  1275. if ( response && response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' ) {
  1276. console.log( '- This wiki doesn\'t exist! ' + ( error || body && body.error && body.error.info ) );
  1277. msg.reactEmoji('nowiki');
  1278. }
  1279. else {
  1280. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1281. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0] + '>' + spoiler );
  1282. }
  1283. if ( reaction ) reaction.removeEmoji();
  1284. }
  1285. else {
  1286. if ( body.query.badrevids ) {
  1287. msg.replyMsg( lang.diff.badrev );
  1288. if ( reaction ) reaction.removeEmoji();
  1289. }
  1290. else if ( body.query.pages && !body.query.pages['-1'] ) {
  1291. var pages = Object.values(body.query.pages);
  1292. if ( pages.length !== 1 ) {
  1293. msg.sendChannel( spoiler + '<' + wiki.toLink() + 'Special:Diff/' + ( args[1] ? args[1] + '/' : '' ) + args[0] + '>' + spoiler );
  1294. if ( reaction ) reaction.removeEmoji();
  1295. }
  1296. else {
  1297. var title = pages[0].title;
  1298. var revisions = pages[0].revisions.sort( (first, second) => Date.parse(second.timestamp) - Date.parse(first.timestamp) );
  1299. var diff = revisions[0].revid;
  1300. var oldid = ( revisions[1] ? revisions[1].revid : 0 );
  1301. var editor = [lang.diff.info.editor, ( revisions[0].userhidden !== undefined ? lang.diff.hidden : revisions[0].user )];
  1302. var timestamp = [lang.diff.info.timestamp, new Date(revisions[0].timestamp).toLocaleString(lang.user.dateformat, timeoptions)];
  1303. var difference = revisions[0].size - ( revisions[1] ? revisions[1].size : 0 );
  1304. var size = [lang.diff.info.size, lang.diff.info.bytes.replace( '%s', ( difference > 0 ? '+' : '' ) + difference )];
  1305. 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 ) )];
  1306. 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(', ')];
  1307. var pagelink = wiki.toLink() + title.toTitle() + '?diff=' + diff + '&oldid=' + oldid;
  1308. if ( msg.showEmbed() ) {
  1309. var text = '<' + pagelink + '>';
  1310. var editorlink = '[' + editor[1] + '](' + wiki.toLink() + 'User:' + editor[1].toTitle() + ')';
  1311. if ( revisions[0].anon !== undefined ) {
  1312. editorlink = '[' + editor[1] + '](' + wiki.toLink() + 'Special:Contributions/' + editor[1].toTitle(true) + ')';
  1313. }
  1314. if ( editor[1] === lang.diff.hidden ) editorlink = editor[1];
  1315. 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] );
  1316. if ( tags ) {
  1317. var taglink = '';
  1318. var tagtext = '';
  1319. var tagparser = new htmlparser.Parser( {
  1320. onopentag: (tagname, attribs) => {
  1321. if ( tagname === 'a' ) taglink = attribs.href;
  1322. },
  1323. ontext: (htmltext) => {
  1324. if ( taglink ) tagtext += '[' + htmltext.escapeFormatting() + '](' + taglink + ')'
  1325. else tagtext += htmltext.escapeFormatting();
  1326. },
  1327. onclosetag: (tagname) => {
  1328. if ( tagname === 'a' ) taglink = '';
  1329. }
  1330. }, {decodeEntities:true} );
  1331. tagparser.write( tags[1] );
  1332. tagparser.end();
  1333. embed.addField( tags[0], tagtext );
  1334. }
  1335. var more = '\n__' + lang.diff.info.more + '__';
  1336. if ( !compare && oldid ) request( {
  1337. uri: wiki + 'api.php?action=compare&prop=diff&fromrev=' + oldid + '&torev=' + diff + '&format=json',
  1338. json: true
  1339. }, function( cperror, cpresponse, cpbody ) {
  1340. if ( cpbody && cpbody.warnings ) log_warn(cpbody.warnings);
  1341. if ( cperror || !cpresponse || cpresponse.statusCode !== 200 || !cpbody || !cpbody.compare || cpbody.compare['*'] === undefined ) {
  1342. var noerror = false;
  1343. if ( cpbody && cpbody.error ) {
  1344. switch ( cpbody.error.code ) {
  1345. case 'nosuchrevid':
  1346. noerror = true;
  1347. break;
  1348. case 'missingcontent':
  1349. noerror = true;
  1350. break;
  1351. default:
  1352. noerror = false;
  1353. }
  1354. }
  1355. if ( !noerror ) console.log( '- ' + ( cpresponse && cpresponse.statusCode ) + ': Error while getting the diff: ' + ( cperror || cpbody && cpbody.error && cpbody.error.info ) );
  1356. }
  1357. else if ( cpbody.compare.fromtexthidden === undefined && cpbody.compare.totexthidden === undefined && cpbody.compare.fromarchive === undefined && cpbody.compare.toarchive === undefined ) {
  1358. var current_tag = '';
  1359. var small_prev_ins = '';
  1360. var small_prev_del = '';
  1361. var ins_length = more.length;
  1362. var del_length = more.length;
  1363. var added = false;
  1364. var parser = new htmlparser.Parser( {
  1365. onopentag: (tagname, attribs) => {
  1366. if ( tagname === 'ins' || tagname == 'del' ) {
  1367. current_tag = tagname;
  1368. }
  1369. if ( tagname === 'td' && attribs.class === 'diff-addedline' ) {
  1370. current_tag = tagname+'a';
  1371. }
  1372. if ( tagname === 'td' && attribs.class === 'diff-deletedline' ) {
  1373. current_tag = tagname+"d";
  1374. }
  1375. if ( tagname === 'td' && attribs.class === 'diff-marker' ) {
  1376. added = true;
  1377. }
  1378. },
  1379. ontext: (htmltext) => {
  1380. if ( current_tag === 'ins' && ins_length <= 1000 ) {
  1381. ins_length += ( '**' + htmltext.escapeFormatting() + '**' ).length;
  1382. if ( ins_length <= 1000 ) small_prev_ins += '**' + htmltext.escapeFormatting() + '**';
  1383. else small_prev_ins += more;
  1384. }
  1385. if ( current_tag === 'del' && del_length <= 1000 ) {
  1386. del_length += ( '~~' + htmltext.escapeFormatting() + '~~' ).length;
  1387. if ( del_length <= 1000 ) small_prev_del += '~~' + htmltext.escapeFormatting() + '~~';
  1388. else small_prev_del += more;
  1389. }
  1390. if ( ( current_tag === 'afterins' || current_tag === 'tda') && ins_length <= 1000 ) {
  1391. ins_length += htmltext.escapeFormatting().length;
  1392. if ( ins_length <= 1000 ) small_prev_ins += htmltext.escapeFormatting();
  1393. else small_prev_ins += more;
  1394. }
  1395. if ( ( current_tag === 'afterdel' || current_tag === 'tdd') && del_length <= 1000 ) {
  1396. del_length += htmltext.escapeFormatting().length;
  1397. if ( del_length <= 1000 ) small_prev_del += htmltext.escapeFormatting();
  1398. else small_prev_del += more;
  1399. }
  1400. if ( added ) {
  1401. if ( htmltext === '+' && ins_length <= 1000 ) {
  1402. ins_length++;
  1403. if ( ins_length <= 1000 ) small_prev_ins += '\n';
  1404. else small_prev_ins += more;
  1405. }
  1406. if ( htmltext === '−' && del_length <= 1000 ) {
  1407. del_length++;
  1408. if ( del_length <= 1000 ) small_prev_del += '\n';
  1409. else small_prev_del += more;
  1410. }
  1411. added = false;
  1412. }
  1413. },
  1414. onclosetag: (tagname) => {
  1415. if ( tagname === 'ins' ) {
  1416. current_tag = 'afterins';
  1417. } else if ( tagname === 'del' ) {
  1418. current_tag = 'afterdel';
  1419. } else {
  1420. current_tag = '';
  1421. }
  1422. }
  1423. }, {decodeEntities:true} );
  1424. parser.write( cpbody.compare['*'] );
  1425. parser.end();
  1426. if ( small_prev_del.length ) {
  1427. if ( small_prev_del.replace( /\~\~/g, '' ).trim().length ) {
  1428. embed.addField( lang.diff.info.removed, small_prev_del.replace( /\~\~\~\~/g, '' ), true );
  1429. } else embed.addField( lang.diff.info.removed, '__' + lang.diff.info.whitespace + '__', true );
  1430. }
  1431. if ( small_prev_ins.length ) {
  1432. if ( small_prev_ins.replace( /\*\*/g, '' ).trim().length ) {
  1433. embed.addField( lang.diff.info.added, small_prev_ins.replace( /\*\*\*\*/g, '' ), true );
  1434. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  1435. }
  1436. }
  1437. else if ( cpbody.compare.fromtexthidden !== undefined ) {
  1438. embed.addField( lang.diff.info.removed, '__' + lang.diff.hidden + '__', true );
  1439. }
  1440. else if ( cpbody.compare.totexthidden !== undefined ) {
  1441. embed.addField( lang.diff.info.added, '__' + lang.diff.hidden + '__', true );
  1442. }
  1443. msg.sendChannel( spoiler + text + spoiler, embed );
  1444. if ( reaction ) reaction.removeEmoji();
  1445. } );
  1446. else {
  1447. if ( compare ) {
  1448. if ( compare[0].length ) embed.addField( lang.diff.info.removed, compare[0], true );
  1449. if ( compare[1].length ) embed.addField( lang.diff.info.added, compare[1], true );
  1450. }
  1451. else if ( revisions[0]['*'] ) {
  1452. var content = revisions[0]['*'].escapeFormatting();
  1453. if ( content.trim().length ) {
  1454. if ( content.length <= 1000 ) content = '**' + content + '**';
  1455. else {
  1456. content = content.substring(0, 1000 - more.length);
  1457. content = '**' + content.substring(0, content.lastIndexOf('\n')) + '**' + more;
  1458. }
  1459. embed.addField( lang.diff.info.added, content, true );
  1460. } else embed.addField( lang.diff.info.added, '__' + lang.diff.info.whitespace + '__', true );
  1461. }
  1462. msg.sendChannel( spoiler + text + spoiler, embed );
  1463. if ( reaction ) reaction.removeEmoji();
  1464. }
  1465. }
  1466. else {
  1467. var embed = {};
  1468. var text = '<' + pagelink + '>\n\n' + editor.join(' ') + '\n' + timestamp.join(' ') + '\n' + size.join(' ') + '\n' + comment.join(' ');
  1469. if ( tags ) {
  1470. var tagparser = new htmlparser.Parser( {
  1471. ontext: (htmltext) => {
  1472. text += htmltext.escapeFormatting();
  1473. }
  1474. }, {decodeEntities:true} );
  1475. tagparser.write( '\n' + tags.join(' ') );
  1476. tagparser.end();
  1477. }
  1478. msg.sendChannel( spoiler + text + spoiler, embed );
  1479. if ( reaction ) reaction.removeEmoji();
  1480. }
  1481. }
  1482. }
  1483. else {
  1484. msg.reactEmoji('error');
  1485. if ( reaction ) reaction.removeEmoji();
  1486. }
  1487. }
  1488. } );
  1489. }
  1490. function cmd_random(lang, msg, wiki, reaction, spoiler) {
  1491. request( {
  1492. 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',
  1493. json: true
  1494. }, function( error, response, body ) {
  1495. if ( body && body.warnings ) log_warn(body.warnings);
  1496. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  1497. if ( response && response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' ) {
  1498. console.log( '- This wiki doesn\'t exist! ' + ( error || body && body.error && body.error.info ) );
  1499. msg.reactEmoji('nowiki');
  1500. }
  1501. else {
  1502. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1503. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Random>' + spoiler );
  1504. }
  1505. }
  1506. else {
  1507. querypage = Object.values(body.query.pages)[0];
  1508. var pagelink = wiki.toLink() + querypage.title.toTitle();
  1509. var embed = new Discord.RichEmbed().setAuthor( body.query.general.sitename ).setTitle( querypage.title.escapeFormatting() ).setURL( pagelink );
  1510. if ( querypage.pageprops && querypage.pageprops.displaytitle ) embed.setTitle( querypage.pageprops.displaytitle.escapeFormatting() );
  1511. if ( querypage.pageprops && querypage.pageprops.description ) {
  1512. var description = '';
  1513. var parser = new htmlparser.Parser( {
  1514. ontext: (htmltext) => {
  1515. description += htmltext.escapeFormatting();
  1516. }
  1517. }, {decodeEntities:true} );
  1518. parser.write( querypage.pageprops.description );
  1519. parser.end();
  1520. if ( description.length > 2000 ) description = description.substring(0, 2000) + '\u2026';
  1521. embed.setDescription( description );
  1522. }
  1523. else if ( querypage.extract ) {
  1524. var extract = querypage.extract.escapeFormatting();
  1525. if ( extract.length > 2000 ) extract = extract.substring(0, 2000) + '\u2026';
  1526. embed.setDescription( extract );
  1527. }
  1528. if ( querypage.pageimage && querypage.original && querypage.title !== body.query.general.mainpage ) {
  1529. embed.setThumbnail( querypage.original.source );
  1530. }
  1531. else embed.setThumbnail( ( body.query.general.logo.startsWith( '//' ) ? 'https:' : '' ) + body.query.general.logo );
  1532. msg.sendChannel( spoiler + '🎲 <' + pagelink + '>' + spoiler, embed );
  1533. }
  1534. if ( reaction ) reaction.removeEmoji();
  1535. } );
  1536. }
  1537. function cmd_overview(lang, msg, wiki, reaction, spoiler) {
  1538. request( {
  1539. uri: wiki + 'api.php?action=query&meta=siteinfo&siprop=general&titles=Special:Statistics&format=json',
  1540. json: true
  1541. }, function( error, response, body ) {
  1542. if ( body && body.warnings ) log_warn(body.warnings);
  1543. if ( error || !response || response.statusCode !== 200 || !body || body.batchcomplete === undefined || !body.query || !body.query.pages ) {
  1544. if ( response && response.request && response.request.uri && response.request.uri.href === 'https://www.gamepedia.com/' ) {
  1545. console.log( '- This wiki doesn\'t exist! ' + ( error || body && body.error && body.error.info ) );
  1546. msg.reactEmoji('nowiki');
  1547. }
  1548. else {
  1549. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the search results: ' + ( error || body && body.error && body.error.info ) );
  1550. msg.sendChannelError( spoiler + '<' + wiki.toLink() + 'Special:Statistics>' + spoiler );
  1551. }
  1552. }
  1553. else if ( allSites.some( site => site.wiki_domain === body.query.general.servername ) ) {
  1554. var site = allSites.find( site => site.wiki_domain === body.query.general.servername );
  1555. var name = [lang.overview.name, site.wiki_display_name];
  1556. var created = [lang.overview.created, new Date(parseInt(site.created + '000', 10)).toLocaleString(lang.user.dateformat, timeoptions)];
  1557. var manager = [lang.overview.manager, site.wiki_managers];
  1558. var official = [lang.overview.official, ( site.official_wiki ? lang.overview.yes : lang.overview.no )];
  1559. var articles = [lang.overview.articles, site.ss_good_articles];
  1560. var pages = [lang.overview.pages, site.ss_total_pages];
  1561. var edits = [lang.overview.edits, site.ss_total_edits];
  1562. var users = [lang.overview.users, site.ss_active_users];
  1563. var title = body.query.pages['-1'].title;
  1564. var pagelink = wiki.toLink() + title.toTitle();
  1565. if ( msg.showEmbed() ) {
  1566. var text = '<' + pagelink + '>';
  1567. 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');
  1568. 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 ).addField( name[0], name[1], true ).addField( created[0], created[1], true ).addField( manager[0], managerlist, true ).addField( official[0], official[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 ).setTimestamp( client.readyTimestamp ).setFooter( lang.overview.inaccurate );
  1569. }
  1570. else {
  1571. var embed = {};
  1572. var text = '<' + pagelink + '>\n\n' + name.join(' ') + '\n' + created.join(' ') + '\n' + manager[0] + ' ' + manager[1].join(', ') + '\n' + official.join(' ') + '\n' + articles.join(' ') + '\n' + pages.join(' ') + '\n' + edits.join(' ') + '\n' + users.join(' ') + '\n\n*' + lang.overview.inaccurate + '*';
  1573. }
  1574. msg.sendChannel( spoiler + text + spoiler, embed );
  1575. }
  1576. else {
  1577. console.log( '- This site isn\'t listed: ' + wiki )
  1578. msg.replyMsg( lang.overview.missing );
  1579. }
  1580. if ( reaction ) reaction.removeEmoji();
  1581. } );
  1582. }
  1583. function cmd_bug(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  1584. var invoke = args[0];
  1585. args = args.slice(1);
  1586. if ( invoke && /\d+$/.test(invoke) && !args.length ) {
  1587. var project = '';
  1588. if ( /^\d+$/.test(invoke) ) project = 'MC-';
  1589. request( {
  1590. uri: 'https://bugs.mojang.com/rest/api/2/issue/' + encodeURIComponent( project + invoke ) + '?fields=summary,issuelinks,fixVersions,resolution,status',
  1591. json: true
  1592. }, function( error, response, body ) {
  1593. var link = 'https://bugs.mojang.com/browse/';
  1594. if ( error || !response || response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  1595. if ( body && body.errorMessages ) {
  1596. if ( body.errorMessages.includes( 'Issue Does Not Exist' ) ) {
  1597. msg.reactEmoji('🤷');
  1598. }
  1599. else if ( body.errorMessages.includes( 'You do not have the permission to see the specified issue.' ) ) {
  1600. msg.sendChannel( spoiler + mclang.bug.private + '\n<' + link + project + invoke + '>' + spoiler );
  1601. }
  1602. else {
  1603. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + body.errorMessages.join(' - ') );
  1604. msg.reactEmoji('error');
  1605. }
  1606. }
  1607. else {
  1608. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issue: ' + ( error || body && body.message ) );
  1609. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  1610. else msg.sendChannelError( spoiler + '<' + link + project + invoke + '>' + spoiler );
  1611. }
  1612. }
  1613. else {
  1614. if ( !body.fields ) {
  1615. msg.reactEmoji('error');
  1616. }
  1617. else {
  1618. var bugs = body.fields.issuelinks.filter( bug => bug.outwardIssue || ( bug.inwardIssue && bug.type.name != 'Duplicate' ) );
  1619. if ( bugs.length ) {
  1620. var embed = new Discord.RichEmbed();
  1621. var extrabugs = [];
  1622. bugs.forEach( bug => {
  1623. var ward = ( bug.outwardIssue ? 'outward' : 'inward' );
  1624. var issue = bug[ward + 'Issue'];
  1625. var name = bug.type[ward] + ' ' + issue.key;
  1626. var value = issue.fields.status.name + ': [' + issue.fields.summary.escapeFormatting() + '](' + link + issue.key + ')';
  1627. if ( embed.fields.length < 25 ) embed.addField( name, value );
  1628. else extrabugs.push({name,value,inline:false});
  1629. } );
  1630. if ( extrabugs.length ) embed.setFooter( mclang.bug.more.replaceSave( '%s', extrabugs.length ) );
  1631. }
  1632. var status = '**' + ( body.fields.resolution ? body.fields.resolution.name : body.fields.status.name ) + ':** ';
  1633. var fixed = '';
  1634. if ( body.fields.resolution && body.fields.fixVersions && body.fields.fixVersions.length ) {
  1635. fixed = '\n' + mclang.bug.fixed + ' ' + body.fields.fixVersions.map( v => v.name ).join(', ');
  1636. }
  1637. msg.sendChannel( spoiler + status + body.fields.summary.escapeFormatting() + '\n<' + link + body.key + '>' + fixed + spoiler, embed );
  1638. }
  1639. }
  1640. if ( reaction ) reaction.removeEmoji();
  1641. } );
  1642. }
  1643. else if ( invoke && invoke.toLowerCase() === 'version' && args.length && args.join(' ').length < 100 ) {
  1644. var jql = 'fixVersion="' + args.join(' ').replace( /("|\\)/g, '\\$1' ).toSearch() + '"+order+by+key';
  1645. request( {
  1646. uri: 'https://bugs.mojang.com/rest/api/2/search?fields=summary,resolution,status&jql=' + jql + '&maxResults=25',
  1647. json: true
  1648. }, function( error, response, body ) {
  1649. var link = 'https://bugs.mojang.com/issues/?jql=' + jql;
  1650. if ( error || !response || response.statusCode !== 200 || !body || body['status-code'] === 404 || body.errorMessages || body.errors ) {
  1651. if ( body && body.errorMessages ) {
  1652. if ( body.errorMessages.includes( 'The value \'' + args.join(' ') + '\' does not exist for the field \'fixVersion\'.' ) ) {
  1653. msg.reactEmoji('🤷');
  1654. }
  1655. else {
  1656. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issues: ' + body.errorMessages.join(' - ') );
  1657. msg.reactEmoji('error');
  1658. }
  1659. }
  1660. else {
  1661. console.log( '- ' + ( response && response.statusCode ) + ': Error while getting the issues: ' + ( error || body && body.message ) );
  1662. if ( body && body['status-code'] === 404 ) msg.reactEmoji('error');
  1663. else msg.sendChannelError( spoiler + '<' + link + '>' + spoiler );
  1664. }
  1665. }
  1666. else {
  1667. if ( !body.issues ) {
  1668. msg.reactEmoji('error');
  1669. }
  1670. else {
  1671. if ( body.total > 0 ) {
  1672. var embed = new Discord.RichEmbed();
  1673. body.issues.forEach( bug => {
  1674. var status = ( bug.fields.resolution ? bug.fields.resolution.name : bug.fields.status.name );
  1675. var value = status + ': [' + bug.fields.summary.escapeFormatting() + '](https://bugs.mojang.com/browse/' + bug.key + ')';
  1676. embed.addField( bug.key, value );
  1677. } );
  1678. if ( body.total > 25 ) embed.setFooter( mclang.bug.more.replaceSave( '%s', body.total - 25 ) );
  1679. }
  1680. var total = '**' + args.join(' ') + ':** ' + mclang.bug.total.replaceSave( '%s', body.total );
  1681. msg.sendChannel( spoiler + total + '\n<' + link + '>' + spoiler, embed );
  1682. }
  1683. }
  1684. if ( reaction ) reaction.removeEmoji();
  1685. } );
  1686. }
  1687. else {
  1688. msg.notminecraft = true;
  1689. check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  1690. }
  1691. }
  1692. function cmd_befehl(lang, mclang, msg, befehl, args, title, cmd, querystring, fragment, reaction, spoiler) {
  1693. befehl = befehl.toLowerCase();
  1694. var aliasCmd = ( minecraft.cmd.aliase[befehl] || befehl );
  1695. if ( aliasCmd in minecraft.cmd.list ) {
  1696. var regex = new RegExp('/' + aliasCmd, 'g');
  1697. var cmdSyntax = minecraft.cmd.list[aliasCmd].join( '\n' ).replaceSave( regex, '/' + befehl );
  1698. msg.sendChannel( spoiler + '```md\n' + cmdSyntax + '```<' + mclang.link + mclang.cmd.page + aliasCmd + '>' + spoiler, {split:{maxLength:2000,prepend:spoiler + '```md\n',append:'```' + spoiler}} );
  1699. if ( reaction ) reaction.removeEmoji();
  1700. }
  1701. else {
  1702. msg.reactEmoji('❓');
  1703. msg.notminecraft = true;
  1704. check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  1705. }
  1706. }
  1707. function cmd_befehl2(lang, mclang, msg, args, title, cmd, querystring, fragment, reaction, spoiler) {
  1708. if ( args.join('') ) {
  1709. if ( args[0].startsWith( '/' ) ) cmd_befehl(lang, mclang, msg, args[0].substring(1), args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  1710. else cmd_befehl(lang, mclang, msg, args[0], args.slice(1), title, cmd, querystring, fragment, reaction, spoiler);
  1711. }
  1712. else {
  1713. msg.notminecraft = true;
  1714. check_wiki(lang, msg, title, mclang.link, cmd, reaction, spoiler, querystring, fragment);
  1715. }
  1716. }
  1717. function cmd_multiline(lang, msg, args, line) {
  1718. if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) {
  1719. if ( msg.isAdmin() ) msg.reactEmoji('error', true);
  1720. else msg.reactEmoji('❌');
  1721. }
  1722. }
  1723. function cmd_voice(lang, msg, args, line) {
  1724. if ( msg.isAdmin() && !args.join('') ) msg.replyMsg( lang.voice.text + '\n`' + lang.voice.channel + ' – <' + lang.voice.name + '>`' );
  1725. else cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  1726. }
  1727. function cmd_get(lang, msg, args, line) {
  1728. var id = args.join().replace( /^\\?<(?:@!?|#)(\d+)>$/, '$1' );
  1729. if ( /^\d+$/.test(id) ) {
  1730. if ( client.guilds.has(id) ) {
  1731. var guild = client.guilds.get(id);
  1732. var guildname = ['Guild:', guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( pause[guild.id] ? '\\*' : '' )];
  1733. var guildowner = ['Owner:', guild.owner.user.tag.escapeFormatting() + ' `' + guild.ownerID + '` ' + guild.owner.toString()];
  1734. var guildsize = ['Size:', guild.memberCount + ' members (' + guild.members.filter( member => member.user.bot ).size + ' bots)'];
  1735. var guildpermissions = ['Missing permissions:', ( guild.me.permissions.has(defaultPermissions) ? '*none*' : '`' + guild.me.permissions.missing(defaultPermissions).join('`, `') + '`' )];
  1736. var guildsettings = ['Settings:', ( guild.id in settings ? '```json\n' + JSON.stringify( settings[guild.id], null, '\t' ) + '\n```' : '*default*' )];
  1737. if ( msg.showEmbed() ) {
  1738. var text = '';
  1739. 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] ).addField( guildsettings[0], guildsettings[1] );
  1740. }
  1741. else {
  1742. var embed = {};
  1743. var text = guildname.join(' ') + '\n' + guildowner.join(' ') + '\n' + guildsize.join(' ') + '\n' + guildpermissions.join(' ') + '\n' + guildsettings.join(' ');
  1744. }
  1745. msg.sendChannel( text, embed, true );
  1746. } else if ( client.guilds.some( guild => guild.members.has(id) ) ) {
  1747. var username = [];
  1748. var guildlist = ['Guilds:'];
  1749. var guilds = client.guilds.filter( guild => guild.members.has(id) )
  1750. guildlist.push('\n' + guilds.map( function(guild) {
  1751. var member = guild.members.get(id);
  1752. if ( !username.length ) username.push('User:', member.user.tag.escapeFormatting() + ' `' + member.id + '` ' + member.toString());
  1753. return guild.name.escapeFormatting() + ' `' + guild.id + '`' + ( member.permissions.has('MANAGE_GUILD') ? '\\*' : '' );
  1754. } ).join('\n'));
  1755. if ( guildlist[1].length > 1000 ) guildlist[1] = guilds.size;
  1756. if ( msg.showEmbed() ) {
  1757. var text = '';
  1758. var embed = new Discord.RichEmbed().addField( username[0], username[1] ).addField( guildlist[0], guildlist[1] );
  1759. }
  1760. else {
  1761. var embed = {};
  1762. var text = username.join(' ') + '\n' + guildlist.join(' ');
  1763. }
  1764. msg.sendChannel( text, embed, true );
  1765. } else if ( client.guilds.some( guild => guild.channels.filter( chat => chat.type === 'text' ).has(id) ) ) {
  1766. var channel = client.guilds.find( guild => guild.channels.filter( chat => chat.type === 'text' ).has(id) ).channels.get(id);
  1767. var channelguild = ['Guild:', channel.guild.name.escapeFormatting() + ' `' + channel.guild.id + '`' + ( pause[channel.guild.id] ? '\\*' : '' )];
  1768. var channelname = ['Channel:', '#' + channel.name.escapeFormatting() + ' `' + channel.id + '` ' + channel.toString()];
  1769. var channelpermissions = ['Missing permissions:', ( channel.memberPermissions(channel.guild.me).has(defaultPermissions) ? '*none*' : '`' + channel.memberPermissions(channel.guild.me).missing(defaultPermissions).join('`, `') + '`' )];
  1770. var channelwiki = ['Default Wiki:', channel.getWiki()];
  1771. if ( msg.showEmbed() ) {
  1772. var text = '';
  1773. var embed = new Discord.RichEmbed().addField( channelguild[0], channelguild[1] ).addField( channelname[0], channelname[1] ).addField( channelpermissions[0], channelpermissions[1] ).addField( channelwiki[0], channelwiki[1] );
  1774. }
  1775. else {
  1776. var embed = {};
  1777. var text = channelguild.join(' ') + '\n' + channelname.join(' ') + '\n' + channelpermissions.join(' ') + '\n' + channelwiki[0] + ' <' + channelwiki[1] + '>';
  1778. }
  1779. msg.sendChannel( text, embed, true );
  1780. } else msg.replyMsg( 'I couldn\'t find a result for `' + id + '`', {}, true );
  1781. } else if ( msg.channel.type !== 'text' || !pause[msg.guild.id] ) cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  1782. }
  1783. String.prototype.toLink = function() {
  1784. if ( this.endsWith( '.org/w/' ) ) return this.substring(0, this.length - 2) + 'wiki/';
  1785. else return this;
  1786. };
  1787. String.prototype.isMention = function(guild) {
  1788. var text = this.trim();
  1789. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  1790. };
  1791. Discord.Channel.prototype.getWiki = function() {
  1792. if ( this.type === 'text' && this.guild.id in settings ) {
  1793. if ( settings[this.guild.id].channels && this.id in settings[this.guild.id].channels ) return settings[this.guild.id].channels[this.id];
  1794. else return settings[this.guild.id].wiki;
  1795. }
  1796. else return settings.default.wiki;
  1797. };
  1798. Discord.Message.prototype.isAdmin = function() {
  1799. return this.channel.type === 'text' && this.member && this.member.permissions.has('MANAGE_GUILD');
  1800. };
  1801. Discord.Message.prototype.isOwner = function() {
  1802. return this.author.id === process.env.owner;
  1803. };
  1804. Discord.Message.prototype.showEmbed = function() {
  1805. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  1806. };
  1807. Discord.Message.prototype.uploadFiles = function() {
  1808. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  1809. };
  1810. Array.prototype.toEmojis = function() {
  1811. var text = this.join(' ');
  1812. var regex = /(<a?:)(\d+)(>)/g;
  1813. if ( regex.test(text) ) {
  1814. regex.lastIndex = 0;
  1815. var emojis = client.emojis;
  1816. while ( ( entry = regex.exec(text) ) !== null ) {
  1817. if ( emojis.has(entry[2]) ) {
  1818. text = text.replaceSave(entry[0], emojis.get(entry[2]).toString());
  1819. } else {
  1820. text = text.replaceSave(entry[0], entry[1] + 'unknown_emoji:' + entry[2] + entry[3]);
  1821. }
  1822. }
  1823. return text.split(' ');
  1824. }
  1825. else return this;
  1826. };
  1827. String.prototype.toTitle = function(isMarkdown = false) {
  1828. var title = this.replace( / /g, '_' ).replace( /\%/g, '%25' ).replace( /\?/g, '%3F' ).replace( /@(here|everyone)/g, '%40$1' );
  1829. if ( isMarkdown ) title = title.replace( /(\(|\))/g, '\\$1' );
  1830. return title;
  1831. };
  1832. String.prototype.toSearch = function() {
  1833. return encodeURIComponent( this ).replace( /%20/g, '+' );
  1834. };
  1835. String.prototype.toSection = function() {
  1836. return encodeURIComponent( this.replace( / /g, '_' ) ).replace( /\'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\%/g, '.' );
  1837. };
  1838. String.prototype.toFormatting = function(showEmbed = false, ...args) {
  1839. if ( showEmbed ) return this.toMarkdown(...args);
  1840. else return this.toPlaintext();
  1841. };
  1842. String.prototype.toMarkdown = function(wiki, title = '') {
  1843. var text = this;
  1844. while ( ( link = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g.exec(text) ) !== null ) {
  1845. if ( link[1] ) {
  1846. var page = ( /^(#|\/)/.test(link[1]) ? title.toTitle(true) + ( /^#/.test(link[1]) ? '#' + link[1].substring(1).toSection() : link[1].toTitle(true) ) : link[1].toTitle(true) );
  1847. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + wiki.toLink() + page + ')' );
  1848. } else {
  1849. var page = ( /^(#|\/)/.test(link[2]) ? title.toTitle(true) + ( /^#/.test(link[2]) ? '#' + link[2].substring(1).toSection() : link[2].toTitle(true) ) : link[2].toTitle(true) );
  1850. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + wiki.toLink() + page + ')' );
  1851. }
  1852. }
  1853. while ( title !== '' && ( link = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g.exec(text) ) !== null ) {
  1854. var page = title.toTitle(true) + '#' + link[1].toSection();
  1855. text = text.replaceSave( link[0], '[→](' + wiki.toLink() + page + ')' + link[1] + ( link[2] ? ': ' + link[2] : '' ) );
  1856. }
  1857. return text.escapeFormatting();
  1858. };
  1859. String.prototype.toPlaintext = function() {
  1860. return this.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' ).escapeFormatting();
  1861. };
  1862. String.prototype.escapeFormatting = function() {
  1863. return this.replace( /(`|_|\*|~|:|<|>|{|}|@|\||\\|\/\/)/g, '\\$1' );
  1864. };
  1865. String.prototype.replaceSave = function(pattern, replacement) {
  1866. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( '$', '$$$$' ) : replacement ) );
  1867. };
  1868. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  1869. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  1870. var emoji = '440871715938238494';
  1871. switch ( name ) {
  1872. case 'nowiki':
  1873. emoji = '505884572001763348';
  1874. break;
  1875. case 'error':
  1876. emoji = '440871715938238494';
  1877. break;
  1878. case 'support':
  1879. emoji = '448222377009086465';
  1880. break;
  1881. case 'oppose':
  1882. emoji = '448222455425794059';
  1883. break;
  1884. default:
  1885. emoji = name;
  1886. }
  1887. return this.react(emoji).catch(log_error);
  1888. } else {
  1889. console.log( '- Aborted, paused.' );
  1890. return Promise.resolve();
  1891. }
  1892. };
  1893. Discord.MessageReaction.prototype.removeEmoji = function() {
  1894. return this.remove().catch(log_error);
  1895. };
  1896. Discord.Message.prototype.sendChannel = function(content, options, ignorePause = false) {
  1897. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  1898. return this.channel.send(content, options).then( msg => {
  1899. msg.allowDelete(this.author.id);
  1900. return msg;
  1901. }, log_error );
  1902. } else {
  1903. console.log( '- Aborted, paused.' );
  1904. return Promise.resolve();
  1905. }
  1906. };
  1907. Discord.Message.prototype.sendChannelError = function(content, options) {
  1908. return this.channel.send(content, options).then( msg => {
  1909. msg.reactEmoji('error');
  1910. msg.allowDelete(this.author.id);
  1911. return msg;
  1912. }, log_error );
  1913. };
  1914. Discord.Message.prototype.replyMsg = function(content, options, ignorePause = false) {
  1915. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  1916. return this.reply(content, options).then( msg => {
  1917. msg.allowDelete(this.author.id);
  1918. return msg;
  1919. }, log_error );
  1920. } else {
  1921. console.log( '- Aborted, paused.' );
  1922. return Promise.resolve();
  1923. }
  1924. };
  1925. Discord.Message.prototype.deleteMsg = function(timeout = 0) {
  1926. return this.delete(timeout).catch(log_error);
  1927. };
  1928. Discord.Message.prototype.allowDelete = function(author) {
  1929. return this.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑' && user.id === author, {max:1,time:30000} ).then( reaction => {
  1930. if ( reaction.size ) {
  1931. this.deleteMsg();
  1932. }
  1933. } );
  1934. };
  1935. String.prototype.hasPrefix = function(flags = '') {
  1936. return RegExp( '^' + process.env.prefix + '(?: |$)', flags ).test(this.toLowerCase());
  1937. };
  1938. client.on( 'message', msg => {
  1939. if ( stop || !msg.content.hasPrefix('m') || msg.webhookID || msg.author.id === client.user.id ) return;
  1940. var cont = msg.content;
  1941. var author = msg.author;
  1942. var channel = msg.channel;
  1943. if ( channel.type === 'text' ) var permissions = channel.permissionsFor(client.user);
  1944. if ( !ready.settings && settings === defaultSettings ) getSettings();
  1945. if ( !ready.allSites && !allSites.length ) getAllSites();
  1946. if ( settings === defaultSettings ) {
  1947. msg.sendChannel( '⚠ **Limited Functionality** ⚠\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  1948. }
  1949. var lang = i18n[( channel.type === 'text' && settings[msg.guild.id] || settings.default ).lang];
  1950. if ( channel.type !== 'text' || permissions.has(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']) ) {
  1951. var invoke = ( cont.split(' ')[1] ? cont.split(' ')[1].split('\n')[0].toLowerCase() : '' );
  1952. var aliasInvoke = ( lang.aliase[invoke] || invoke );
  1953. var ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  1954. if ( cont.hasPrefix() && ( ( msg.isAdmin() && aliasInvoke in multilinecmdmap ) || ownercmd ) ) {
  1955. if ( ownercmd || permissions.has('MANAGE_MESSAGES') ) {
  1956. var args = cont.split(' ').slice(2);
  1957. if ( cont.split(' ')[1].split('\n')[1] ) args.unshift( '', cont.split(' ')[1].split('\n')[1] );
  1958. if ( !( ownercmd || aliasInvoke in pausecmdmap ) && pause[msg.guild.id] ) console.log( msg.guild.name + ': Paused' );
  1959. else console.log( ( msg.guild ? msg.guild.name : '@' + author.username ) + ': ' + cont );
  1960. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, cont);
  1961. else if ( !pause[msg.guild.id] || aliasInvoke in pausecmdmap ) multilinecmdmap[aliasInvoke](lang, msg, args, cont);
  1962. } else {
  1963. console.log( msg.guild.name + ': Missing permissions - MANAGE_MESSAGES' );
  1964. msg.replyMsg( lang.missingperm + ' `MANAGE_MESSAGES`' );
  1965. }
  1966. } else {
  1967. var count = 0;
  1968. msg.cleanContent.replace(/\u200b/g, '').split('\n').forEach( function(line) {
  1969. if ( line.hasPrefix() && count < 10 ) {
  1970. count++;
  1971. invoke = ( line.split(' ')[1] ? line.split(' ')[1].toLowerCase() : '' );
  1972. var args = line.split(' ').slice(2);
  1973. aliasInvoke = ( lang.aliase[invoke] || invoke );
  1974. ownercmd = ( msg.isOwner() && aliasInvoke in ownercmdmap );
  1975. if ( channel.type === 'text' && pause[msg.guild.id] && !( ( msg.isAdmin() && aliasInvoke in pausecmdmap ) || ownercmd ) ) console.log( msg.guild.name + ': Paused' );
  1976. else console.log( ( msg.guild ? msg.guild.name : '@' + author.username ) + ': ' + line );
  1977. if ( ownercmd ) ownercmdmap[aliasInvoke](lang, msg, args, line);
  1978. else if ( channel.type !== 'text' || !pause[msg.guild.id] || ( msg.isAdmin() && aliasInvoke in pausecmdmap ) ) {
  1979. if ( aliasInvoke in cmdmap ) cmdmap[aliasInvoke](lang, msg, args, line);
  1980. else if ( /^![a-z\d-]{1,50}$/.test(invoke) ) cmd_link(lang, msg, args.join(' '), 'https://' + invoke.substring(1) + '.gamepedia.com/', ' ' + invoke + ' ');
  1981. else cmd_link(lang, msg, line.split(' ').slice(1).join(' '));
  1982. }
  1983. } else if ( line.hasPrefix() && count === 10 ) {
  1984. count++;
  1985. console.log( '- Message contains too many commands!' );
  1986. msg.reactEmoji('⚠');
  1987. msg.sendChannelError( lang.limit.replaceSave( '%s', author.toString() ) );
  1988. }
  1989. } );
  1990. }
  1991. } else if ( msg.isAdmin() || msg.isOwner() ) {
  1992. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  1993. console.log( msg.guild.name + ': Missing permissions - ' + missing.join(', ') );
  1994. if ( !missing.includes( 'SEND_MESSAGES' ) ) msg.replyMsg( lang.missingperm + ' `' + missing.join('`, `') + '`' );
  1995. }
  1996. } );
  1997. client.on( 'voiceStateUpdate', (oldm, newm) => {
  1998. if ( stop ) return;
  1999. if ( !ready.settings && settings === defaultSettings ) getSettings();
  2000. if ( !ready.allSites && !allSites.length ) getAllSites();
  2001. if ( oldm.guild.me.permissions.has('MANAGE_ROLES') && oldm.voiceChannelID !== newm.voiceChannelID ) {
  2002. var lang = i18n[( settings[oldm.guild.id] || settings.default ).lang].voice;
  2003. if ( oldm.voiceChannel ) {
  2004. var oldrole = oldm.roles.find( role => role.name === lang.channel + ' – ' + oldm.voiceChannel.name );
  2005. if ( oldrole && oldrole.comparePositionTo(oldm.guild.me.highestRole) < 0 ) {
  2006. console.log( oldm.guild.name + ': ' + oldm.displayName + ' left the voice channel "' + oldm.voiceChannel.name + '".' );
  2007. oldm.removeRole( oldrole, lang.left.replaceSave( '%1$s', oldm.displayName ).replaceSave( '%2$s', oldm.voiceChannel.name ) ).catch(log_error);
  2008. }
  2009. }
  2010. if ( newm.voiceChannel ) {
  2011. var newrole = newm.guild.roles.find( role => role.name === lang.channel + ' – ' + newm.voiceChannel.name );
  2012. if ( newrole && newrole.comparePositionTo(newm.guild.me.highestRole) < 0 ) {
  2013. console.log( newm.guild.name + ': ' + newm.displayName + ' joined the voice channel "' + newm.voiceChannel.name + '".' );
  2014. newm.addRole( newrole, lang.join.replaceSave( '%1$s', newm.displayName ).replaceSave( '%2$s', newm.voiceChannel.name ) ).catch(log_error);
  2015. }
  2016. }
  2017. }
  2018. } );
  2019. client.on( 'guildCreate', guild => {
  2020. console.log( '- I\'ve been added to a server.' );
  2021. } );
  2022. client.on( 'guildDelete', guild => {
  2023. console.log( '- I\'ve been removed from a server.' );
  2024. if ( !guild.available ) {
  2025. console.log( '- ' + guild.name + ': This server isn\'t responding.' );
  2026. return;
  2027. }
  2028. if ( settings === defaultSettings ) {
  2029. console.log( '- Error while getting current settings.' );
  2030. }
  2031. else {
  2032. var temp_settings = JSON.parse(JSON.stringify(settings));
  2033. var save = false;
  2034. Object.keys(temp_settings).forEach( function(guild) {
  2035. if ( !client.guilds.has(guild) && guild !== 'default' ) {
  2036. delete temp_settings[guild];
  2037. save = true;
  2038. }
  2039. } );
  2040. if ( save ) request.post( {
  2041. uri: process.env.save,
  2042. headers: access,
  2043. body: {
  2044. branch: 'master',
  2045. commit_message: client.user.username + ': Settings removed',
  2046. actions: [
  2047. {
  2048. action: 'update',
  2049. file_path: process.env.file,
  2050. content: JSON.stringify( temp_settings, null, '\t' )
  2051. }
  2052. ]
  2053. },
  2054. json: true
  2055. }, function( error, response, body ) {
  2056. if ( error || !response || response.statusCode !== 201 || !body || body.error ) {
  2057. console.log( '- ' + ( response && response.statusCode ) + ': Error while removing the settings: ' + ( error || body && ( body.message || body.error ) ) );
  2058. }
  2059. else {
  2060. settings = JSON.parse(JSON.stringify(temp_settings));
  2061. console.log( '- Settings successfully removed.' );
  2062. }
  2063. } );
  2064. }
  2065. } );
  2066. client.login(process.env.token).catch( error => log_error(error, true, 'LOGIN-') );
  2067. client.on( 'error', error => log_error(error, true) );
  2068. client.on( 'warn', warning => log_warn(warning, false) );
  2069. if ( isDebug ) client.on( 'debug', debug => console.log( '- Debug: ' + debug ) );
  2070. function log_error(error, isBig = false, type = '') {
  2071. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  2072. if ( isDebug ) {
  2073. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n' + util.inspect( error ) + '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  2074. } else {
  2075. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n- ' + error.name + ': ' + error.message );
  2076. else console.log( '- ' + error.name + ': ' + error.message );
  2077. }
  2078. }
  2079. function log_warn(warning, api = true) {
  2080. if ( isDebug ) {
  2081. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  2082. } else {
  2083. if ( api ) console.warn( '- Warning: ' + Object.keys(warning).join(', ') );
  2084. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  2085. }
  2086. }
  2087. async function graceful(code = 1) {
  2088. stop = true;
  2089. console.log( '- SIGTERM: Preparing to close...' );
  2090. setTimeout( async () => {
  2091. console.log( '- SIGTERM: Destroying client...' );
  2092. await client.destroy();
  2093. setTimeout( async () => {
  2094. console.log( '- SIGTERM: Closing takes too long, terminating!' );
  2095. process.exit(code);
  2096. }, 1000 ).unref();
  2097. }, 2000 ).unref();
  2098. }
  2099. process.once( 'SIGINT', graceful );
  2100. process.once( 'SIGTERM', graceful );