Преглед на файлове

add wastebasket to /inline

Markus-Rost преди 4 години
родител
ревизия
7af6701144
променени са 3 файла, в които са добавени 89 реда и са изтрити 35 реда
  1. 9 18
      bot.js
  2. 65 16
      interactions/inline.js
  3. 15 1
      util/functions.js

+ 9 - 18
bot.js

@@ -21,12 +21,14 @@ const {defaultSettings} = require('./util/default.json');
 const Lang = require('./util/i18n.js');
 const Wiki = require('./util/wiki.js');
 const newMessage = require('./util/newMessage.js');
+const {allowDelete} = require('./util/functions.js');
 global.patreons = {};
 global.voice = {};
 const db = require('./util/database.js');
 
 const Discord = require('discord.js');
 const client = new Discord.Client( {
+	messageEditHistoryMaxSize: 1,
 	messageCacheLifetime: 300,
 	messageSweepInterval: 300,
 	allowedMentions: {
@@ -183,19 +185,6 @@ Discord.Message.prototype.replyMsg = function(content, options = {}, ignorePause
 	}
 };
 
-/**
- * All users to delete their command responses.
- * @param {Discord.Message} msg - The response.
- * @param {String} author - The user.
- */
-function allowDelete(msg, author) {
-	msg.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:120000} ).then( reaction => {
-		if ( reaction.size ) {
-			msg.delete().catch(log_error);
-		}
-	} );
-};
-
 String.prototype.hasPrefix = function(prefix, flags = '') {
 	var suffix = '';
 	if ( prefix.endsWith( ' ' ) ) {
@@ -246,9 +235,11 @@ client.on( 'raw', rawEvent => {
 			}
 		}, log_error );
 	}
-	if ( !interaction.guild_id ) return slash[interaction.data.name](interaction, new Lang(), new Wiki());
-	var guild = client.guilds.cache.get(interaction.guild_id);
-	db.get( 'SELECT wiki, lang, role FROM discord WHERE guild = ? AND (channel = ? OR channel = ? OR channel IS NULL) ORDER BY channel DESC', [interaction.guild_id, interaction.channel_id, '#' + guild?.channels.cache.get(interaction.channel_id)?.parentID], (dberror, row) => {
+	var channel = client.channels.cache.get(interaction.channel_id);
+	if ( !interaction.guild_id ) {
+		return slash[interaction.data.name](interaction, new Lang(), new Wiki(), channel);
+	}
+	db.get( 'SELECT wiki, lang, role FROM discord WHERE guild = ? AND (channel = ? OR channel = ? OR channel IS NULL) ORDER BY channel DESC', [interaction.guild_id, interaction.channel_id, '#' + channel?.parentID], (dberror, row) => {
 		if ( dberror ) {
 			console.log( '- Error while getting the wiki: ' + dberror );
 			return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
@@ -270,7 +261,7 @@ client.on( 'raw', rawEvent => {
 			}, log_error );
 		}
 		var lang = new Lang(row.lang || defaultSettings.lang);
-		if ( row.role && !interaction.member.roles.includes( row.role ) && guild?.roles.cache.has(row.role) && ( !interaction.member.roles.length || !interaction.member.roles.some( role => guild.roles.cache.get(role)?.comparePositionTo(row.role) >= 0 ) ) ) {
+		if ( row.role && !interaction.member.roles.includes( row.role ) && channel?.guild?.roles.cache.has(row.role) && ( !interaction.member.roles.length || !interaction.member.roles.some( role => channel.guild.roles.cache.get(role)?.comparePositionTo(row.role) >= 0 ) ) ) {
 			return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
 				json: {
 					//type: 4,
@@ -290,7 +281,7 @@ client.on( 'raw', rawEvent => {
 			}, log_error );
 		}
 		var wiki = new Wiki(row.wiki || defaultSettings.wiki);
-		return slash[interaction.data.name](interaction, lang, wiki, guild);
+		return slash[interaction.data.name](interaction, lang, wiki, channel);
 	} );
 } );
 

+ 65 - 16
interactions/inline.js

@@ -1,15 +1,15 @@
 const logging = require('../util/logging.js');
 const Wiki = require('../util/wiki.js');
-const {limitLength, partialURIdecode} = require('../util/functions.js');
+const {limitLength, partialURIdecode, allowDelete} = require('../util/functions.js');
 
 /**
  * Post a message with inline wiki links.
  * @param {Object} interaction - The interaction.
  * @param {import('../util/i18n.js')} lang - The user language.
  * @param {import('../util/wiki.js')} wiki - The wiki for the interaction.
- * @param {import('discord.js').Guild} [guild] - The guild for the interaction.
+ * @param {import('discord.js').TextChannel} [channel] - The guild for the interaction.
  */
-function slash_inline(interaction, lang, wiki, guild) {
+function slash_inline(interaction, lang, wiki, channel) {
 	var text = ( interaction.data.options?.[0]?.value || '' ).replace( /\]\(/g, ']\\(' ).trim();
 	if ( !text ) {
 		return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
@@ -38,8 +38,8 @@ function slash_inline(interaction, lang, wiki, guild) {
 		|| ( (interaction.member.permissions & 1 << 17) === 1 << 17 ) ) { // MENTION_EVERYONE
 			allowed_mentions.parse = ['users', 'roles', 'everyone'];
 		}
-		else if ( guild ) {
-			allowed_mentions.roles = guild.roles.cache.filter( role => role.mentionable ).map( role => role.id );
+		else if ( channel?.guild ) {
+			allowed_mentions.roles = channel.guild.roles.cache.filter( role => role.mentionable ).map( role => role.id );
 			if ( allowed_mentions.roles.length > 100 ) {
 				allowed_mentions.roles = allowed_mentions.roles.slice(0, 100);
 			}
@@ -55,12 +55,22 @@ function slash_inline(interaction, lang, wiki, guild) {
 				flags: 0
 			}
 		}
-	} ).then( response => {
-		if ( response.statusCode !== 204 ) {
-			console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
+	} ).then( aresponse => {
+		if ( aresponse.statusCode !== 204 ) {
+			console.log( '- Slash: ' + aresponse.statusCode + ': Error while sending the response: ' + aresponse.body?.message );
 			return;
 		}
-		if ( !text.includes( '{{' ) && !( text.includes( '[[' ) && text.includes( ']]' ) ) ) return;
+		if ( !text.includes( '{{' ) && !( text.includes( '[[' ) && text.includes( ']]' ) ) ) {
+			return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
+				json: {}
+			} ).then( presponse => {
+				if ( presponse.statusCode === 200 && presponse.body?.id ) {
+					channel?.messages.fetch(presponse.body.id).then( msg => {
+						allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
+					}, () => {} );
+				}
+			}, () => {} );
+		}
 		var textReplacement = [];
 		var replacedText = text.replace( /\u200b/g, '' ).replace( /(?<!\\)(?:<a?(:\w+:)\d+>|```.+?```|`.+?`)/gs, (replacement, arg) => {
 			textReplacement.push(replacement);
@@ -85,7 +95,7 @@ function slash_inline(interaction, lang, wiki, guild) {
 				else templates.push({raw: title, title, template: 'Template:' + title});
 			}
 			inlineLink = null;
-			regex = /(?<!\\)\[\[([^<>\[\]\|\{\}\x01-\x1F\x7F]+)(?:\|(?:(?!\[\[).)*?)?(?<!\\)\]\]/g;
+			regex = /(?<!\\)\[\[([^<>\[\]\|\{\}\x01-\x1F\x7F]+)(?:\|(?:(?!\[\[|\]\\\]).)*?)?(?<!\\)\]\]/g;
 			while ( ( inlineLink = regex.exec(line) ) !== null ) {
 				inlineLink[1] = inlineLink[1].trim();
 				let title = inlineLink[1].split('#')[0].trim();
@@ -94,7 +104,17 @@ function slash_inline(interaction, lang, wiki, guild) {
 				links.push({raw: title, title, section});
 			}
 		} );
-		if ( !templates.length && !links.length ) return;
+		if ( !templates.length && !links.length ) {
+			return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
+				json: {}
+			} ).then( presponse => {
+				if ( presponse.statusCode === 200 && presponse.body?.id ) {
+					channel?.messages.fetch(presponse.body.id).then( msg => {
+						allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
+					}, () => {} );
+				}
+			}, () => {} );
+		}
 		return got.get( wiki + 'api.php?action=query&meta=siteinfo&siprop=general&iwurl=true&titles=' + encodeURIComponent( [
 			...templates.map( link => link.title + '|' + link.template ),
 			...links.map( link => link.title )
@@ -107,7 +127,15 @@ function slash_inline(interaction, lang, wiki, guild) {
 				else {
 					console.log( '- ' + response.statusCode + ': Error while following the links: ' + body?.error?.info );
 				}
-				return;
+				return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
+					json: {}
+				} ).then( presponse => {
+					if ( presponse.statusCode === 200 && presponse.body?.id ) {
+						channel?.messages.fetch(presponse.body.id).then( msg => {
+							allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
+						}, () => {} );
+					}
+				}, () => {} );
 			}
 			logging(wiki, interaction.guild_id, 'slash', 'inline');
 			wiki.updateWiki(body.query.general);
@@ -188,7 +216,7 @@ function slash_inline(interaction, lang, wiki, guild) {
 						}
 						return linkprefix + '[' + title + '](<' + ( link.url || wiki.toLink(link.title || link.template, '', '', true) ) + '>)' + linktrail;
 					} );
-					regex = new RegExp( '([' + body.query.general.linkprefixcharset.replace( /\\x([a-fA-f0-9]{4,6}|\{[a-fA-f0-9]{4,6}\})/g, '\\u$1' ) + ']+)?' + '(?<!\\\\)\\[\\[' + '((?:[^' + "<>\\[\\]\\|\{\}\\x01-\\x1F\\x7F" + ']|' + '\\u200b<replacement\\u200b\\d+\\u200b.+?>\\u200b' + ')+)' + '(?:\\|((?:(?!\\[\\[|\\]\\().)*?))?' + '(?<!\\\\)\\]\\]' + body.query.general.linktrail.replace( /\\x([a-fA-f0-9]{4,6}|\{[a-fA-f0-9]{4,6}\})/g, '\\u$1' ).replace( /^\/\^(\(\[.+?\]\+\))\(\.\*\)\$\/sDu?$/, '$1?' ), 'gu' );
+					regex = new RegExp( '([' + body.query.general.linkprefixcharset.replace( /\\x([a-fA-f0-9]{4,6}|\{[a-fA-f0-9]{4,6}\})/g, '\\u$1' ) + ']+)?' + '(?<!\\\\)\\[\\[' + '((?:[^' + "<>\\[\\]\\|\{\}\\x01-\\x1F\\x7F" + ']|' + '\\u200b<replacement\\u200b\\d+\\u200b.+?>\\u200b' + ')+)' + '(?:\\|((?:(?!\\[\\[|\\]\\(|\\]\\\\\\]).)*?))?' + '(?<!\\\\)\\]\\]' + body.query.general.linktrail.replace( /\\x([a-fA-f0-9]{4,6}|\{[a-fA-f0-9]{4,6}\})/g, '\\u$1' ).replace( /^\/\^(\(\[.+?\]\+\))\(\.\*\)\$\/sDu?$/, '$1?' ), 'gu' );
 					line = line.replace( regex, (fullLink, linkprefix = '', title, display, linktrail = '') => {
 						title = title.replace( /(?:%[\dA-F]{2})+/g, partialURIdecode );
 						let rawTitle = title.replace( /\u200b<replacement\u200b\d+\u200b(.+?)>\u200b/g, '$1' ).split('#')[0].trim();
@@ -224,12 +252,24 @@ function slash_inline(interaction, lang, wiki, guild) {
 						content: text,
 						allowed_mentions
 					}
-				} ).then( response => {
-					if ( response.statusCode !== 200 ) {
-						console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
+				} ).then( presponse => {
+					if ( presponse.statusCode !== 200 ) {
+						console.log( '- Slash: ' + presponse.statusCode + ': Error while sending the response: ' + presponse.body?.message );
 					}
+					channel?.messages.fetch(presponse.body.id).then( msg => {
+						allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
+					}, () => {} );
 				}, log_error );
 			}
+			else return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
+				json: {}
+			} ).then( presponse => {
+				if ( presponse.statusCode === 200 && presponse.body?.id ) {
+					channel?.messages.fetch(presponse.body.id).then( msg => {
+						allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
+					}, () => {} );
+				}
+			}, () => {} );
 		}, error => {
 			if ( wiki.noWiki(error.message) ) {
 				console.log( '- This wiki doesn\'t exist!' );
@@ -237,6 +277,15 @@ function slash_inline(interaction, lang, wiki, guild) {
 			else {
 				console.log( '- Error while following the links: ' + error );
 			}
+			return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
+				json: {}
+			} ).then( presponse => {
+				if ( presponse.statusCode === 200 && presponse.body?.id ) {
+					channel?.messages.fetch(presponse.body.id).then( msg => {
+						allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
+					}, () => {} );
+				}
+			}, () => {} );
 		} );
 	}, log_error );
 }

+ 15 - 1
util/functions.js

@@ -400,6 +400,19 @@ function partialURIdecode(m) {
 	return text;
 };
 
+/**
+ * Allow users to delete their command responses.
+ * @param {import('discord.js').Message} msg - The response.
+ * @param {String} author - The user id.
+ */
+function allowDelete(msg, author) {
+	msg.awaitReactions( (reaction, user) => reaction.emoji.name === '🗑️' && user.id === author, {max:1,time:300000} ).then( reaction => {
+		if ( reaction.size ) {
+			msg.delete().catch(log_error);
+		}
+	} );
+};
+
 module.exports = {
 	got,
 	parse_infobox,
@@ -410,5 +423,6 @@ module.exports = {
 	htmlToDiscord,
 	escapeFormatting,
 	limitLength,
-	partialURIdecode
+	partialURIdecode,
+	allowDelete
 };