Delete Discord.js v13 slash command that doesnt exist - javascript

lately, I started working on a discord bot and added slash commands.
I noticed that I have a ping(replies with pong) command that I didn't create or I did and I can't get rid of it.
Here is my interactionHandler.js
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
module.exports = async (err, files, client) => {
if (err) return console.error(err);
client.interactionsArray = [];
files.forEach((file) => {
const interaction = require(`./../interactions/${file}`);
client.interactions.set(interaction.data.name, interaction);
client.interactionsArray.push(interaction.data.toJSON());
});
const rest = new REST({ version: "9" }).setToken(process.env.DISCORD_TOKEN);
(async () => {
try {
// console.log("Refreshing slash command list");
// const guildIds = await client.guilds.cache.map((guild) => guild.id);
// const clientId = await client.user.id;
// guildIds.forEach(async (guildId) => {
// await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
// body: client.interactionsArray,
// });
// });
await rest.put(
Routes.applicationGuildCommands("934895917453168653", "967384688069066852"),
{ body: client.interactionsArray},
);
console.log("Successfully refreshed slash command list");
} catch (error) {
console.error(error);
}
})();
};
Is there a way to delete the command because I cant find a way.
I was thinking of getting the ID of the command but I don't know how.
Thanks for all the helpers :)
Discord.js v13

These commands may not be refreshing because of 2 reasons:
These commands may be global commands to change that to refreshing global (instead of guild) commands replace Routes.applicationGuildCommands to Routes.applicationCommands
These commands may be from a different guild which in the case you should change the guild ID
To figure out the problem you should do client.application.commands.fetch() to get all your commands and then console.log() the result.
Example
//This will fetch all your slash commands
const commands = await client.application.commands.fetch();
//Returns a collection of application commands
console.log(commands);

Related

deferReply() cannot solve DiscordAPIError[10062]: Unknown interaction

I am trying to make a discord bot with discordJS (v14) and I followed the tutorial from
https://discordjs.guide/creating-your-bot/slash-commands.html#individual-command-files and created a slash command. However, when I call the slash command, it always shoe DiscordAPIError[10062]: Unknown interaction I tried to use the command await interaction.deferReply() but it still failed.
Here are my code of that function
play.js
const { SlashCommandBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("Play the song from the url or search query")
.addStringOption(option =>
option.setName("query")
.setDescription("The url or search query")
.setRequired(true)
),
async execute(interaction) {
console.log("interaction received"); // This part can run
await interaction.deferReply()
console.log("play command executed"); // cannot run
await interaction.editReply({ content: interaction.options.getString("query"), ephemeral: true });
}
}
index.js
const fs = require('node:fs');
const path = require('node:path');
const {
Client,
Collection,
Events,
GatewayIntentBits,
REST,
Routes,
} = require('discord.js');
require("dotenv").config();
// Tokens
const BOT_TOKEN = process.env.DISCORD_TOKEN;
const CLIENT_ID = process.env.CLIENT_ID;
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const rest = new REST({ version: 10 }).setToken(BOT_TOKEN);
// When the client is ready, run this code (only once)
// We use 'c' for the event parameter to keep it separate from the already defined 'client'
client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`);
});
// Create a new collection for commands
client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
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);
// Set a new item in the Collection with the key as the command name and the value as the exported module
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.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return;
console.log(interaction);
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
console.log(`Executing ${interaction.commandName} command.`);
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
const commands = [];
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
console.log(command.data.toJSON());
commands.push(command.data.toJSON());
}
// try to register the slash commands
(async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationCommands(CLIENT_ID),
{ body: commands },
);
console.log(`Successfully reloaded ${data.length} application (/) commands.`);
// Log in to Discord with your client's token
client.login(BOT_TOKEN);
} catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error);
}
})();
The terminal result shows that it received the message but it continue to have the error
DiscordAPIError[10062]: Unknown interaction
May I ask how can I solve the problem and why it would happen?

Command interaction not responding

this code is not executing the desired function which is to be able to initiate a message to repeat on a set interval. When debugging there are no errors and the bot comes online fine but the command can't be used and it says nothing to suggest what the problem is.
I need a professionals help to identify the reason this code is not working and why the bot acts as if it does not even exist.
This is the shortest amount of code to replicate the results I have left out the config.json because it has my token but I know for sure that that file is configured properly anyway
Test.ts file in commands folder
const Discord = require("discord.js");
const source = require('../index');
module.exports.run = (Client, message, args) => {
if (!args [0]) return message.reply(`Please specify if you are turning the command on or off!`);
if (args[1]) return message.reply(`Please specify if you are turning the command on or off! [Too many Arguments!]`);
switch (args[0])
{
default:
{
message.reply('Invalid argument specified.')
break;
}
case "on":
{
if (!source.timedCheck){
source.timedCheck =setInterval(() =>{
// Function for set interval
console.log("Interval cycle run!" + (val++) + "times!");
valcheck();
}, 25 * 10000);
message.reply('command started!');
} else {
return message.reply(`command already running!`)
}
break;
}
case "off":
{
if (source.timedCheck){
message.reply(`user has turned off command!`);
clearInterval(source.timedCheck);
source.timedCheck = undefined;
} else {
return message.reply(`command already offline!`)
}
break;
}
}
let valcheck = () => {
if (source.val > 5){
clearInterval(source.timedCheck);
source.timedCheck = undefined;
message.channel.send(`command finished as scheduled!`);
}
};
};
module.exports.help = {
name: "test",
usage: "test <on/off>"
};
Index.js file
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
// Export variables for commands
module.exports.timedCheck = undefined;
module.exports.val = 0;
// Login to Discord with your client's token
client.login(token);
You didn't tell the bot to execute this command. In your Index file you have to require the command file, catch the "message" or the "interactionCreate" events and then execute your command.
This code is incomplete and I can only guide you in a direction as you miss many things in your code.
You should read a tutorial: https://discordjs.guide/creating-your-bot/creating-commands.html#command-deployment-script
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./src/commands');
// require every command and add to commands collection
for (const file of commandFiles) {
const command = require(`./src/commands/${file}`);
client.commands.set(command.name, command);
}
client.on('message', async message => {
// extract your args from the message, something like:
const args = message.content.slice(prefix.length).split(/ +/);
try {
command.execute(message, args, client); // provide more vars if you need them
} catch (error) {
// handle errors here
}

How to commit and push with simple-git (NODEJS)?

I'm trying to do a simple Commit & Push to an existing repo using simple-git however I can't find
any example regarding this issue in the API in NPM (or Github) of simple-git.
I'm talking about this package : https://www.npmjs.com/package/simple-git
Consider the code :
const gitRepo = 'REPO-URL';
const tempFolder = '...';
// Simple Git
const simpleGit = require('simple-git')();
const options = ['--depth', '1'];
const callback = () => {
console.log('Done cloning!');
// Now change some code in the cloned code
// and commit && push
};
// Cloning ...
simpleGit.outputHandler((command, stdout, stderr) => {
stdout.pipe(process.stdout);
stderr.pipe(process.stderr)
stdout.on('data', (data) => {
// Print data
console.log(data.toString('utf8'));})
})
.clone(gitRepo, tempFolder, options, callback);
How can we commit and push using simple-git ?
Like #Lawrence Cherone said :
You can just use the basic commands as is.
This is how i used it in my project ( though i got a submodule in it where this example is changing its (git)working directory to content(submodule) first. After that i just commit with a message.
app.post("/gitCommit", async function(req, res) {
try {
await git.cwd({ path: 'content' }).commit(req.body.msg);
res.sendStatus(200)
} catch(err) {
console.log(err)
}
});
If you already have a working and initialised repo your in,
then you could just do the following:
await git.commit("your_message")
await git.push()
await git.push('origin', 'master')
You can leave out the 'await' part depending on your code running async.

MongoDB reusable custom javascript module

I would like to create a local Javascript module I can "require" in other files to handle all MongoDB CRUD operations.
I wrote something as:
-- dbConn.js file --
require('dotenv').config()
const MongoClient = require('mongodb').MongoClient
const ObjectID = require('mongodb').ObjectID
let _connection
const connectDB = async () => {
try {
const client = await MongoClient.connect(process.env.MONGO_DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
console.log('Connected to MongoDB')
return client
} catch (err) {
console.log(error)
}
}
exports.findOne = async () => {
let client = await connectDB()
if (!client) {
return;
}
try {
const db = client.db("Test_DB");
const collection = db.collection('IoT_data_Coll');
const query = {}
let res = await collection.findOne(query);
return res;
} catch (err) {
console.log(err);
} finally {
client.close();
}
}
exports.findAll = async () => {
let client = await connectDB()
if (!client) {
return;
}
try {
const db = client.db("Test_DB");
const collection = db.collection('IoT_data_Coll');
const query = {}
let res = await collection.find(query).toArray();
return res;
} catch (err) {
console.log(err);
} finally {
client.close();
}
}
Then in another file (not necessary inside Express app), say
-- app.js ---
const findAll = require('./dbConn').findAll
const findOne = require('./dbConn').findOne
findAll().then(res => JSON.stringify(console.log(res)))
findOne().then(res => JSON.stringify(console.log(res)))
I wonder if it is correct?
I have to close the connection after each method/CRUD operation?
I was trying to use IIF instead of ".then", as:
(async () => {
console.log(await findOne())
})()
But I receive a weird error saying that findAll is not a function.
What's wrong with it?
Thanks.
It really depends on your use case which isn’t clear If you are using Express or just stand alone and how frequent are you planning to run app.js
Either way your code is expensive, each time you reference dbCon.js you are opening a new connection to the database.
So you can fix app.js by only requiring dbCon.js once and use it..
The best practice is to ofcourse use connection pooling https://www.compose.com/articles/connection-pooling-with-mongodb/

discord.js - give role by reacting - return value problem

So I wanted a command intomy bot, which iis able to give server roles if you react on the message. By google/youtube I done this. My problem is, that if I react on the message my algorith won't step into my switch also if I react to the costum emoji it won't even detect it that I reacted for it. Probably somewhere the return value is different but I was unable to find it yet. Sy could check on it?
const { MessageEmbed } = require('discord.js');
const { config: { prefix } } = require('../app');
exports.run = async (client, message, args) => {
await message.delete().catch(O_o=>{});
const a = message.guild.roles.cache.get('697214498565652540'); //CSGO
const b = message.guild.roles.cache.get('697124716636405800'); //R6
const c = message.guild.roles.cache.get('697385382265749585'); //PUBG
const d = message.guild.roles.cache.get('697214438402687009'); //TFT
const filter = (reaction, user) => ['πŸ‡¦' , 'πŸ‡§' , 'πŸ‡¨' , '<:tft:697426435161194586>' ].includes(reaction.emoji.name) && user.id === message.author.id;
const embed = new MessageEmbed()
.setTitle('Available Roles')
.setDescription(`
πŸ‡¦ ${a.toString()}
πŸ‡§ ${b.toString()}
πŸ‡¨ ${c.toString()}
<:tft:697426435161194586> ${d.toString()}
`)
.setColor(0xdd9323)
.setFooter(`ID: ${message.author.id}`);
message.channel.send(embed).then(async msg => {
await msg.react('πŸ‡¦');
await msg.react('πŸ‡§');
await msg.react('πŸ‡¨');
await msg.react('697426435161194586');
msg.awaitReactions(filter, {
max: 1,
time: 15000,
errors: ['time']
}).then(collected => {
const reaction = collected.cache.first();
switch (reaction.emoji.name) {
case 'πŸ‡¦':
message.member.addRole(a).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${a.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case 'πŸ‡§':
message.member.addRole(b).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${b.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case 'πŸ‡¨':
message.member.addRole(c).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${c.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
case '<:tft:697426435161194586>':
message.member.addRole(d).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role **${err.message}.**`);
});
message.channel.send(`You have been added to the **${d.name}** role!`).then(m => m.delete(30000));
msg.delete();
break;
}
}).catch(collected => {
return message.channel.send(`I couldn't add you to this role!`);
});
});
};
exports.help = {
name: 'roles'
};
As of discord.js v12, the new way to add a role is message.member.roles.add(role), not message.member.addRole. Refer to the documentation for more information.
You need to use roles.add() instead of addRole()
Mate, You cannot use the id of emoji in codes(except when you are sending a message). so, the custom emoji has to be replaced by a real emoji that shows a box in your editor and works perfectly in discord. If you can find it, then this might be complete as discord API cannot find the emoji <:tft:697426435161194586>. you can get an emoji by using it in discord and opening discord in a browser and through inspect element, get the emoji.
Else, you will have to use different emoji.

Categories

Resources