Markus-Rost пре 4 година
родитељ
комит
9161f30c25
5 измењених фајлова са 52 додато и 89 уклоњено
  1. 17 32
      bot.js
  2. 4 4
      dashboard/index.js
  3. 3 0
      dashboard/oauth.js
  4. 1 3
      database.js
  5. 27 50
      interactions/inline.js

+ 17 - 32
bot.js

@@ -204,35 +204,28 @@ fs.readdir( './interactions', (error, files) => {
 	} );
 	} );
 } );
 } );
 /*
 /*
-!test eval got.post(`https://discord.com/api/v8/applications/${msg.client.user.id}/commands`, {
-	headers:{Authorization: `Bot ${process.env.token}`},
-	json: require('../interactions/commands.json')[0]
-}).then(response=>console.log(response.statusCode,response.body))
+!test eval client.api.applications(client.user.id).commands.post( {
+	data: require('../interactions/commands.json')[0]
+} )
 */
 */
-client.on( 'raw', rawEvent => {
-	if ( rawEvent.t !== 'INTERACTION_CREATE' ) return;
-	var interaction = rawEvent.d;
+client.ws.on( 'INTERACTION_CREATE', interaction => {
 	if ( interaction.version !== 1 || interaction.type !== 2 ) return;
 	if ( interaction.version !== 1 || interaction.type !== 2 ) return;
-	interaction.application_id = client.user.id;
 	if ( !slash.hasOwnProperty(interaction.data.name) ) {
 	if ( !slash.hasOwnProperty(interaction.data.name) ) {
-		consol.log( '- Slash: Unknown command: ' + interaction.data.name );
-		return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
-			json: {
+		console.log( '- Slash: Unknown command: ' + interaction.data.name );
+		return client.api.interactions(interaction.id, interaction.token).callback.post( {
+			data: {
 				type: 4,
 				type: 4,
 				data: {
 				data: {
-					content: '[<:error:440871715938238494> Unknown Command! <:error:440871715938238494>](<' + process.env.invite + '>)',
+					content: '<:error:440871715938238494> [Unknown Command!](<' + process.env.invite + '>) <:error:440871715938238494>',
 					allowed_mentions: {
 					allowed_mentions: {
 						parse: []
 						parse: []
 					},
 					},
 					flags: 64
 					flags: 64
 				}
 				}
 			}
 			}
-		} ).then( response => {
-			if ( response.statusCode !== 204 ) {
-				console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
-			}
-		}, log_error );
+		} ).catch(log_error);
 	}
 	}
+	interaction.client = client;
 	var channel = client.channels.cache.get(interaction.channel_id);
 	var channel = client.channels.cache.get(interaction.channel_id);
 	if ( !interaction.guild_id ) {
 	if ( !interaction.guild_id ) {
 		return slash[interaction.data.name](interaction, new Lang(), new Wiki(), channel);
 		return slash[interaction.data.name](interaction, new Lang(), new Wiki(), channel);
@@ -240,8 +233,8 @@ client.on( 'raw', rawEvent => {
 	db.query( 'SELECT wiki, lang, role FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', [interaction.guild_id, interaction.channel_id, '#' + channel?.parentID] ).then( ({rows:[row]}) => {
 	db.query( 'SELECT wiki, lang, role FROM discord WHERE guild = $1 AND (channel = $2 OR channel = $3 OR channel IS NULL) ORDER BY channel DESC NULLS LAST LIMIT 1', [interaction.guild_id, interaction.channel_id, '#' + channel?.parentID] ).then( ({rows:[row]}) => {
 		var lang = new Lang(( row?.lang || channel?.guild?.preferredLocale ));
 		var lang = new Lang(( row?.lang || channel?.guild?.preferredLocale ));
 		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 ) ) ) {
 		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: {
+			return client.api.interactions(interaction.id, interaction.token).callback.post( {
+				data: {
 					type: 4,
 					type: 4,
 					data: {
 					data: {
 						content: lang.get('interaction.missingrole', '<@&' + row.role + '>'),
 						content: lang.get('interaction.missingrole', '<@&' + row.role + '>'),
@@ -251,32 +244,24 @@ client.on( 'raw', rawEvent => {
 						flags: 64
 						flags: 64
 					}
 					}
 				}
 				}
-			} ).then( response => {
-				if ( response.statusCode !== 204 ) {
-					console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
-				}
-			}, log_error );
+			} ).catch(log_error);
 		}
 		}
 		var wiki = new Wiki(row?.wiki);
 		var wiki = new Wiki(row?.wiki);
 		return slash[interaction.data.name](interaction, lang, wiki, channel);
 		return slash[interaction.data.name](interaction, lang, wiki, channel);
 	}, dberror => {
 	}, dberror => {
 		console.log( '- Slash: Error while getting the wiki: ' + dberror );
 		console.log( '- Slash: Error while getting the wiki: ' + dberror );
-		return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
-			json: {
+		return client.api.interactions(interaction.id, interaction.token).callback.post( {
+			data: {
 				type: 4,
 				type: 4,
 				data: {
 				data: {
-					content: '[<:error:440871715938238494> Error! <:error:440871715938238494>](<' + process.env.invite + '>)',
+					content: '<:error:440871715938238494> [Error!](<' + process.env.invite + '>) <:error:440871715938238494>',
 					allowed_mentions: {
 					allowed_mentions: {
 						parse: []
 						parse: []
 					},
 					},
 					flags: 64
 					flags: 64
 				}
 				}
 			}
 			}
-		} ).then( response => {
-			if ( response.statusCode !== 204 ) {
-				console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
-			}
-		}, log_error );
+		} ).catch(log_error);
 	} );
 	} );
 } );
 } );
 
 

+ 4 - 4
dashboard/index.js

@@ -54,8 +54,8 @@ const server = http.createServer((req, res) => {
 	if ( req.method === 'POST' && req.url.startsWith( '/guild/' ) ) {
 	if ( req.method === 'POST' && req.url.startsWith( '/guild/' ) ) {
 		let args = req.url.split('/');
 		let args = req.url.split('/');
 		let state = req.headers.cookie?.split('; ')?.filter( cookie => {
 		let state = req.headers.cookie?.split('; ')?.filter( cookie => {
-			return cookie.split('=')[0] === 'wikibot';
-		} )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)?)"$/, '$1' ) )?.join();
+			return cookie.split('=')[0] === 'wikibot' && /^"(\w*(?:-\d+)*)"$/.test(( cookie.split('=')[1] || '' ));
+		} )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)*)"$/, '$1' ) )?.join();
 
 
 		if ( args.length === 5 && ['settings', 'verification', 'rcscript'].includes( args[3] )
 		if ( args.length === 5 && ['settings', 'verification', 'rcscript'].includes( args[3] )
 		&& /^(?:default|new|\d+)$/.test(args[4]) && settingsData.has(state)
 		&& /^(?:default|new|\d+)$/.test(args[4]) && settingsData.has(state)
@@ -152,8 +152,8 @@ const server = http.createServer((req, res) => {
 	if ( lastGuild ) res.setHeader('Set-Cookie', ['guild=""; HttpOnly; Path=/; Max-Age=0']);
 	if ( lastGuild ) res.setHeader('Set-Cookie', ['guild=""; HttpOnly; Path=/; Max-Age=0']);
 
 
 	var state = req.headers.cookie?.split('; ')?.filter( cookie => {
 	var state = req.headers.cookie?.split('; ')?.filter( cookie => {
-		return cookie.split('=')[0] === 'wikibot' && /^"(\w*(?:-\d+)?)"$/.test(( cookie.split('=')[1] || '' ));
-	} )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)?)"$/, '$1' ) )?.join();
+		return cookie.split('=')[0] === 'wikibot' && /^"(\w*(?:-\d+)*)"$/.test(( cookie.split('=')[1] || '' ));
+	} )?.map( cookie => cookie.replace( /^wikibot="(\w*(?:-\d+)*)"$/, '$1' ) )?.join();
 
 
 	if ( reqURL.pathname === '/login' ) {
 	if ( reqURL.pathname === '/login' ) {
 		let action = '';
 		let action = '';

+ 3 - 0
dashboard/oauth.js

@@ -146,6 +146,9 @@ function dashboard_oauth(res, state, searchParams, lastGuild) {
 					else settings.guilds.notMember.set(guilds[i].id, guilds[i]);
 					else settings.guilds.notMember.set(guilds[i].id, guilds[i]);
 				} );
 				} );
 				settingsData.set(settings.state, settings);
 				settingsData.set(settings.state, settings);
+				if ( searchParams.has('guild_id') ) {
+					lastGuild = searchParams.get('guild_id') + '/settings';
+				}
 				res.writeHead(302, {
 				res.writeHead(302, {
 					Location: ( lastGuild && /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(lastGuild) ? `/guild/${lastGuild}` : '/' ),
 					Location: ( lastGuild && /^\d+\/(?:settings|verification|rcscript)(?:\/(?:\d+|new))?$/.test(lastGuild) ? `/guild/${lastGuild}` : '/' ),
 					'Set-Cookie': [`wikibot="${settings.state}"; HttpOnly; Path=/`]
 					'Set-Cookie': [`wikibot="${settings.state}"; HttpOnly; Path=/`]

+ 1 - 3
database.js

@@ -168,9 +168,7 @@ module.exports = db.connect().then( () => {
 	console.log( '- Error while connecting to the database: ' + dberror );
 	console.log( '- Error while connecting to the database: ' + dberror );
 	return Promise.reject();
 	return Promise.reject();
 } ).then( () => {
 } ).then( () => {
-	db.end().then( () => {
-		console.log( '- Closed the database connection.' );
-	}, dberror => {
+	db.end().catch( dberror => {
 		console.log( '- Error while closing the database connection: ' + dberror );
 		console.log( '- Error while closing the database connection: ' + dberror );
 	} );
 	} );
 }, () => {
 }, () => {

+ 27 - 50
interactions/inline.js

@@ -5,6 +5,7 @@ const {limitLength, partialURIdecode, allowDelete} = require('../util/functions.
 /**
 /**
  * Post a message with inline wiki links.
  * Post a message with inline wiki links.
  * @param {Object} interaction - The interaction.
  * @param {Object} interaction - The interaction.
+ * @param {import('discord.js').Client} interaction.client - The client of the interaction.
  * @param {import('../util/i18n.js')} lang - The user language.
  * @param {import('../util/i18n.js')} lang - The user language.
  * @param {import('../util/wiki.js')} wiki - The wiki for the interaction.
  * @param {import('../util/wiki.js')} wiki - The wiki for the interaction.
  * @param {import('discord.js').TextChannel} [channel] - The channel for the interaction.
  * @param {import('discord.js').TextChannel} [channel] - The channel for the interaction.
@@ -13,8 +14,8 @@ function slash_inline(interaction, lang, wiki, channel) {
 	var text = ( interaction.data.options?.[0]?.value || '' ).replace( /\]\(/g, ']\\(' );
 	var text = ( interaction.data.options?.[0]?.value || '' ).replace( /\]\(/g, ']\\(' );
 	text = text.replace( /\x1F/g, '' ).replace( /(?<!@)\u200b/g, '' ).trim();
 	text = text.replace( /\x1F/g, '' ).replace( /(?<!@)\u200b/g, '' ).trim();
 	if ( !text.includes( '{{' ) && !( text.includes( '[[' ) && text.includes( ']]' ) ) && !text.includes( 'PMID' ) && !text.includes( 'RFC' ) && !text.includes( 'ISBN' ) ) {
 	if ( !text.includes( '{{' ) && !( text.includes( '[[' ) && text.includes( ']]' ) ) && !text.includes( 'PMID' ) && !text.includes( 'RFC' ) && !text.includes( 'ISBN' ) ) {
-		return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
-			json: {
+		return interaction.client.api.interactions(interaction.id, interaction.token).callback.post( {
+			data: {
 				type: 4,
 				type: 4,
 				data: {
 				data: {
 					content: lang.get('interaction.inline'),
 					content: lang.get('interaction.inline'),
@@ -24,13 +25,7 @@ function slash_inline(interaction, lang, wiki, channel) {
 					flags: 64
 					flags: 64
 				}
 				}
 			}
 			}
-		} ).then( response => {
-			if ( response.statusCode !== 204 ) {
-				console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
-			}
-		}, error => {
-			console.log( '- Slash: Error while sending the response: ' + error );
-		} );
+		} ).catch(log_error);
 	}
 	}
 	var allowed_mentions = {
 	var allowed_mentions = {
 		parse: ['users']
 		parse: ['users']
@@ -63,42 +58,36 @@ function slash_inline(interaction, lang, wiki, channel) {
 		} ),
 		} ),
 		allowed_mentions
 		allowed_mentions
 	};
 	};
-	return got.post( `https://discord.com/api/v8/interactions/${interaction.id}/${interaction.token}/callback`, {
-		json: {
+	return interaction.client.api.interactions(interaction.id, interaction.token).callback.post( {
+		data: {
 			type: 5,
 			type: 5,
 			data: {
 			data: {
 				flags: 0
 				flags: 0
 			}
 			}
 		}
 		}
-	} ).then( aresponse => {
-		if ( aresponse.statusCode !== 204 ) {
-			console.log( '- Slash: ' + aresponse.statusCode + ': Error while sending the response: ' + aresponse.body?.message );
-			return;
-		}
+	} ).then( () => {
 		var textReplacement = [];
 		var textReplacement = [];
 		var magiclinks = [];
 		var magiclinks = [];
 		var replacedText = text.replace( /(?<!\\)(?:<a?(:\w+:)\d+>|<#(\d+)>|<@!?(\d+)>|<@&(\d+)>|```.+?```|``.+?``|`.+?`)/gs, (replacement, emoji, textchannel, user, role) => {
 		var replacedText = text.replace( /(?<!\\)(?:<a?(:\w+:)\d+>|<#(\d+)>|<@!?(\d+)>|<@&(\d+)>|```.+?```|``.+?``|`.+?`)/gs, (replacement, emoji, textchannel, user, role) => {
 			textReplacement.push(replacement);
 			textReplacement.push(replacement);
 			var arg = '';
 			var arg = '';
 			if ( emoji ) arg = emoji;
 			if ( emoji ) arg = emoji;
-			if ( channel ) {
-				if ( textchannel ) {
-					let tempchannel = channel.client.channels.cache.get(textchannel);
-					if ( tempchannel ) arg = '#' + tempchannel.name;
-				}
-				if ( user ) {
-					let tempuser = channel.guild?.members.cache.get(user);
-					if ( tempuser ) arg = '@' + tempuser.displayName;
-					else {
-						tempuser = channel.client.users.cache.get(user);
-						if ( tempuser ) arg = '@' + tempuser.username;
-					}
-				}
-				if ( role ) {
-					let temprole = channel.guild?.roles.cache.get(role);
-					if ( temprole ) arg = '@' + temprole.name;
+			if ( textchannel ) {
+				let tempchannel = interaction.client.channels.cache.get(textchannel);
+				if ( tempchannel ) arg = '#' + tempchannel.name;
+			}
+			if ( user ) {
+				let tempuser = channel?.guild?.members.cache.get(user);
+				if ( tempuser ) arg = '@' + tempuser.displayName;
+				else {
+					tempuser = interaction.client.users.cache.get(user);
+					if ( tempuser ) arg = '@' + tempuser.username;
 				}
 				}
 			}
 			}
+			if ( role ) {
+				let temprole = channel?.guild?.roles.cache.get(role);
+				if ( temprole ) arg = '@' + temprole.name;
+			}
 			return '\x1F<replacement\x1F' + textReplacement.length + ( arg ? '\x1F' + arg : '' ) + '>\x1F';
 			return '\x1F<replacement\x1F' + textReplacement.length + ( arg ? '\x1F' + arg : '' ) + '>\x1F';
 		} ).replace( /\b(PMID|RFC) +([0-9]+)\b/g, (replacement, type, id) => {
 		} ).replace( /\b(PMID|RFC) +([0-9]+)\b/g, (replacement, type, id) => {
 			magiclinks.push({type, id, replacementId: textReplacement.length});
 			magiclinks.push({type, id, replacementId: textReplacement.length});
@@ -291,9 +280,7 @@ function slash_inline(interaction, lang, wiki, channel) {
 			}
 			}
 			return sendMessage(interaction, message, channel);
 			return sendMessage(interaction, message, channel);
 		} );
 		} );
-	}, error => {
-		console.log( '- Slash: Error while sending the response: ' + error );
-	} );
+	}, log_error );
 }
 }
 
 
 /**
 /**
@@ -303,23 +290,13 @@ function slash_inline(interaction, lang, wiki, channel) {
  * @param {String} message.content - The message content.
  * @param {String} message.content - The message content.
  * @param {{parse: String[], roles?: String[]}} message.allowed_mentions - The allowed mentions.
  * @param {{parse: String[], roles?: String[]}} message.allowed_mentions - The allowed mentions.
  * @param {import('discord.js').TextChannel} [channel] - The channel for the interaction.
  * @param {import('discord.js').TextChannel} [channel] - The channel for the interaction.
- * @returns {Promise<import('discord.js').Message?>}
  */
  */
 function sendMessage(interaction, message, channel) {
 function sendMessage(interaction, message, channel) {
-	return got.patch( `https://discord.com/api/v8/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`, {
-		json: message
-	} ).then( response => {
-		if ( response.statusCode !== 200 ) {
-			console.log( '- Slash: ' + response.statusCode + ': Error while sending the response: ' + response.body?.message );
-			return;
-		}
-		return channel?.messages.fetch(response.body.id).then( msg => {
-			if ( msg ) allowDelete(msg, ( interaction.member?.user.id || interaction.user.id ));
-			return msg;
-		}, () => {} );
-	}, error => {
-		console.log( '- Slash: Error while sending the response: ' + error );
-	} );
+	return interaction.client.api.webhooks(interaction.application_id, interaction.token).messages('@original').patch( {
+		data: message
+	} ).then( msg => {
+		if ( channel ) allowDelete(channel.messages.add(msg), ( interaction.member?.user.id || interaction.user.id ));
+	}, log_error );
 }
 }
 
 
 module.exports = {
 module.exports = {