const {
InteractionType,
GatewayIntentBits,
EmbedBuilder,
} = require("discord.js");
const { Client } = require("discord.js");
const { SlashCommandBuilder } = require("@discordjs/builders");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { token, clientId, guildId } = require("../../config.json");
const client = new Client({
intents: Object.keys(GatewayIntentBits).map((a) => {
return GatewayIntentBits[a];
}),
});
const commandData = new SlashCommandBuilder()
.setName("checkuserguilds")
.setDescription("Check the guilds a user is in")
.addUserOption((option) =>
option
.setName("user")
.setDescription("The user to check the guilds for")
.setRequired(true)
);
const allowedRoleName = "DOW Directors"; // Replace 'YOUR_ALLOWED_ROLE_NAME' with the name of the role allowed to run the command
client.once("ready", async () => {
console.log(`Logged in as ${client.user.tag}!`);
const rest = new REST({ version: "9" }).setToken(token);
try {
console.log("Started refreshing application (/) commands.");
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: [commandData.toJSON()],
});
console.log("Successfully reloaded application (/) commands.");
} catch (error) {
console.error(error);
}
});
const execute = async (interaction) => {
if (interaction.type === InteractionType.ApplicationCommand) {
if (interaction.commandName === "checkuserguilds") {
if (!checkPermission(interaction.member)) {
return interaction.reply({
content: "You do not have permission to run this command.",
ephemeral: true,
});
}
const user = interaction.options.getUser("user");
if (!user) {
return interaction.reply({
content: "Please specify a user.",
ephemeral: true,
});
}
try {
const guilds = await getUserGuilds(user.id);
const embed = new EmbedBuilder()
.setColor("#0099ff")
.setTitle("User Guilds")
.setDescription(
`User ${user.tag} is in the following guilds:n${guilds.join("n")}`
);
await interaction.reply({ embeds: });
} catch (error) {
console.error("Error fetching user guilds:", error);
await interaction.reply("Error fetching user guilds.");
}
}
}
};
function checkPermission(member) {
return member.roles.cache.some((role) => role.name === allowedRoleName);
}
async function getUserGuilds(userId) {
try {
const user = await client.users.fetch(userId);
const userGuilds = client.guilds.cache.filter((guild) =>
guild.members.cache.has(user.id)
);
return userGuilds.map((guild) => guild.name);
} catch (error) {
console.error("Error fetching user guilds:", error);
return [];
}
}
module.exports = {
data: commandData,
execute,
};
I have tried to reset my tokens, and I am still receiving the “Error fetching user guilds: Expected token to be set for this request, but none was present.” I have configured the code to where I am not just handing out the token in all the commands. so it is centrally located in the config.json file.