Hey everyone! I’m new to JavaScript and I’m working on a Discord bot. I need help with a command that generates a link based on user input. The tricky part is checking if the URL actually exists before sending it in chat.
If the URL doesn’t work, I want to send a wiki page instead. I’m using discord.js, but I’m not sure if I need to install anything else. Here’s what I’ve tried so far:
if (message.content.startsWith('!showme')) {
const input = message.content.slice(7).toLowerCase();
const url = `https://example.com/characters/${input}.html`;
// How do I check if this URL exists?
// If it doesn't, send a wiki link instead
message.channel.send(url);
}
I’ve looked at some code examples online, but they crash my bot. Do I need to use AJAX or something else? Any help would be awesome!
For URL validation in a Discord bot, I’d recommend using the ‘got’ library. It’s reliable and easy to use. First, install it with ‘npm install got’. Then, modify your code like this:
const got = require(‘got’);
async function checkUrl(url) {
try {
await got.head(url);
return true;
} catch (error) {
return false;
}
}
// In your command handler:
const urlExists = await checkUrl(url);
if (urlExists) {
message.channel.send(url);
} else {
message.channel.send(‘https://wiki.example.com/characters’);
}
This approach is efficient and handles various edge cases. Remember to implement proper error handling and rate limiting to prevent abuse. Good luck with your bot!
yo, have u tried using axios? it’s pretty cool for http requests. just npm install axios and then:
const axios = require('axios');
axios.get(url)
.then(() => message.channel.send(url))
.catch(() => message.channel.send('wiki link here'));
works like a charm for me, hope it helps!
I’ve dealt with similar issues in my Discord bot projects. For URL validation, you don’t need AJAX since you’re working server-side. Instead, try using the ‘node-fetch’ package. It’s lightweight and perfect for this task.
First, install it with npm install node-fetch. Then, in your code:
const fetch = require('node-fetch');
// In your command handler:
const response = await fetch(url);
if (response.ok) {
message.channel.send(url);
} else {
message.channel.send('https://wiki.example.com/characters');
}
This checks if the URL returns a successful status code. If not, it sends the wiki link. Remember to wrap this in a try-catch block to handle network errors gracefully.
Hope this helps! Let me know if you need any clarification.