Convert to Typescript
This commit is contained in:
62
src/commands/eyecandy.ts
Normal file
62
src/commands/eyecandy.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { SlashCommandBuilder, ChatInputCommandInteraction } from 'discord.js';
|
||||
import axios from 'axios';
|
||||
|
||||
const GIPHY_API_URL = 'http://api.giphy.com/v1/gifs/search';
|
||||
|
||||
// Initialise the command data.
|
||||
export const data = new SlashCommandBuilder()
|
||||
.setName('eyecandy')
|
||||
.setDescription('Returns a random gif of Gerard Butler.');
|
||||
|
||||
console.log(`Loaded ${data.name} command.`);
|
||||
|
||||
/**
|
||||
* Execute the command, fetch a random Gerard Butler gif, and send it to the user.
|
||||
* @param interaction The interaction that triggered the command.
|
||||
* @returns A promise that resolves when the command is finished executing.
|
||||
*/
|
||||
export async function execute(
|
||||
interaction: ChatInputCommandInteraction
|
||||
): Promise<void> {
|
||||
await interaction.deferReply();
|
||||
|
||||
if (!process.env.GIPHY_API_KEY) {
|
||||
await interaction.reply('The bot is missing the GIPHY API key.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Fetch a random gif of Gerard Butler.
|
||||
const gifUrl = await fetchGif();
|
||||
|
||||
// Reply with the gif.
|
||||
await interaction.editReply(gifUrl);
|
||||
} catch (error: any) {
|
||||
console.error('Error executing the command:', error.message);
|
||||
await interaction.editReply(`An error occurred: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a random gif of Gerard Butler from Giphy.
|
||||
* @returns A promise that resolves to the URL of the gif.
|
||||
* @throws An error if no gif is found or if the request fails.
|
||||
*/
|
||||
async function fetchGif(): Promise<string> {
|
||||
const randomOffset = Math.floor(Math.random() * 100);
|
||||
const giphyQueryUrl = `${GIPHY_API_URL}?api_key=${process.env.GIPHY_API_KEY}&q=gerard+butler&limit=1&offset=${randomOffset}`;
|
||||
|
||||
try {
|
||||
const response = await axios.get(giphyQueryUrl, { timeout: 5000 });
|
||||
const result = response.data;
|
||||
|
||||
if (result.data.length === 0) {
|
||||
throw new Error('No gifs found for the given query.');
|
||||
}
|
||||
|
||||
return result.data[0].images.original.url;
|
||||
} catch (error: any) {
|
||||
console.error('Error fetching GIF:', error.message);
|
||||
throw new Error('Failed to retrieve a GIF from Giphy.');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user