bot.js 17 KB

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