bot.js 17 KB

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