bot.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. } );
  16. const {defaultSettings, wikiProjects} = require('./util/default.json');
  17. const Lang = require('./util/i18n.js');
  18. const newMessage = require('./util/newMessage.js');
  19. global.patreons = {};
  20. global.voice = {};
  21. var db = require('./util/database.js');
  22. const Discord = require('discord.js');
  23. var client = new Discord.Client( {
  24. messageCacheLifetime: 300,
  25. messageSweepInterval: 300,
  26. allowedMentions: {
  27. parse: []
  28. },
  29. presence: {
  30. status: 'online',
  31. activity: {
  32. type: 'STREAMING',
  33. name: process.env.prefix + 'help',
  34. url: 'https://www.twitch.tv/wikibot'
  35. }
  36. },
  37. ws: {
  38. large_threshold: 1000,
  39. intents: [
  40. 'GUILDS',
  41. 'GUILD_MESSAGES',
  42. 'GUILD_MESSAGE_REACTIONS',
  43. 'GUILD_VOICE_STATES',
  44. 'GUILD_INTEGRATIONS',
  45. 'DIRECT_MESSAGES',
  46. 'DIRECT_MESSAGE_REACTIONS'
  47. ]
  48. }
  49. } );
  50. global.pause = {};
  51. var isStop = false;
  52. client.on( 'ready', () => {
  53. client.ready = true;
  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. client.on( 'shardDisconnect', () => client.ready = false );
  60. String.prototype.noWiki = function(href) {
  61. if ( !href ) return true;
  62. else if ( this.startsWith( 'https://www.' ) && ( this.endsWith( '.gamepedia.com/' ) || this.isFandom() ) ) return true;
  63. else if ( this.isFandom() ) return [
  64. this.replace( /^https:\/\/([a-z\d-]{1,50}\.(?:fandom\.com|wikia\.org))\/(?:[a-z-]{1,8}\/)?$/, 'https://community.fandom.com/wiki/Community_Central:Not_a_valid_community?from=$1' ),
  65. this + 'language-wikis'
  66. ].includes( href.replace( /Unexpected token < in JSON at position 0 in "([^ ]+)"/, '$1' ) );
  67. else return false;
  68. };
  69. String.prototype.isFandom = function() {
  70. return /^https:\/\/[a-z\d-]{1,50}\.(?:fandom\.com|wikia\.org)\/(?:[a-z-]{1,8}\/)?$/.test(this);
  71. };
  72. String.prototype.isMention = function(guild) {
  73. var text = this.trim();
  74. return text === '@' + client.user.username || text.replace( /^<@!?(\d+)>$/, '$1' ) === client.user.id || ( guild && text === '@' + guild.me.displayName );
  75. };
  76. Discord.Message.prototype.isAdmin = function() {
  77. return this.channel.type === 'text' && this.member && ( this.member.permissions.has('MANAGE_GUILD') || ( this.isOwner() && this.evalUsed ) );
  78. };
  79. Discord.Message.prototype.isOwner = function() {
  80. return process.env.owner.split('|').includes( this.author.id );
  81. };
  82. Discord.Message.prototype.showEmbed = function() {
  83. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('EMBED_LINKS');
  84. };
  85. Discord.Message.prototype.uploadFiles = function() {
  86. return this.channel.type !== 'text' || this.channel.permissionsFor(client.user).has('ATTACH_FILES');
  87. };
  88. String.prototype.toLink = function(title = '', querystring = '', fragment = '', {server: serverURL, articlepath: articlePath} = {}, isMarkdown = false) {
  89. var linksuffix = ( querystring ? '?' + querystring : '' ) + ( fragment ? '#' + fragment.toSection() : '' );
  90. if ( serverURL && articlePath ) return serverURL.replace( /^(?:https?:)?\/\//, 'https://' ) + articlePath.replaceSave( '$1', title.toTitle(isMarkdown, articlePath.includes( '?' )) ) + ( articlePath.includes( '?' ) && linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  91. if ( this.endsWith( '.gamepedia.com/' ) ) return this + title.toTitle(isMarkdown) + linksuffix;
  92. if ( this.isFandom() ) return this + 'wiki/' + title.toTitle(isMarkdown) + linksuffix;
  93. let project = wikiProjects.find( project => this.split('/')[2].endsWith( project.name ) );
  94. if ( project ) {
  95. let regex = this.match( new RegExp( '^https://' + project.regex + project.scriptPath + '$' ) );
  96. if ( regex ) return 'https://' + regex[1] + project.articlePath + title.toTitle(isMarkdown, project.articlePath.includes( '?' )) + ( project.articlePath.includes( '?' ) && linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  97. }
  98. return this + 'index.php?title=' + title.toTitle(isMarkdown, true) + ( linksuffix.startsWith( '?' ) ? '&' + linksuffix.substring(1) : linksuffix );
  99. };
  100. String.prototype.toDescLink = function(title = '') {
  101. return this + 'wiki/' + encodeURIComponent( title.replace( / /g, '_' ) );
  102. };
  103. String.prototype.toTitle = function(isMarkdown = false, inQuery = false) {
  104. var title = this.replace( / /g, '_' ).replace( /\%/g, '%25' ).replace( /\\/g, '%5C' ).replace( /\?/g, '%3F' ).replace( /@(here|everyone)/g, '%40$1' );
  105. if ( inQuery ) title = title.replace( /\&/g, '%26' );
  106. if ( isMarkdown ) title = title.replace( /([\(\)])/g, '\\$1' );
  107. return title;
  108. };
  109. String.prototype.toSearch = function() {
  110. return encodeURIComponent( this ).replace( /%20/g, '+' );
  111. };
  112. String.prototype.toSection = function() {
  113. return encodeURIComponent( this.replace( / /g, '_' ) ).replace( /\'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\%/g, '.' );
  114. };
  115. String.prototype.toFormatting = function(showEmbed = false, ...args) {
  116. if ( showEmbed ) return this.toMarkdown(...args);
  117. else return this.toPlaintext();
  118. };
  119. String.prototype.toMarkdown = function(wiki, path, title = '') {
  120. var text = this.replace( /[\(\)\\]/g, '\\$&' );
  121. var link = null;
  122. var regex = /\[\[(?:([^\|\]]+)\|)?([^\]]+)\]\]([a-z]*)/g;
  123. while ( ( link = regex.exec(text) ) !== null ) {
  124. var pagetitle = ( link[1] || link[2] );
  125. var page = wiki.toLink(( /^[#\/]/.test(pagetitle) ? title + ( pagetitle.startsWith( '/' ) ? pagetitle : '' ) : pagetitle ), '', ( pagetitle.startsWith( '#' ) ? pagetitle.substring(1) : '' ), path, true);
  126. text = text.replaceSave( link[0], '[' + link[2] + link[3] + '](' + page + ')' );
  127. }
  128. regex = /\/\*\s*([^\*]+?)\s*\*\/\s*(.)?/g;
  129. while ( title !== '' && ( link = regex.exec(text) ) !== null ) {
  130. text = text.replaceSave( link[0], '[→' + link[1] + '](' + wiki.toLink(title, '', link[1], path, true) + ')' + ( link[2] ? ': ' + link[2] : '' ) );
  131. }
  132. return text.escapeFormatting(true);
  133. };
  134. String.prototype.toPlaintext = function() {
  135. return this.replace( /\[\[(?:[^\|\]]+\|)?([^\]]+)\]\]/g, '$1' ).replace( /\/\*\s*([^\*]+?)\s*\*\//g, '→$1:' ).escapeFormatting();
  136. };
  137. String.prototype.escapeFormatting = function(isMarkdown) {
  138. var text = this;
  139. if ( !isMarkdown ) text = text.replace( /[\(\)\\]/g, '\\$&' );
  140. return text.replace( /[`_\*~:<>{}@\|]|\/\//g, '\\$&' );
  141. };
  142. String.prototype.replaceSave = function(pattern, replacement) {
  143. return this.replace( pattern, ( typeof replacement === 'string' ? replacement.replace( /\$/g, '$$$$' ) : replacement ) );
  144. };
  145. Discord.Message.prototype.reactEmoji = function(name, ignorePause = false) {
  146. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  147. var emoji = ':error:440871715938238494';
  148. switch ( name ) {
  149. case 'nowiki':
  150. emoji = ':unknown_wiki:505884572001763348';
  151. break;
  152. case 'error':
  153. emoji = ':error:440871715938238494';
  154. break;
  155. default:
  156. emoji = name;
  157. }
  158. return this.react(emoji).catch(log_error);
  159. } else {
  160. console.log( '- Aborted, paused.' );
  161. return Promise.resolve();
  162. }
  163. };
  164. Discord.MessageReaction.prototype.removeEmoji = function() {
  165. return this.users.remove().catch(log_error);
  166. };
  167. Discord.Message.prototype.sendChannel = function(content, options = {}, ignorePause = false) {
  168. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  169. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  170. return this.channel.send(content, options).then( msg => {
  171. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  172. else msg.allowDelete(this.author.id);
  173. return msg;
  174. }, error => {
  175. log_error(error);
  176. this.reactEmoji('error');
  177. } );
  178. } else {
  179. console.log( '- Aborted, paused.' );
  180. return Promise.resolve();
  181. }
  182. };
  183. Discord.Message.prototype.sendChannelError = function(content, options = {}) {
  184. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  185. return this.channel.send(content, options).then( msg => {
  186. if ( msg.length ) msg.forEach( message => {
  187. message.reactEmoji('error');
  188. message.allowDelete(this.author.id);
  189. } );
  190. else {
  191. msg.reactEmoji('error');
  192. msg.allowDelete(this.author.id);
  193. }
  194. return msg;
  195. }, error => {
  196. log_error(error);
  197. this.reactEmoji('error');
  198. } );
  199. };
  200. Discord.Message.prototype.replyMsg = function(content, options = {}, ignorePause = false, allowDelete = true) {
  201. if ( this.channel.type !== 'text' || !pause[this.guild.id] || ( ignorePause && ( this.isAdmin() || this.isOwner() ) ) ) {
  202. if ( !options.allowedMentions ) options.allowedMentions = {users:[this.author.id]};
  203. return this.reply(content, options).then( msg => {
  204. if ( allowDelete ) {
  205. if ( msg.length ) msg.forEach( message => message.allowDelete(this.author.id) );
  206. else msg.allowDelete(this.author.id);
  207. }
  208. return msg;
  209. }, error => {
  210. log_error(error);
  211. this.reactEmoji('error');
  212. } );
  213. } else {
  214. console.log( '- Aborted, paused.' );
  215. return Promise.resolve();
  216. }
  217. };
  218. Discord.Message.prototype.deleteMsg = function(timeout = 0) {
  219. return this.delete({timeout}).catch(log_error);
  220. };
  221. Discord.Message.prototype.allowDelete = function(author) {
  222. return this.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:120000} ).then( reaction => {
  223. if ( reaction.size ) {
  224. this.deleteMsg();
  225. }
  226. } );
  227. };
  228. String.prototype.hasPrefix = function(prefix, flags = '') {
  229. var suffix = '';
  230. if ( prefix.endsWith( ' ' ) ) {
  231. prefix = prefix.trim();
  232. suffix = '(?: |$)';
  233. }
  234. var regex = new RegExp( '^' + prefix.replace( /\W/g, '\\$&' ) + suffix, flags );
  235. return regex.test(this.replace( /\u200b/g, '' ).toLowerCase());
  236. };
  237. client.on( 'message', msg => {
  238. if ( isStop || msg.type !== 'DEFAULT' || msg.system || msg.webhookID || msg.author.bot || msg.author.id === msg.client.user.id ) return;
  239. if ( !msg.content.hasPrefix(( msg.channel.type === 'text' && patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  240. if ( msg.content === process.env.prefix + 'help' && ( msg.isAdmin() || msg.isOwner() ) ) {
  241. if ( msg.channel.permissionsFor(msg.client.user).has('SEND_MESSAGES') ) {
  242. console.log( msg.guild.name + ': ' + msg.content );
  243. 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) => {
  244. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  245. msg.replyMsg( new Lang(( row || defaultSettings ).lang).get('general.prefix', patreons[msg.guild.id]), {}, true );
  246. } );
  247. }
  248. }
  249. if ( !( msg.content.includes( '[[' ) && msg.content.includes( ']]' ) ) && !( msg.content.includes( '{{' ) && msg.content.includes( '}}' ) ) ) return;
  250. }
  251. if ( msg.channel.type === 'text' ) {
  252. var permissions = msg.channel.permissionsFor(msg.client.user);
  253. var missing = permissions.missing(['SEND_MESSAGES','ADD_REACTIONS','USE_EXTERNAL_EMOJIS','READ_MESSAGE_HISTORY']);
  254. if ( missing.length ) {
  255. if ( msg.isAdmin() || msg.isOwner() ) {
  256. console.log( msg.guild.id + ': Missing permissions - ' + missing.join(', ') );
  257. if ( !missing.includes( 'SEND_MESSAGES' ) ) {
  258. 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) => {
  259. if ( dberror ) console.log( '- Error while getting the lang: ' + dberror );
  260. if ( msg.content.hasPrefix(( patreons[msg.guild.id] || process.env.prefix ), 'm') ) {
  261. msg.replyMsg( new Lang(( row || defaultSettings ).lang).get('general.missingperm') + ' `' + missing.join('`, `') + '`', {}, true );
  262. }
  263. } );
  264. }
  265. }
  266. return;
  267. }
  268. db.get( 'SELECT wiki, lang, inline FROM discord WHERE guild = ? AND (channel = ? OR channel IS NULL) ORDER BY channel DESC', [msg.guild.id, msg.channel.id], (dberror, row) => {
  269. if ( dberror ) {
  270. console.log( '- Error while getting the wiki: ' + dberror );
  271. if ( permissions.has('SEND_MESSAGES') ) {
  272. msg.sendChannel( '⚠️ **Limited Functionality** ⚠️\nNo settings found, please contact the bot owner!\n' + process.env.invite, {}, true );
  273. newMessage(msg, new Lang());
  274. }
  275. return dberror;
  276. }
  277. if ( row ) newMessage(msg, new Lang(row.lang), row.wiki, patreons[msg.guild.id], row.inline);
  278. else {
  279. msg.defaultSettings = true;
  280. newMessage(msg, new Lang());
  281. }
  282. } );
  283. }
  284. else newMessage(msg, new Lang());
  285. } );
  286. client.on( 'voiceStateUpdate', (olds, news) => {
  287. if ( isStop || !( olds.guild.id in voice ) || !olds.guild.me.permissions.has('MANAGE_ROLES') || olds.channelID === news.channelID ) return;
  288. var lang = new Lang(voice[olds.guild.id], 'voice');
  289. if ( olds.member && olds.channel ) {
  290. var oldrole = olds.member.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + olds.channel.name );
  291. if ( oldrole && oldrole.comparePositionTo(olds.guild.me.roles.highest) < 0 ) {
  292. console.log( olds.guild.id + ': ' + olds.member.id + ' left the voice channel "' + olds.channel.id + '".' );
  293. olds.member.roles.remove( oldrole, lang.get('left', olds.member.displayName, olds.channel.name) ).catch(log_error);
  294. }
  295. }
  296. if ( news.member && news.channel ) {
  297. var newrole = news.guild.roles.cache.find( role => role.name === lang.get('channel') + ' – ' + news.channel.name );
  298. if ( newrole && newrole.comparePositionTo(news.guild.me.roles.highest) < 0 ) {
  299. console.log( news.guild.id + ': ' + news.member.id + ' joined the voice channel "' + news.channel.id + '".' );
  300. news.member.roles.add( newrole, lang.get('join', news.member.displayName, news.channel.name) ).catch(log_error);
  301. }
  302. }
  303. } );
  304. client.on( 'guildCreate', guild => {
  305. console.log( '- I\'ve been added to a server.' );
  306. } );
  307. client.on( 'guildDelete', guild => {
  308. if ( !guild.available ) {
  309. console.log( '- ' + guild.id + ': This server isn\'t responding.' );
  310. return;
  311. }
  312. console.log( '- I\'ve been removed from a server.' );
  313. db.run( 'DELETE FROM discord WHERE guild = ?', [guild.id], function (dberror) {
  314. if ( dberror ) {
  315. console.log( '- Error while removing the settings: ' + dberror );
  316. return dberror;
  317. }
  318. if ( guild.id in patreons ) client.shard.broadcastEval( `delete global.patreons['${guild.id}']` );
  319. if ( guild.id in voice ) delete voice[guild.id];
  320. if ( this.changes ) console.log( '- Settings successfully removed.' );
  321. } );
  322. db.run( 'DELETE FROM verification WHERE guild = ?', [guild.id], function (dberror) {
  323. if ( dberror ) {
  324. console.log( '- Error while removing the verifications: ' + dberror );
  325. return dberror;
  326. }
  327. if ( this.changes ) console.log( '- Verifications successfully removed.' );
  328. } );
  329. db.run( 'DELETE FROM rcgcdw WHERE guild = ?', [guild.id], function (dberror) {
  330. if ( dberror ) {
  331. console.log( '- Error while removing the RcGcDw: ' + dberror );
  332. return dberror;
  333. }
  334. if ( this.changes ) console.log( '- RcGcDw successfully removed.' );
  335. } );
  336. } );
  337. client.on( 'error', error => log_error(error, true) );
  338. client.on( 'warn', warning => log_warn(warning, false) );
  339. client.login(process.env.token).catch( error => {
  340. log_error(error, true, 'LOGIN-');
  341. client.login(process.env.token).catch( error => {
  342. log_error(error, true, 'LOGIN-');
  343. client.login(process.env.token).catch( error => {
  344. log_error(error, true, 'LOGIN-');
  345. process.exit(1);
  346. } );
  347. } );
  348. } );
  349. if ( isDebug ) client.on( 'debug', debug => {
  350. if ( isDebug ) console.log( '- ' + shardId + ': Debug: ' + debug );
  351. } );
  352. global.log_error = function(error, isBig = false, type = '') {
  353. var time = new Date(Date.now()).toLocaleTimeString('de-DE', { timeZone: 'Europe/Berlin' });
  354. if ( isDebug ) {
  355. console.error( '--- ' + type + 'ERROR START ' + time + ' ---\n', error, '\n--- ' + type + 'ERROR END ' + time + ' ---' );
  356. } else {
  357. if ( isBig ) console.log( '--- ' + type + 'ERROR: ' + time + ' ---\n-', error );
  358. else console.log( '- ' + error.name + ': ' + error.message );
  359. }
  360. }
  361. global.log_warn = function(warning, api = true) {
  362. if ( isDebug ) {
  363. console.warn( '--- Warning start ---\n' + util.inspect( warning ) + '\n--- Warning end ---' );
  364. } else {
  365. if ( api ) console.warn( '- Warning: ' + Object.keys(warning).join(', ') );
  366. else console.warn( '--- Warning ---\n' + util.inspect( warning ) );
  367. }
  368. }
  369. /**
  370. * End the process gracefully.
  371. * @param {String} signal - The signal received.
  372. */
  373. async function graceful(signal) {
  374. isStop = true;
  375. console.log( '- ' + shardId + ': ' + signal + ': Preparing to close...' );
  376. setTimeout( async () => {
  377. console.log( '- ' + shardId + ': ' + signal + ': Destroying client...' );
  378. await client.destroy();
  379. await db.close( dberror => {
  380. if ( dberror ) {
  381. console.log( '- ' + shardId + ': ' + signal + ': Error while closing the database connection: ' + dberror );
  382. return dberror;
  383. }
  384. console.log( '- ' + shardId + ': ' + signal + ': Closed the database connection.' );
  385. process.exit(0);
  386. } );
  387. }, 1000 ).unref();
  388. }
  389. process.once( 'SIGINT', graceful );
  390. process.once( 'SIGTERM', graceful );