I am developing a discord servers list, the site itself is complete, but I am having major issues ever since switching to slash commands (requirement for verification, unless approved for Message Intent). Basically what I am trying to accomplish (and what was working prior to switching to slash commands) is when my bot joins a guild, an admin can type: /setup – this command is supposed to get the guild id, approx. member count, server icon and send the information to my database (api/update-database.php) where server_id = ?.
Prior to switching, this worked by typing !setup. Now I am lost, the console is telling me: Error updating guild data: Request failed with status code 401
.
The bot token is set correctly in my .env file, as well as the client ID.
Here is my commands/api/setup.js
const { SlashCommandBuilder, PermissionFlagsBits } = require("discord.js");
const axios = require("axios");
async function sendInviteLinkToServer(guildId, inviteUrl) {
const apiUrl = "http://localhost/discord-servers/api";
try {
// Fetch server details from Discord API
const guildDetailUrl = `https://discord.com/api/guilds/${guildId}?with_counts=true`;
const response = await axios.get(guildDetailUrl, {
headers: {
Authorization: `Bot ${process.env.BOT_TOKEN}`,
},
});
if (response.status !== 200) {
console.error("Failed to fetch guild details:", response.statusText);
return;
}
const guildDetailData = response.data;
if (guildDetailData) {
const server_image = guildDetailData.icon
? `https://cdn.discordapp.com/icons/${guildId}/${guildDetailData.icon}.png`
: "https://localhost/discord-servers/images/site/no-image-available.png";
const user_count = guildDetailData.approximate_member_count || 0;
// Log data to console before making the POST request
console.log("Data to be sent to update-database.php:");
console.log("Server ID:", guildId);
console.log("Server Image:", server_image);
console.log("User Count:", user_count);
// Make a POST request to update-database.php
const updateDatabaseUrl = apiUrl + "/update-database.php";
const updateData = {
server_id: guildId,
server_image: server_image,
user_count: user_count,
invite_url: inviteUrl, // include the invite URL in the data
};
const headers = {
"Content-type": "application/x-www-form-urlencoded",
};
const dbResponse = await axios.post(updateDatabaseUrl, updateData, {
headers,
});
console.log("Database updated successfully:", dbResponse.data);
}
} catch (error) {
console.error(`Error updating guild data: ${error.message}`);
}
}
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup the invite link for the servers listing on redacted")
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
async execute(interaction) {
// Ensure the interaction is in a guild
if (!interaction.guild) {
await interaction.reply("This command can only be used in a server.");
return;
}
// Check if user has administrative permissions
if (
!interaction.member.permissions.has(PermissionFlagsBits.Administrator)
) {
await interaction.reply(
"You need to have administrator permissions to use this command."
);
return;
}
// Fetch the bot's member object
let botMember;
try {
botMember = await interaction.guild.members.fetch(
interaction.client.user.id
);
} catch (error) {
console.error("Failed to fetch bot member object:", error);
await interaction.reply(
"An error occurred while checking my permissions."
);
return;
}
// Ensure the bot has the correct permissions
const botPermissions = interaction.channel.permissionsFor(botMember);
if (!botPermissions.has(PermissionFlagsBits.SendMessages)) {
await interaction.reply(
"I don't have the permission to send messages in this channel."
);
console.error("Bot lacks SendMessages permission in the channel.");
return;
}
if (!botPermissions.has(PermissionFlagsBits.CreateInstantInvite)) {
await interaction.reply("I don't have the permission to create invites.");
console.error("Bot lacks CreateInstantInvite permission in the channel.");
return;
}
// Get the channel to create an invite for
const channel = interaction.guild.channels.cache.find(
(channel) =>
channel.type === 0 && // 0 corresponds to GUILD_TEXT
channel
.permissionsFor(botMember)
.has(PermissionFlagsBits.CreateInstantInvite)
);
if (!channel) {
await interaction.reply(
"Could not find a suitable channel to create an invite."
);
console.error("No suitable channel found for creating an invite.");
return;
}
try {
const invite = await channel.createInvite({
maxAge: 0, // Infinite duration
maxUses: 0, // Unlimited uses
});
try {
await interaction.reply(
`Successfully created an invite link and updated http://localhost.`
);
console.log("Message sent successfully.");
} catch (error) {
console.error("Failed to send message:", error);
}
// Send the invite link to the local server using Axios
await sendInviteLinkToServer(interaction.guild.id, invite.url);
} catch (error) {
console.error("Error creating invite:", error);
await interaction.reply("There was an error creating the invite link.");
}
},
};
Not sure if this is needed but I will post it anyway, update-database.php:
if (isset($_POST['server_id'], $_POST['server_image'], $_POST['user_count'])) {
// Retrieve POST data
$server_id = $_POST['server_id'];
$server_image = $_POST['server_image'];
$user_count = $_POST['user_count'];
// Example query: Update guild details
$stmt = $conn->prepare("UPDATE servers SET server_image = ?, user_count = ? WHERE server_id = ?");
$stmt->bind_param("ssi", $server_image, $user_count, $server_id);
if ($stmt->execute()) {
echo "Database updated successfully";
} else {
echo "Error updating database: " . $stmt->error;
}
$stmt->close();
} else {
echo "Missing POST data";
}
I removed the need for the API on my update-database.php to see if that was the issue, it was not. I am unsure what to do next, Discord.js is new to me!