bot.js 16 KB

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