bot.js 16 KB

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