bot.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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, wikiProjects} = 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: {
  31. status: 'online',
  32. activity: {
  33. type: 'STREAMING',
  34. name: process.env.prefix + 'help',
  35. url: 'https://www.twitch.tv/wikibot'
  36. }
  37. },
  38. ws: {
  39. large_threshold: 1000,
  40. intents: [
  41. 'GUILDS',
  42. 'GUILD_MESSAGES',
  43. 'GUILD_MESSAGE_REACTIONS',
  44. 'GUILD_VOICE_STATES',
  45. 'GUILD_INTEGRATIONS',
  46. 'DIRECT_MESSAGES',
  47. 'DIRECT_MESSAGE_REACTIONS'
  48. ]
  49. }
  50. } );
  51. global.pause = {};
  52. var isStop = false;
  53. client.on( 'ready', () => {
  54. console.log( '\n- ' + shardId + ': Successfully logged in as ' + client.user.username + '!\n' );
  55. Object.keys(voice).forEach( guild => {
  56. if ( !client.guilds.cache.has(guild) ) delete voice[guild];
  57. } );
  58. } );
  59. String.prototype.isMention = function(guild) {
  60. var text = this.trim();
  61. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  62. };
  63. Discord.Channel.prototype.isGuild = function() {
  64. return ['text', 'news'].includes( this.type );
  65. }
  66. Discord.Message.prototype.isAdmin = function() {
  67. return this.channel.isGuild() && this.member && ( this.member.permissions.has('MANAGE_GUILD') || ( this.isOwner() && this.evalUsed ) );
  68. };
  69. Discord.Message.prototype.isOwner = function() {
  70. return process.env.owner.split('|').includes( this.author.id );
  71. };
  72. Discord.Message.prototype.showEmbed = function() {
  73. return !this.channel.isGuild() || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  74. };
  75. Discord.Message.prototype.uploadFiles = function() {
  76. return !this.channel.isGuild() || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  77. };
  78. String.prototype.escapeFormatting = function(isMarkdown) {
  79. var text = this;
  80. if ( !isMarkdown ) text = text.replace( /[\(\)\\]/g, '\\$&' );
  81. return text.replace( /[`_\*~:<>{}@\|]|\/\//g, '\\$&' );
  82. };
  83. String.prototype.replaceSave = function(pattern, replacement) {
  84. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  85. };
  86. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  87. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  88. var emoji = ':error:440871715938238494';
  89. switch ( name ) {
  90. case 'nowiki':
  91. emoji = ':unknown_wiki:505884572001763348';
  92. break;
  93. case 'error':
  94. emoji = ':error:440871715938238494';
  95. break;
  96. default:
  97. emoji = name;
  98. }
  99. return this.react(emoji).catch(log_error);
  100. } else {
  101. console.log( '- Aborted, paused.' );
  102. return Promise.resolve();
  103. }
  104. };
  105. Discord.MessageReaction.prototype.removeEmoji = function() {
  106. return this.users.remove().catch(log_error);
  107. };
  108. Discord.Message.prototype.sendChannel = function(content, options = {}, ignorePause = false) {
  109. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  110. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  111. return this.channel.send(content, options).then( msg => {
  112. if ( msg.length ) msg.forEach( message => allowDelete(message, this.author.id) );
  113. else allowDelete(msg, this.author.id);
  114. return msg;
  115. }, error => {
  116. log_error(error);
  117. this.reactEmoji('error');
  118. } );
  119. } else {
  120. console.log( '- Aborted, paused.' );
  121. return Promise.resolve();
  122. }
  123. };
  124. Discord.Message.prototype.sendChannelError = function(content, options = {}) {
  125. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  126. return this.channel.send(content, options).then( msg => {
  127. if ( msg.length ) msg.forEach( message => {
  128. message.reactEmoji('error');
  129. allowDelete(message, this.author.id);
  130. } );
  131. else {
  132. msg.reactEmoji('error');
  133. allowDelete(msg, this.author.id);
  134. }
  135. return msg;
  136. }, error => {
  137. log_error(error);
  138. this.reactEmoji('error');
  139. } );
  140. };
  141. Discord.Message.prototype.replyMsg = function(content, options = {}, ignorePause = false, letDelete = true) {
  142. if ( !this.channel.isGuild() || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  143. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  144. return this.reply(content, options).then( msg => {
  145. if ( letDelete ) {
  146. if ( msg.length ) msg.forEach( message => allowDelete(message, this.author.id) );
  147. else allowDelete(msg, this.author.id);
  148. }
  149. return msg;
  150. }, error => {
  151. log_error(error);
  152. this.reactEmoji('error');
  153. } );
  154. } else {
  155. console.log( '- Aborted, paused.' );
  156. return Promise.resolve();
  157. }
  158. };
  159. /**
  160. * All users to delete their command responses.
  161. * @param {Discord.Message} msg - The response.
  162. * @param {String} author - The user.
  163. */
  164. function allowDelete(msg, author) {
  165. msg.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:120000} ).then( reaction => {
  166. if ( reaction.size ) {
  167. msg.delete().catch(log_error);
  168. }
  169. } );
  170. };
  171. String.prototype.hasPrefix = function(prefix, flags = '') {
  172. var suffix = '';
  173. if ( prefix.endsWith( ' ' ) ) {
  174. prefix = prefix.trim();
  175. suffix = '(?: |$)';
  176. }
  177. var regex = new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + suffix, flags );
  178. return regex.test(this.replace( /\u200b/g, '' ).toLowerCase());
  179. };
  180. client.on( 'message', msg => {
  181. if ( isStop || msg.type !== 'DEFAULT' || msg.system || msg.webhookID || msg.author.bot || msg.author.id === msg.client.user.id ) return;
  182. if ( !msg.content.hasPrefix(( msg.channel.isGuild() && patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  183. if ( msg.content === process.env.prefix + 'help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  184. if ( msg.channel.permissionsFor(msg.client.user).has('SEND_MESSAGES') ) {
  185. console.log( msg.guild.name + ': ' + msg.content );
  186. db.get( 'SELECT lang FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id], (dberror, row) => {
  187. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  188. msg.replyMsg( new Lang(( row || defaultSettings ).lang).get('general.prefix', patreons[msg.guild.id]), {}, true );
  189. } );
  190. }
  191. }
  192. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  193. }
  194. if ( msg.channel.isGuild() ) {
  195. var permissions = msg.channel.permissionsFor(msg.client.user);
  196. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  197. if ( missing.length ) {
  198. if ( msg.isAdmin() || msg.isOwner() ) {
  199. console.log( msg.guild.id + ': Missing permissions - ' + missing.join(', ') );
  200. if ( !missing.includes( 'SEND_MESSAGES' ) ) {
  201. db.get( 'SELECT lang FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id], (dberror, row) => {
  202. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  203. if ( msg.content.hasPrefix(( patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  204. msg.replyMsg( new Lang(( row || defaultSettings ).lang).get('general.missingperm') + ' `' + missing.join('`, `') + '`', {}, true );
  205. }
  206. } );
  207. }
  208. }
  209. return;
  210. }
  211. db.get( 'SELECT wiki, lang, role, inline FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id], (dberror, row) => {
  212. if ( dberror ) {
  213. console.log( '- Error while getting the wiki: ' + dberror );
  214. if ( permissions.has('SEND_MESSAGES') ) {
  215. msg.sendChannel( '⚠️ **Limited Functionality** ⚠️\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  216. newMessage(msg, new Lang());
  217. }
  218. return dberror;
  219. }
  220. if ( row ) {
  221. if ( msg.guild.roles.cache.has(row.role) && msg.guild.roles.cache.get(row.role).comparePositionTo(msg.member.roles.highest) > 0 && !msg.isAdmin() ) {
  222. msg.onlyVerifyCommand = true;
  223. }
  224. newMessage(msg, new Lang(row.lang), row.wiki, patreons[msg.guild.id], row.inline);
  225. }
  226. else {
  227. msg.defaultSettings = true;
  228. newMessage(msg, new Lang());
  229. }
  230. } );
  231. }
  232. else newMessage(msg, new Lang());
  233. } );
  234. client.on( 'voiceStateUpdate', (olds, news) => {
  235. if ( isStop || !( olds.guild.id in voice ) || !olds.guild.me.permissions.has('MANAGE_ROLES') || olds.channelID === news.channelID ) return;
  236. var lang = new Lang(voice[olds.guild.id], 'voice');
  237. if ( olds.member && olds.channel ) {
  238. var oldrole = olds.member.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + olds.channel.name );
  239. if ( oldrole && oldrole.comparePositionTo(olds.guild.me.roles.highest) < 0 ) {
  240. console.log( olds.guild.id + ': ' + olds.member.id + ' left the voice channel "' + olds.channel.id + '".' );
  241. olds.member.roles.remove( oldrole, lang.get('left', olds.member.displayName, olds.channel.name) ).catch(log_error);
  242. }
  243. }
  244. if ( news.member && news.channel ) {
  245. var newrole = news.guild.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + news.channel.name );
  246. if ( newrole && newrole.comparePositionTo(news.guild.me.roles.highest) < 0 ) {
  247. console.log( news.guild.id + ': ' + news.member.id + ' joined the voice channel "' + news.channel.id + '".' );
  248. news.member.roles.add( newrole, lang.get('join', news.member.displayName, news.channel.name) ).catch(log_error);
  249. }
  250. }
  251. } );
  252. client.on( 'guildCreate', guild => {
  253. console.log( '- I\'ve been added to a server.' );
  254. } );
  255. client.on( 'guildDelete', guild => {
  256. if ( !guild.available ) {
  257. console.log( '- ' + guild.id + ': This server isn\'t responding.' );
  258. return;
  259. }
  260. console.log( '- I\'ve been removed from a server.' );
  261. db.run( 'DELETE FROM discord WHERE main = ?', [guild.id], function (dberror) {
  262. if ( dberror ) {
  263. console.log( '- Error while removing the settings: ' + dberror );
  264. return dberror;
  265. }
  266. if ( guild.id in patreons ) client.shard.broadcastEval( `delete global.patreons['${guild.id}']` );
  267. if ( guild.id in voice ) delete voice[guild.id];
  268. if ( this.changes ) console.log( '- Settings successfully removed.' );
  269. } );
  270. } );
  271. client.on( 'error', error => log_error(error, true) );
  272. client.on( 'warn', warning => log_warn(warning, false) );
  273. client.login(process.env.token).catch( error => {
  274. log_error(error, true, 'LOGIN-');
  275. client.login(process.env.token).catch( error => {
  276. log_error(error, true, 'LOGIN-');
  277. client.login(process.env.token).catch( error => {
  278. log_error(error, true, 'LOGIN-');
  279. process.exit(1);
  280. } );
  281. } );
  282. } );
  283. if ( isDebug ) client.on( 'debug', debug => {
  284. if ( isDebug ) console.log( '- ' + shardId + ': Debug: ' + debug );
  285. } );
  286. global.log_error = function(error, isBig = false, type = '') {
  287. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  288. if ( isDebug ) {
  289. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  290. } else {
  291. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  292. else console.log( '- ' + error.name + ': ' + error.message );
  293. }
  294. }
  295. const common_warnings = {
  296. main: [
  297. 'Unrecognized parameters: piprop, explaintext, exsectionformat, exlimit.',
  298. 'Unrecognized parameter: piprop.'
  299. ],
  300. query: [
  301. 'Unrecognized values for parameter "prop": pageimages, extracts.',
  302. 'Unrecognized value for parameter "prop": pageimages.'
  303. ]
  304. }
  305. global.log_warn = function(warning, api = true) {
  306. if ( isDebug ) {
  307. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  308. }
  309. else if ( api ) {
  310. if ( common_warnings.main.includes( warning?.main?.['*'] ) ) delete warning.main;
  311. if ( common_warnings.query.includes( warning?.query?.['*'] ) ) delete warning.query;
  312. var warningKeys = Object.keys(warning);
  313. if ( warningKeys.length ) console.warn( '- Warning: ' + warningKeys.join(', ') );
  314. }
  315. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  316. }
  317. /**
  318. * End the process gracefully.
  319. * @param {NodeJS.Signals} signal - The signal received.
  320. */
  321. function graceful(signal) {
  322. isStop = true;
  323. console.log( '- ' + shardId + ': ' + signal + ': Preparing to close...' );
  324. setTimeout( () => {
  325. console.log( '- ' + shardId + ': ' + signal + ': Destroying client...' );
  326. client.destroy();
  327. db.close( dberror => {
  328. if ( dberror ) {
  329. console.log( '- ' + shardId + ': ' + signal + ': Error while closing the database connection: ' + dberror );
  330. return dberror;
  331. }
  332. console.log( '- ' + shardId + ': ' + signal + ': Closed the database connection.' );
  333. process.exit(0);
  334. } );
  335. }, 1000 ).unref();
  336. }
  337. process.once( 'SIGINT', graceful );
  338. process.once( 'SIGTERM', graceful );