bot.js 17 KB

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