url-shortener/short.js

101 lines
4.1 KiB
JavaScript
Raw Normal View History

2024-10-03 12:22:56 -04:00
const { Client, GatewayIntentBits, REST, Routes, SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const unirest = require('unirest');
require('dotenv').config();
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const rest = new REST({ version: '10' }).setToken(process.env.BOT_TOKEN);
const DiscordClientId = process.env.DISCORD_CLIENT_ID; // Your Discord Client ID
// URL validation function
function isValidURL(url) {
const regex = /^(https?:\/\/)?([a-zA-Z0-9\-\.]+)\.([a-z]{2,})(\/\S*)?$/;
return regex.test(url);
}
client.once('ready', async () => {
console.log(`Logged in as ${client.user.tag}`);
// Define your slash commands using SlashCommandBuilder
const command = new SlashCommandBuilder()
.setName('shortenurl')
.setDescription('Shorten a URL')
.addStringOption(option =>
option.setName('url')
.setDescription('Enter the URL to shorten')
.setRequired(true))
.addStringOption(option =>
option.setName('domain')
.setDescription('Choose the domain for the short URL')
.setRequired(false)
.addChoices(
{ name: 's.shells.lol', value: 's.shells.lol' },
{ name: 's.hehe.rest', value: 's.hehe.rest' },
{ name: 's.dcord.rest', value: 's.dcord.rest' }, // default domain
{ name: 's.nodejs.lol', value: 's.nodejs.lol' },
{ name: 's.dht.rest', value: 's.dht.rest' },
{ name: 's.tcp.quest', value: 's.tcp.quest' }
)
)
.toJSON(); // Convert to JSON
// Add extras to the command for integration
const extras = {
"integration_types": [0, 1], // 0 for guild, 1 for user
"contexts": [0, 1, 2], // 0 for guild, 1 for app DMs, 2 for GDMs and other DMs
};
Object.keys(extras).forEach(key => command[key] = extras[key]);
try {
// Register the command with Discord
await rest.put(Routes.applicationCommands(DiscordClientId), { body: [command] });
console.log('Commands registered successfully.');
} catch (error) {
console.error('Error registering commands:', error);
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand() || interaction.commandName !== 'shortenurl') return;
const domain = interaction.options.getString('domain') || 's.dcord.rest';
const url = interaction.options.getString('url');
// Validate the URL format before proceeding
if (!isValidURL(url)) {
return interaction.reply({ content: 'Please provide a valid URL.', ephemeral: true });
}
try {
// Make API call to the selected domain to create a short URL
unirest.post(`https://${domain}/api/shorturl`)
.headers({
'Content-Type': 'application/json',
'x-api-key': process.env.API_KEY // Use the API key from environment variables
})
.send({ longUrl: url, domain })
.end((response) => {
const data = response.body;
if (data.shortUrl) {
// Render the short URL directly without Markdown brackets for proper embedding
const embed = new EmbedBuilder()
.setColor("#FF0000")
.setTitle("🔗 URL Shortened!")
.setDescription(`${data.shortUrl}`)
.setTimestamp()
.setFooter({ text: `Requested by ${interaction.user.tag}`, iconURL: `${interaction.user.displayAvatarURL()}` });
interaction.reply({ embeds: [embed] });
} else {
interaction.reply({ content: `Failed to shorten URL: ${data.error || 'Unknown error'}`, ephemeral: true });
}
});
} catch (error) {
console.error('Error creating shortened URL:', error);
interaction.reply({ content: 'There was an error trying to shorten the URL. Please try again later.', ephemeral: true });
}
});
client.login(process.env.BOT_TOKEN);