Error with .addNumberOption (slash command) - javascript

I would like to make a commander (cmd slash) to activate maintenance on a remote server. Most of the order is done and functional. But when I want to put the number of minutes via a .addNumberOption, I get the error
Option "minutes" is of type: 10; expected 3.
data: new SlashCommandBuilder()
.setName('maintenancemc-staff')
.setDescription('Active ou désactive le mode maintenance du serveur Minecraft')
.addStringOption((option) =>
option
.setName('raison')
.setDescription('Raison du changement de statut')
.setRequired(true)
)
.addNumberOption((option) =>
option
.setName('minutes')
.setDescription("Décompte d'activation du mode maintenance en minute")
.setRequired(true)
),
async execute(interaction, client) {
await interaction.deferReply({ fetchReply: true, ephemeral: true });
const { options } = interaction;
const raison = options.getString("raison");
const timer = options.getString("minutes");
...
Thank you in advance for your help! 🦊

If you use addNumberOption, instead of options.getString("minutes"), you need to use options.getNumber("minutes").

Related

how to make an slash command with random answers?

My code does not return an error but when I call it on discord, it does not responding.
import { SlashCommandBuilder, EmbedBuilder, CommandInteraction } from "discord.js";
import { SlashCommand } from "../types";
export const command: SlashCommand = {
name: "dé",
data: new SlashCommandBuilder().setName("dé").setDescription("DUEL"),
execute: async (interaction) => {
const liste = [
"`1, tu as fait une réussite critique`",
"`2, tu as fait une réussite moyenne`",
"`3, tu as fait une réussite moyenne`",
"`4, tu as fait une petite réussite`",
"`5, tu as fait un petit échec`",
"`6, tu as fait un echec critique`",
"`7, quelque chose de drôle va arriver`",
"`8, ça provoque l'effet d'un autre sort`",
];
await interaction.reply({
embeds: [new EmbedBuilder().setDescription(liste[Math.floor(Math.random() * liste.length)])],
});
},
};
I would like to make an slashcommand that answers one of these eight answers at random.
I copied your code and checked myself, it works. So the problem is something else, didn't you forget to configure intents? Because it depends on whether the bot can write to the guild.
For example, you can set up the client in this way:
export const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageTyping
]})
You also need to go to https://discord.com/developers/applications/. There, click on the "Bot" tab and turn on all the checkboxes on Privileged Gateway Intents
P.S. Below I'm just proving that the code works. execute is a slash command

Discord.js Error with my embed and idk how to resolve it

i have a embed on my ready.js that sends it to a channel, and its giving me this error
ValidationError: Expected the value to be an object, but received string instead
at ObjectValidator.handle (/root/ZyruzBot/node_modules/#sapphire/shapeshift/dist/index.js:1161:25)
at ObjectValidator.parse (/root/ZyruzBot/node_modules/#sapphire/shapeshift/dist/index.js:113:88)
at EmbedBuilder.setAuthor (/root/ZyruzBot/node_modules/discord.js/node_modules/#discordjs/builders/dist/messages/embed/Embed.cjs:42:37)
at sendTicketMSG (/root/ZyruzBot/events/ready.js:13:10)
at Timeout._onTimeout (/root/ZyruzBot/events/ready.js:86:7)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
validator: 's.object(T)',
given: '🎫 Cria um ticket aqui'
}
Heres the embed and the start of the code:
const { EmbedBuilder } = require('discord.js');
module.exports = {
name: 'ready',
async execute(client) {
console.log('Bot Online!')
console.log('Bot Dev Chain');
const oniChan = client.channels.cache.get(client.config.ticketChannel)
function sendTicketMSG() {
const embed = new EmbedBuilder()
.setColor('ff0000')
.setAuthor('🎫 Cria um ticket aqui', client.user.avatarURL())
.setDescription('Aqui pode abrir um ticket para obter\n\n **__<:SupportTeam:1013602711683473499> Suporte\n <:Servers:1013601908105171014> Adquirir a sua vps\n <a:developer_bot:1013602040745824336> Adquirir o seu bot de discord\n <a:partnership:1013602912162828308> Fazer uma Parceria__**')
.setFooter(client.config.footerText, client.user.avatarURL())
const row = new client.discord.MessageActionRow()
.addComponents(
new client.discord.MessageButton()
.setCustomId('open-ticket')
.setLabel('Cria um ticket aqui')
.setEmoji('🎫')
.setStyle('PRIMARY'),
);
oniChan.send({
embeds: [embed],
components: [row]
})
}
Idk whats generating this error, if you guys know please let me know
Your error lies in the .setAuthor() Method. It seems, that you use a newer version of discord.js in which this method requests an Object with the information.
In this link is another example using an object, maybe this will resolve your issue.
EmbedBuilder

Discord.js V13 Setup Command that collect a Channel

I want to make a Setup Command for my Bot, that I can use to set up channels for the bot e.g. a welcome channel. For this, I used a JSON file.
Code
collector.on('collect', async (i) => {
if (i.customId === 'modchannelbutton') {
const ModChannelSetEmbed = new MessageEmbed()
.setTitle('<:vsl_settings:991655211179442216> | **__SERVER SETUP__**')
.addField(
'» Stand',
setupconfig[interaction.guild.id].modlog === 'nochannel'
? '<:m_notdone:991657968296808478> Du hast noch kein Moderator Log gesetzt'
: `<:m_done:991657855549710376> Dein aktueller Moderator Log ist: <#${
setupconfig[interaction.guild.id].modlog
}>`,
)
.setDescription(
'> Du hast 1 Minute Zeit um einen neuen Moderator Log zu setzen, schreib dafür einfach nur den #Channel in diesem Channel',
)
.setColor('#0c06b6');
row.components[0].setDisabled(true);
await i.update({ embeds: [ModChannelSetEmbed], components: [] });
// … Here I need the Message Collector for the Channel …
}
});
I want to make a collector that collected if the message next to the button is clicked in a channel. But all my tries don't reply.
That means:
Slash Command use —> Button Click —> Channel send
The Collector should control if the message next to the button click is a channel.

Script of welcome / goodbye to discord js bot Error

He is giving me this script of welcome/goodbye to Discord error and he has already tried many things if someone helps me I would appreciate it very much, Thanks
module.exports = (client) => {
const channelIdA = '718596514305277972'
client.on('guildMemberAdd', (member) => {
console.log("Se ha unido una nueva persona al servidor TPA")
const messageA = `message`
const channel = (channelIdA)
channel.send(messageA)
})
}
module.exports = (client) => {
const channelIdB = '890891192995303424'
client.on('guildMemberRemove', (member) => {
console.log("Se ha salido una persona del servidor TPA")
const messageB = `message`
const channel = (channelIdB)
channel.send(messageB)
})
}
You are attempting to send a message to a channel by calling the .send() method. However, you are calling the method on a string. The send() method only exists on text based channels. To send a message to a specific channel, replace your message sending code with this
client.on("guildMemberAdd", members => {
client.channels.cache.get("REPLACE WITH CHANNEL ID").send("message")
});
client.on("guildMemberRemove", members => {
client.channels.cache.get("REPLACE WITH OTHER CHANNEL ID").send(" other message")
});
If the above does not work, try this:
(works without cache)
client.on("guildMemberAdd", async (member) => {
const channel = await client.channels.fetch("REPLACE WITH CHANNEL ID")
channel.send(`${member.user.username}, welcome`)
});
client.on("guildMemberRemove", async (member) => {
const channel = await client.channels.fetch("REPLACE WITH OTHER CHANNEL ID")
channel.send(`${member.user.username} has left`)
});
You should be getting the channel using this. If you already have the channel in cache (something happened in the channel after the bot started), you can use the channels cache as well.

Delete an embed when a reaction is added

module.exports.run = (client, message, args) => {
if (message.member.roles.some(role => role.name === process.env.MODO)) {
const user = message.mentions.users.first();
// Parse Amount
const amount = !!parseInt(message.content.split(' ')[1]) ? parseInt(message.content.split(' ')[1]) : parseInt(message.content.split(' ')[2])
if (!amount) return message.reply('Vous devez spécifier un montant à supprimer !');
if (!amount && !user) return message.reply('Vous devez spécifier un utilisateur et le montant, ou juste une quantité de messages à purger !');
if (amount > 100) return message.reply('Malheureusement, discord ne permet pas la Suppression de plus de 100 messages en une fois ...');
// Fetch 100 messages (will be filtered and lowered up to max amount requested)
message.channel.fetchMessages({
limit: amount,
}).then((messages) => {
if (user) {
const filterBy = user ? user.id : Client.user.id;
messages = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
}
message.channel.bulkDelete(messages).catch(error => console.log(error.stack));
});
var purge = new Discord.RichEmbed()
.setAuthor(`Suppression de ${amount} Messages dans le salon ${message.channel.name}`)
.setFooter("Requête par " + message.member.user.tag, message.member.user.avatarURL)
.setTimestamp()
.setColor(0xF03434)
message.channel.send(purge).then(message => {
message.react('🗑')
client.on('messageReactionAdd', (reaction, user) => {
// on vérifie que ce soit bien la bonne réaction et on ne compte pas celui du bot
if (reaction.emoji.name === '🗑' && user.id !== client.user.id) {
message.delete()
}
})
});
}
}
What I would like is that at the level of the 'final' embed, when it tells me that the purge has been done, there is a reaction '🗑' and when we click it removes the message.
The problem is that the current code removes all the embed of the same type.
If I click on the reaction of the first embed, it also removes the second, and does not delete anything else...
Attaching a listener to the client's messageReactionAdd event is what's causing this; any reaction emits this event, and your code is executed for each one after a single purge. As long as the reaction is 🗑 and the user isn't the client, Message.delete() will be called on message.
(node: 10752) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at item.request.gen.end (/Users/jeremy/Desktop/BERRYBOT/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:85:15)
at then (/Users/jeremy/Desktop/BERRYBOT/node_modules/snekfetch/src/index.js:215:21)
at process._tickCallback (internal / process / next_tick.js: 68: 7)
(node: 10752) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated from the inside of the outside world, but it was not handled by .catch (). (rejection id: 14)
After adding that reaction that deletes the wrong message, it no longer exists. When you try to delete it again, this error will be thrown.
Furthermore, your code isn't waiting for the messages to be purged before sending the reply. Because of this, the message can be sent before and subsequently deleted by the TextChannel.bulkDelete() call. Then, when you try to react to the same message via Message.react(), your error is thrown because it no longer exists.
To make sure the code is executed in the proper order, make sure you're using your then() chains properly, or utilize the beauty of async/await.
Reorganizing the code, still using then() methods:
message.channel.fetchMessages({ limit: amount })
.then(fetchedMessages => {
const filterBy = user ? user.id : Client.user.id;
const toPurge = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
message.channel.bulkDelete(toPurge)
.then(deletedMessages => {
var embed = new Discord.RichEmbed()
.setAuthor(`Suppression de ${deletedMessages.size} Messages dans le salon ${message.channel.name}`)
.setFooter(`Requête par ${message.author.tag}`, message.author.avatarURL)
.setTimestamp()
.setColor(0xF03434)
message.channel.send(embed)
.then(reply => {
reply.react('🗑');
const filter = (reaction, user) => reaction.emoji.name === '🗑' && user.id !== client.user.id;
reply.createReactionCollector(filter, { maxMatches: 1 })
.on('collect', () => reply.delete());
});
});
})
.catch(console.error);
Alternatively, using await:
// You must define your callback function as async to use the 'await' keyword! It should look like...
// async (client, message, args) => { ... }
try {
const fetchedMessages = await message.channel.fetchMessages({ limit: amount });
const filterBy = user ? user.id : Client.user.id;
const toPurge = messages.filter(m => m.author.id === filterBy).array().slice(0, amount);
const deletedMessages = await message.channel.bulkDelete(toPurge);
var embed = new Discord.RichEmbed()
.setAuthor(`Suppression de ${deletedMessages.size} Messages dans le salon ${message.channel.name}`)
.setFooter(`Requête par ${message.author.tag}`, message.author.avatarURL)
.setTimestamp()
.setColor(0xF03434)
const reply = await message.channel.send(embed)
await reply.react('🗑');
const filter = (reaction, user) => reaction.emoji.name === '🗑' && user.id !== client.user.id;
reply.createReactionCollector(filter, { maxMatches: 1 })
.on('collect', async () => await reply.delete());
} catch(err) {
console.error(err);
}
You'll notice this code is using ReactionCollectors as opposed to attaching listeners to the messageReactionAdd event. The former are meant for this usage and will prevent memory leaks. Also, I've changed some of the variable names to make the code easier to read and understand. A few other very minor improvements are present as well.

Categories

Resources