Slashcommands with API

Hi, i tried to create a SlashCommand which gets data from https://brawlhalla.fly.dev/v1/glory/id?brawlhalla_id=3145331 but idk why the slash command doesnt work. (im new to js)
const { SlashCommandBuilder } = require('@discordjs/builders');
const fetch = require('node-fetch');

module.exports = {
data: new SlashCommandBuilder()
.setName('glory')
.setDescription('Zeigt Informationen über einen Spieler in Brawlhalla an.')
.addIntegerOption(option =>
option.setName('brawlhalla_id')
.setDescription('Die Brawlhalla ID des Spielers')
.setRequired(true)),

async execute(interaction) {
const brawlhallaId = interaction.options.getInteger('brawlhalla_id');
const url = `https://brawlhalla.fly.dev/v1/glory/id?brawlhalla_id=${brawlhallaId}`;

try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}

const data = await response.json();


console.log(data);

await interaction.reply('Daten erfolgreich abgerufen.');
} catch (error) {
console.error('Error fetching data from Brawlhalla API:', error);
await interaction.reply('Es gab ein Problem beim Abrufen der Daten.');
}
},
};
const { SlashCommandBuilder } = require('@discordjs/builders');
const fetch = require('node-fetch');

module.exports = {
data: new SlashCommandBuilder()
.setName('glory')
.setDescription('Zeigt Informationen über einen Spieler in Brawlhalla an.')
.addIntegerOption(option =>
option.setName('brawlhalla_id')
.setDescription('Die Brawlhalla ID des Spielers')
.setRequired(true)),

async execute(interaction) {
const brawlhallaId = interaction.options.getInteger('brawlhalla_id');
const url = `https://brawlhalla.fly.dev/v1/glory/id?brawlhalla_id=${brawlhallaId}`;

try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}

const data = await response.json();


console.log(data);

await interaction.reply('Daten erfolgreich abgerufen.');
} catch (error) {
console.error('Error fetching data from Brawlhalla API:', error);
await interaction.reply('Es gab ein Problem beim Abrufen der Daten.');
}
},
};
18 Replies
d.js toolkit
d.js toolkit5mo ago
- What's your exact discord.js npm list discord.js and node node -v version? - Not a discord.js issue? Check out #other-js-ts. - Consider reading #how-to-get-help to improve your question! - Explain what exactly your issue is. - Post the full error stack trace, not just the top part! - Show your code! - Issue solved? Press the button! - Marked as resolved by OP
Hype
HypeOP5mo ago
[email protected] Node.js v20.14.0
NyR
NyR5mo ago
Explain "doesn't work" how?
Hype
HypeOP5mo ago
No description
Hype
HypeOP5mo ago
forgot to send mb not responding*
NyR
NyR5mo ago
That tells us nothing, what errors you get in console? If any. Also you are fetching from an API there, which can take more than 3s, so you might wanna defer before that, and then edit the response after getting your data
Hype
HypeOP5mo ago
console is saying "No command matching glory was found."xd im gonna try that ty
NyR
NyR5mo ago
That looks like a custom error, show the full error stack instead of just describing it, also show your interaction handler
Hype
HypeOP5mo ago
theres no full error stack, thats the only output, or im too stupid to find it. xd deploy-commands.js
const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json');
const fs = require('fs');
const path = require('path');

const commands = [];

const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);

if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}

const rest = new REST({ version: '10' }).setToken(token);

(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);

const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);

console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(`Error refreshing application (/) commands: ${error.message}`);
}
})();
const { REST, Routes } = require('discord.js');
const { clientId, guildId, token } = require('./config.json');
const fs = require('fs');
const path = require('path');

const commands = [];

const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);

if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON());
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}

const rest = new REST({ version: '10' }).setToken(token);

(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);

const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);

console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) {
console.error(`Error refreshing application (/) commands: ${error.message}`);
}
})();
index.js
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

const express = require('express');
const { port } = require('./config.json');

const app = express();

app.get('/', (request, response) => {
return response.sendFile('index.html', { root: '.' });
});

app.listen(port, () => console.log(`App listening at http://localhost:${port}`));

for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}

client.once(Events.ClientReady, readyClient => {
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.commands = new Collection();
const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath);

const express = require('express');
const { port } = require('./config.json');

const app = express();

app.get('/', (request, response) => {
return response.sendFile('index.html', { root: '.' });
});

app.listen(port, () => console.log(`App listening at http://localhost:${port}`));

for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command);
} else {
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
}
}
}

client.once(Events.ClientReady, readyClient => {
console.log(`Ready! Logged in as ${readyClient.user.tag}`);
});
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);

if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}

try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
});

client.login(token);
client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName);

if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}

try {
await command.execute(interaction);
} catch (error) {
console.error(error);
if (interaction.replied || interaction.deferred) {
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
} else {
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
});

client.login(token);
chewie
chewie5mo ago
your command isnt being picked up by the handler can you show your file tree, where the file is located exactly
Hype
HypeOP5mo ago
No description
Hype
HypeOP5mo ago
anyone else with advice? 🙂
Unknown User
Unknown User5mo ago
Message Not Public
Sign In & Join Server To View
d.js docs
d.js docs5mo ago
:node: fs.readdirSync(path[, options]) Reads the contents of the directory.
Hype
HypeOP5mo ago
alr ty @rmHawk765 tysm, it worked ❤️ nvm, new problem, i updated the handler with recursive. i added a 2nd command with same nearly same api usage.
const { SlashCommandBuilder } = require('@discordjs/builders');
const fetch = require('node-fetch');

module.exports = {
data: new SlashCommandBuilder()
.setName('stats')
.setDescription('Zeigt Informationen über einen Spieler in Brawlhalla an.')
.addIntegerOption(option =>
option.setName('brawlhalla_id')
.setDescription('Die Brawlhalla ID des Spielers')
.setRequired(true)),

async execute(interaction) {
await interaction.deferReply(); // Den Befehl zunächst als "ausgeführt" markieren

const brawlhallaId = interaction.options.getInteger('brawlhalla_id');
const url = `https://brawlhalla.fly.dev/v1/ranked/id?brawlhalla_id=${brawlhallaId}`;

try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}

const data = await response.json();

// Verarbeite die Daten und sende die Antwort an Discord
const playerName = data.data.name;
const peakRating = data.data.peak_rating;

await interaction.editReply(`Das Peak Rating von Spieler ${playerName} beträgt: ${peakRating}`);
} catch (error) {
console.error('Error fetching data from Brawlhalla API:', error);
await interaction.editReply('Es gab ein Problem beim Abrufen der Daten.');
}
},
};
const { SlashCommandBuilder } = require('@discordjs/builders');
const fetch = require('node-fetch');

module.exports = {
data: new SlashCommandBuilder()
.setName('stats')
.setDescription('Zeigt Informationen über einen Spieler in Brawlhalla an.')
.addIntegerOption(option =>
option.setName('brawlhalla_id')
.setDescription('Die Brawlhalla ID des Spielers')
.setRequired(true)),

async execute(interaction) {
await interaction.deferReply(); // Den Befehl zunächst als "ausgeführt" markieren

const brawlhallaId = interaction.options.getInteger('brawlhalla_id');
const url = `https://brawlhalla.fly.dev/v1/ranked/id?brawlhalla_id=${brawlhallaId}`;

try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}

const data = await response.json();

// Verarbeite die Daten und sende die Antwort an Discord
const playerName = data.data.name;
const peakRating = data.data.peak_rating;

await interaction.editReply(`Das Peak Rating von Spieler ${playerName} beträgt: ${peakRating}`);
} catch (error) {
console.error('Error fetching data from Brawlhalla API:', error);
await interaction.editReply('Es gab ein Problem beim Abrufen der Daten.');
}
},
};
And ive the same problem "No command matching stats was found." i dont understand why its the same problem and why stats is not working but my other command from the top is. the data from my first command looks like that
{
"statusCode": 200,
"message": "barbarbar338 from database",
"data": {
"brawlhalla_id": 3145331,
"name": "barbarbar338",
"bestElo": 1865,
"eloReset": 1680,
"glory": {
"wins": 300,
"rating": 3792
},
"lastSynced": 1721253293077
}
}
{
"statusCode": 200,
"message": "barbarbar338 from database",
"data": {
"brawlhalla_id": 3145331,
"name": "barbarbar338",
"bestElo": 1865,
"eloReset": 1680,
"glory": {
"wins": 300,
"rating": 3792
},
"lastSynced": 1721253293077
}
}
and the data from my new command like that
{
"statusCode": 200,
"message": "barbarbar338 synced",
"data": {
"name": "barbarbar338",
"brawlhalla_id": 3145331,
"rating": 1833,
"peak_rating": 1865,
"tier": "Platinum 3",
"wins": 13,
"games": 22,
"region": "EU",
"global_rank": 0,
"region_rank": 0,
"legends": [
{
"legend_id": 3,
"legend_name_key": "bodvar",
"rating": 752,
"peak_rating": 0,
"tier": "Tin 1",
"wins": 0,
"games": 0
},
{
"legend_id": 4,
"legend_name_key": "cassidy",
"rating": 756,
"peak_rating": 0,
"tier": "Tin 1",
"wins": 0,
"games": 0
},...........
{
"statusCode": 200,
"message": "barbarbar338 synced",
"data": {
"name": "barbarbar338",
"brawlhalla_id": 3145331,
"rating": 1833,
"peak_rating": 1865,
"tier": "Platinum 3",
"wins": 13,
"games": 22,
"region": "EU",
"global_rank": 0,
"region_rank": 0,
"legends": [
{
"legend_id": 3,
"legend_name_key": "bodvar",
"rating": 752,
"peak_rating": 0,
"tier": "Tin 1",
"wins": 0,
"games": 0
},
{
"legend_id": 4,
"legend_name_key": "cassidy",
"rating": 756,
"peak_rating": 0,
"tier": "Tin 1",
"wins": 0,
"games": 0
},...........
im too stupid to understand that
az.5577
az.55775mo ago
What error ur receiving?
Hype
HypeOP5mo ago
Theres no error, the command handler wont register the command Had the same Problem with my first command, but fixed it and now i have the same Problem again
az.5577
az.55775mo ago
Try console logging every command path to check if he finds the command or no
Want results from more Discord servers?
Add your server