bot.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. const util = require('util');
  2. util.inspect.defaultOptions = {compact:false,breakLength:Infinity};
  3. global.isDebug = ( process.argv[2] === 'debug' );
  4. global.shardId = null;
  5. process.on( 'message', message => {
  6. if ( !message.shard ) return;
  7. shardId = message.shard.id;
  8. } );
  9. global.got = require('got').extend( {
  10. throwHttpErrors: false,
  11. timeout: 5000,
  12. headers: {
  13. 'User-Agent': 'Wiki-Bot/' + ( isDebug ? 'testing' : process.env.npm_package_version ) + ' (Discord; ' + process.env.npm_package_name + ')'
  14. },
  15. responseType: 'json'
  16. } );
  17. const {defaultSettings} = require('./util/default.json');
  18. const Lang = require('./util/i18n.js');
  19. const newMessage = require('./util/newMessage.js');
  20. global.patreons = {};
  21. global.voice = {};
  22. const db = require('./util/database.js');
  23. const Discord = require('discord.js');
  24. const client = new Discord.Client( {
  25. messageCacheLifetime: 300,
  26. messageSweepInterval: 300,
  27. allowedMentions: {
  28. parse: []
  29. },
  30. presence: ( process.env.READONLY ? {
  31. status: 'dnd',
  32. activity: {
  33. type: 'PLAYING',
  34. name: 'READONLY: ' + process.env.prefix + 'test'
  35. }
  36. } : {
  37. status: 'online',
  38. activity: {
  39. type: 'STREAMING',
  40. name: process.env.prefix + 'help',
  41. url: 'https://www.twitch.tv/wikibot'
  42. }
  43. } ),
  44. ws: {
  45. large_threshold: 1000,
  46. intents: [
  47. 'GUILDS',
  48. 'GUILD_MESSAGES',
  49. 'GUILD_MESSAGE_REACTIONS',
  50. 'GUILD_VOICE_STATES',
  51. 'GUILD_INTEGRATIONS',
  52. 'DIRECT_MESSAGES',
  53. 'DIRECT_MESSAGE_REACTIONS'
  54. ]
  55. }
  56. } );
  57. global.pause = {};
  58. var isStop = false;
  59. client.on( 'ready', () => {
  60. console.log( '\n- ' + shardId + ': Successfully logged in as ' + client.user.username + '!\n' );
  61. Object.keys(voice).forEach( guild => {
  62. if ( !client.guilds.cache.has(guild) ) delete voice[guild];
  63. } );
  64. } );
  65. String.prototype.isMention = function(guild) {
  66. var text = this.trim();
  67. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  68. };
  69. Discord.Channel.prototype.isGuild = function() {
  70. return ['text', 'news'].includes( this.type );
  71. }
  72. Discord.Message.prototype.isAdmin = function() {
  73. return this.channel.isGuild() && this.member && ( this.member.permissions.has('MANAGE_GUILD') || ( this.isOwner() && this.evalUsed ) );
  74. };
  75. Discord.Message.prototype.isOwner = function() {
  76. return process.env.owner.split('|').includes( this.author.id );
  77. };
  78. Discord.Message.prototype.showEmbed = function() {
  79. return !this.channel.isGuild() || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  80. };
  81. Discord.Message.prototype.uploadFiles = function() {
  82. return !this.channel.isGuild() || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  83. };
  84. String.prototype.escapeFormatting = function(isMarkdown) {
  85. var text = this;
  86. if ( !isMarkdown ) text = text.replace( /[\(\)\\]/g, '\\$&' );
  87. return text.replace( /[`_\*~:<>{}@\|]|\/\//g, '\\$&' );
  88. };
  89. String.prototype.replaceSave = function(pattern, replacement) {
  90. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  91. };
  92. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  93. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  94. var emoji = ':error:440871715938238494';
  95. switch ( name ) {
  96. case 'nowiki':
  97. emoji = ':unknown_wiki:505884572001763348';
  98. break;
  99. case 'error':
  100. emoji = ':error:440871715938238494';
  101. break;
  102. default:
  103. emoji = name;
  104. }
  105. return this.react(emoji).catch(log_error);
  106. } else {
  107. console.log( '- Aborted, paused.' );
  108. return Promise.resolve();
  109. }
  110. };
  111. Discord.MessageReaction.prototype.removeEmoji = function() {
  112. return this.users.remove().catch(log_error);
  113. };
  114. Discord.Message.prototype.sendChannel = function(content, options = {}, ignorePause = false) {
  115. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  116. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  117. return this.channel.send(content, options).then( msg => {
  118. if ( msg.length ) msg.forEach( message => allowDelete(message, this.author.id) );
  119. else allowDelete(msg, this.author.id);
  120. return msg;
  121. }, error => {
  122. log_error(error);
  123. this.reactEmoji('error');
  124. } );
  125. } else {
  126. console.log( '- Aborted, paused.' );
  127. return Promise.resolve();
  128. }
  129. };
  130. Discord.Message.prototype.sendChannelError = function(content, options = {}) {
  131. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  132. return this.channel.send(content, options).then( msg => {
  133. if ( msg.length ) msg.forEach( message => {
  134. message.reactEmoji('error');
  135. allowDelete(message, this.author.id);
  136. } );
  137. else {
  138. msg.reactEmoji('error');
  139. allowDelete(msg, this.author.id);
  140. }
  141. return msg;
  142. }, error => {
  143. log_error(error);
  144. this.reactEmoji('error');
  145. } );
  146. };
  147. Discord.Message.prototype.replyMsg = function(content, options = {}, ignorePause = false, letDelete = true) {
  148. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  149. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  150. return this.reply(content, options).then( msg => {
  151. if ( letDelete ) {
  152. if ( msg.length ) msg.forEach( message => allowDelete(message, this.author.id) );
  153. else allowDelete(msg, this.author.id);
  154. }
  155. return msg;
  156. }, error => {
  157. log_error(error);
  158. this.reactEmoji('error');
  159. } );
  160. } else {
  161. console.log( '- Aborted, paused.' );
  162. return Promise.resolve();
  163. }
  164. };
  165. /**
  166. * All users to delete their command responses.
  167. * @param {Discord.Message} msg - The response.
  168. * @param {String} author - The user.
  169. */
  170. function allowDelete(msg, author) {
  171. msg.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:120000} ).then( reaction => {
  172. if ( reaction.size ) {
  173. msg.delete().catch(log_error);
  174. }
  175. } );
  176. };
  177. String.prototype.hasPrefix = function(prefix, flags = '') {
  178. var suffix = '';
  179. if ( prefix.endsWith( ' ' ) ) {
  180. prefix = prefix.trim();
  181. suffix = '(?: |$)';
  182. }
  183. var regex = new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + suffix, flags );
  184. return regex.test(this.replace( /\u200b/g, '' ).toLowerCase());
  185. };
  186. const Wiki = require('./util/wiki.js');
  187. const slash_inline = require('./interactions/inline.js');
  188. const fs = require('fs');
  189. var slash = {};
  190. fs.readdir( './interactions', (error, files) => {
  191. if ( error ) return error;
  192. files.filter( file => file.endsWith('.js') ).forEach( file => {
  193. var command = require('./interactions/' + file);
  194. slash[command.name] = command.run;
  195. } );
  196. } );
  197. /*
  198. !test eval got.post(`https://discord.com/api/v8/applications/${msg.client.user.id}/commands`, {
  199. headers:{Authorization: `Bot ${process.env.token}`},
  200. json: require('../interactions/commands.json')[0]
  201. }).then(response=>console.log(response.statusCode,response.body))
  202. */
  203. client.on( 'raw', rawEvent => {
  204. if ( rawEvent.t !== 'INTERACTION_CREATE' ) return;
  205. var interaction = rawEvent.d;
  206. if ( interaction.version !== 1 || interaction.type !== 2 ) return;
  207. interaction.application_id = client.user.id;
  208. if ( !slash.hasOwnProperty(interaction.data.name) ) {
  209. consol.log( '- Slash: Unknown command: ' + interaction.data.name );
  210. return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
  211. json: {
  212. //type: 4,
  213. type: 3,
  214. data: {
  215. content: '[<:error:440871715938238494> Unknown Command! <:error:440871715938238494>](<' + process.env.invite + '>)',
  216. allowed_mentions: {
  217. parse: []
  218. },
  219. flags: 64
  220. }
  221. }
  222. } ).then( response => {
  223. if ( response.statusCode !== 204 ) {
  224. console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
  225. }
  226. }, log_error );
  227. }
  228. if ( !interaction.guild_id ) return slash[interaction.data.name](interaction, new Lang(), new Wiki());
  229. var guild = client.guilds.cache.get(interaction.guild_id);
  230. db.get( 'SELECT wiki, lang, role FROM discord WHERE guild = ? AND (channel = ? OR channel = ? OR channel IS NULL) ORDER BY channel DESC', [interaction.guild_id, interaction.channel_id, '#' + guild?.channels.cache.get(interaction.channel_id)?.parentID], (dberror, row) => {
  231. if ( dberror ) {
  232. console.log( '- Error while getting the wiki: ' + dberror );
  233. return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
  234. json: {
  235. //type: 4,
  236. type: 3,
  237. data: {
  238. content: '[<:error:440871715938238494> Error! <:error:440871715938238494>](<' + process.env.invite + '>)',
  239. allowed_mentions: {
  240. parse: []
  241. },
  242. flags: 64
  243. }
  244. }
  245. } ).then( response => {
  246. if ( response.statusCode !== 204 ) {
  247. console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
  248. }
  249. }, log_error );
  250. }
  251. var lang = new Lang(row.lang || defaultSettings.lang);
  252. if ( row.role && !interaction.member.roles.includes( row.role ) && guild?.roles.cache.has(row.role) && ( !interaction.member.roles.length || !interaction.member.roles.some( role => guild.roles.cache.get(role)?.comparePositionTo(row.role) >= 0 ) ) ) {
  253. return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
  254. json: {
  255. //type: 4,
  256. type: 3,
  257. data: {
  258. content: lang.get('interaction.missingrole', '<@&' + row.role + '>'),
  259. allowed_mentions: {
  260. parse: []
  261. },
  262. flags: 64
  263. }
  264. }
  265. } ).then( response => {
  266. if ( response.statusCode !== 204 ) {
  267. console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
  268. }
  269. }, log_error );
  270. }
  271. var wiki = new Wiki(row.wiki || defaultSettings.wiki);
  272. return slash[interaction.data.name](interaction, lang, wiki, guild);
  273. } );
  274. } );
  275. client.on( 'message', msg => {
  276. if ( isStop || msg.type !== 'DEFAULT' || msg.system || msg.webhookID || msg.author.bot || msg.author.id === msg.client.user.id ) return;
  277. if ( !msg.content.hasPrefix(( msg.channel.isGuild() && patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  278. if ( msg.content === process.env.prefix + 'help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  279. if ( msg.channel.permissionsFor(msg.client.user).has('SEND_MESSAGES') ) {
  280. console.log( msg.guild.name + ': ' + msg.content );
  281. db.get( 'SELECT lang FROM discord WHERE guild = ? AND (channel = ? OR channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id, '#' + msg.channel.parentID], (dberror, row) => {
  282. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  283. msg.replyMsg( new Lang(( row || defaultSettings ).lang).get('general.prefix', patreons[msg.guild.id]), {}, true );
  284. } );
  285. }
  286. }
  287. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  288. }
  289. if ( msg.channel.isGuild() ) {
  290. var permissions = msg.channel.permissionsFor(msg.client.user);
  291. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  292. if ( missing.length ) {
  293. if ( msg.isAdmin() || msg.isOwner() ) {
  294. console.log( msg.guild.id + ': Missing permissions - ' + missing.join(', ') );
  295. if ( !missing.includes( 'SEND_MESSAGES' ) ) {
  296. db.get( 'SELECT lang FROM discord WHERE guild = ? AND (channel = ? OR channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id, '#' + msg.channel.parentID], (dberror, row) => {
  297. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  298. if ( msg.content.hasPrefix(( patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  299. msg.replyMsg( new Lang(( row || defaultSettings ).lang).get('general.missingperm') + ' `' + missing.join('`, `') + '`', {}, true );
  300. }
  301. } );
  302. }
  303. }
  304. return;
  305. }
  306. db.get( 'SELECT wiki, lang, role, inline FROM discord WHERE guild = ? AND (channel = ? OR channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id, '#' + msg.channel.parentID], (dberror, row) => {
  307. if ( dberror ) {
  308. console.log( '- Error while getting the wiki: ' + dberror );
  309. if ( permissions.has('SEND_MESSAGES') ) {
  310. msg.sendChannel( '⚠️ **Limited Functionality** ⚠️\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  311. newMessage(msg, new Lang());
  312. }
  313. return dberror;
  314. }
  315. if ( row ) {
  316. if ( msg.guild.roles.cache.has(row.role) && msg.guild.roles.cache.get(row.role).comparePositionTo(msg.member.roles.highest) > 0 && !msg.isAdmin() ) {
  317. msg.onlyVerifyCommand = true;
  318. }
  319. newMessage(msg, new Lang(row.lang), row.wiki, patreons[msg.guild.id], row.inline);
  320. }
  321. else {
  322. msg.defaultSettings = true;
  323. newMessage(msg, new Lang());
  324. }
  325. } );
  326. }
  327. else newMessage(msg, new Lang());
  328. } );
  329. client.on( 'voiceStateUpdate', (olds, news) => {
  330. if ( isStop || !( voice.hasOwnProperty(olds.guild.id) ) || !olds.guild.me.permissions.has('MANAGE_ROLES') || olds.channelID === news.channelID ) return;
  331. var lang = new Lang(voice[olds.guild.id], 'voice');
  332. if ( olds.member && olds.channel ) {
  333. var oldrole = olds.member.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + olds.channel.name );
  334. if ( oldrole && oldrole.comparePositionTo(olds.guild.me.roles.highest) < 0 ) {
  335. console.log( olds.guild.id + ': ' + olds.member.id + ' left the voice channel "' + olds.channel.id + '".' );
  336. olds.member.roles.remove( oldrole, lang.get('left', olds.member.displayName, olds.channel.name) ).catch(log_error);
  337. }
  338. }
  339. if ( news.member && news.channel ) {
  340. var newrole = news.guild.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + news.channel.name );
  341. if ( newrole && newrole.comparePositionTo(news.guild.me.roles.highest) < 0 ) {
  342. console.log( news.guild.id + ': ' + news.member.id + ' joined the voice channel "' + news.channel.id + '".' );
  343. news.member.roles.add( newrole, lang.get('join', news.member.displayName, news.channel.name) ).catch(log_error);
  344. }
  345. }
  346. } );
  347. client.on( 'guildCreate', guild => {
  348. console.log( '- I\'ve been added to a server.' );
  349. } );
  350. client.on( 'guildDelete', guild => {
  351. if ( !guild.available ) {
  352. console.log( '- ' + guild.id + ': This server isn\'t responding.' );
  353. return;
  354. }
  355. console.log( '- I\'ve been removed from a server.' );
  356. db.run( 'DELETE FROM discord WHERE main = ?', [guild.id], function (dberror) {
  357. if ( dberror ) {
  358. console.log( '- Error while removing the settings: ' + dberror );
  359. return dberror;
  360. }
  361. if ( patreons.hasOwnProperty(guild.id) ) client.shard.broadcastEval( `delete global.patreons['${guild.id}']` );
  362. if ( voice.hasOwnProperty(guild.id) ) delete voice[guild.id];
  363. if ( this.changes ) console.log( '- Settings successfully removed.' );
  364. } );
  365. } );
  366. client.on( 'error', error => log_error(error, true) );
  367. client.on( 'warn', warning => log_warn(warning, false) );
  368. client.login(process.env.token).catch( error => {
  369. log_error(error, true, 'LOGIN-');
  370. client.login(process.env.token).catch( error => {
  371. log_error(error, true, 'LOGIN-');
  372. client.login(process.env.token).catch( error => {
  373. log_error(error, true, 'LOGIN-');
  374. process.exit(1);
  375. } );
  376. } );
  377. } );
  378. if ( isDebug ) client.on( 'debug', debug => {
  379. if ( isDebug ) console.log( '- ' + shardId + ': Debug: ' + debug );
  380. } );
  381. global.log_error = function(error, isBig = false, type = '') {
  382. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  383. if ( isDebug ) {
  384. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  385. } else {
  386. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  387. else console.log( '- ' + error.name + ': ' + error.message );
  388. }
  389. }
  390. const common_warnings = {
  391. main: [
  392. 'Unrecognized parameters: piprop, explaintext, exsectionformat, exlimit.',
  393. 'Unrecognized parameters: explaintext, exsectionformat, exlimit.',
  394. 'Unrecognized parameter: piprop.'
  395. ],
  396. query: [
  397. 'Unrecognized values for parameter "prop": pageimages, extracts.',
  398. 'Unrecognized values for parameter "prop": pageimages, extracts',
  399. 'Unrecognized value for parameter "prop": extracts.',
  400. 'Unrecognized value for parameter "prop": pageimages.'
  401. ]
  402. }
  403. global.log_warn = function(warning, api = true) {
  404. if ( isDebug ) {
  405. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  406. }
  407. else if ( api ) {
  408. if ( common_warnings.main.includes( warning?.main?.['*'] ) ) delete warning.main;
  409. if ( common_warnings.query.includes( warning?.query?.['*'] ) ) delete warning.query;
  410. var warningKeys = Object.keys(warning);
  411. if ( warningKeys.length ) console.warn( '- Warning: ' + warningKeys.join(', ') );
  412. }
  413. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  414. }
  415. /**
  416. * End the process gracefully.
  417. * @param {NodeJS.Signals} signal - The signal received.
  418. */
  419. function graceful(signal) {
  420. isStop = true;
  421. console.log( '- ' + shardId + ': ' + signal + ': Preparing to close...' );
  422. setTimeout( () => {
  423. console.log( '- ' + shardId + ': ' + signal + ': Destroying client...' );
  424. client.destroy();
  425. db.close( dberror => {
  426. if ( dberror ) {
  427. console.log( '- ' + shardId + ': ' + signal + ': Error while closing the database connection: ' + dberror );
  428. return dberror;
  429. }
  430. console.log( '- ' + shardId + ': ' + signal + ': Closed the database connection.' );
  431. process.exit(0);
  432. } );
  433. }, 1000 ).unref();
  434. }
  435. process.once( 'SIGINT', graceful );
  436. process.once( 'SIGTERM', graceful );