so I was trying to make a slash command for kicking users on discord but for some reason there seems to be a mistake somewhere, it alwas says DiscordAPIError[40060]: Interaction has already been acknowledged
Code [Please ignore the german sentences]:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { EmbedBuilder, PermissionsBitField } = require('discord.js');
const { execute } = require("./clear");
module.exports = {
data: new SlashCommandBuilder()
.setName('kick')
.setDescription('Dieser Command wird ein Mitglied des Servers von diesem kicken')
.addUserOption(option => option.setName('target').setDescription('Welches Mitglied möchtest du vom Server kicken?').setRequired(true))
.addStringOption(option => option.setName('reason').setDescription('Grund:')),
async execute (interaction, client) {
const kickUser = interaction.options.getUser('target');
const kickMember = await interaction.guild.members.fetch(kickUser.id);
const channel = interaction.channel;
if (!interaction.member.permissions.has(PermissionsBitField.Flags.KickMembers)) return await interaction.reply({ content: "Du kannst das Mitglied aufgrund deiner fehlenden Rechte nicht nutzen", ephemeral: true});
if (!kickMember) return await interaction.reply({ content: 'Der ausgewählte Nutzer ist nicht mehr auf dem Server!', ephemeral: true});
if (!kickMember.kickable) return await interaction.reply({ content: "Dieses Mitglied kann nicht von mir gekickt werden, da dieser über mir steht", ephemeral: true});
let reason = interaction.options.getString('reason');
if (!reason) reason = "Kein Grund angegeben.";
const dmEmbed = new EmbedBuilder()
.setColor('Aqua')
.setDescription(`:white_check_mark: Du wurdest von Otaku Haven gekickt | ${reason}`)
const embed = new EmbedBuilder()
.setColor('Aqua')
.setDescription(`:white_check_mark: ${kickUser.tag} wurde vom Server **gekickt** | ${reason}`)
await kickMember.send({ embeds: [dmEmbed] }).catch(err => {
return;
});
await kickMember.kick({ reason: reason}).catch(err => {
interaction.reply({ content: "Es gab einen Fehler", ephemeral: true});
});
await interaction.reply({ embeds: [embed] });
}
}
I expected the code to work because I compared it to another example code to make sure that there is no mistake!
Related
today i was trying to make a /warn command that DM the warned user, but when i do that i see an error saying : "Expected token to be set for this request, but none was present"
could anyone help me ?
there is my code :
const { SlashCommandBuilder, PermissionFlagsBits, messageLink, Client } = require('discord.js');
const { GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
module.exports = {
data: new SlashCommandBuilder()
.setName('warn')
.setDescription('Choisi une qqun à warn.')
.addUserOption(option =>
option
.setName('cible')
.setDescription('Le membre à warn')
.setRequired(true))
.addStringOption(option =>
option
.setName('raison')
.setDescription('La raison du warn'))
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
async execute(interaction) {
const target = interaction.options.getUser('cible');
await client.users.send(target.id, 'vous avez été warn.')
await interaction.reply(`${target.username} warn`);
},
};
you just need to do
let raison = interaction.options.getString('raison');
if (!raison) raison = "No raison provided.";
try {
target.send(`vous avez été warn. \n> Raison: ${raison}`)
} catch (e) { interaction.reply({content: 'couldn\'t dm user his DMs are closed', ephemeral: true}) }
I made a command that creates an embed based on a message in discord such as:
!embed #FF0000 - Hello - World - https:/random_image.png
but how can I make a parameter optional, for example make an embed without image
const Discord = require("discord.js");
module.exports = {
name: "embed",
description: "Genera un embed en base a un imput",
permissions: ["BAN_MEMBERS"],
async execute(client, message, args, discord) {
if (! message.member.permissions.has("BAN_MEMBERS")) return message.channel.send("No tienes permiso para usar este comando.")
const msgcontent = args.join(" ");
const msgsplit = msgcontent.split(' - ');
const color = msgsplit[0]
const title = msgsplit[1]
const description = msgsplit[2]
const image = msgsplit[3]
if(!color) return message.channel.send('¡Ingresa el codigo HEX que quieres en tu embed!');
if(!title) return message.channel.send("¡Ingresa el título que quieres en tu embed!");
if(!description) return message.channel.send("Ingresa la descripción que quieres en tu embed!");
if (!image) return message.channel.send("Ingresa el link de la imagen que quieres en tu embed!")
const embed = new Discord.MessageEmbed()
.setColor(`${color}`)
.setTitle(`${title}`)
.setDescription(`${description}`)
.setImage(`${image}`)
message.channel.send({ embeds: [embed] });
}
}
If the image field is empty, you can create a new embed without it. Kind of like this
if(image === undefined){
const embed = new Discord.MessageEmbed()
.setColor(`${color}`)
.setTitle(`${title}`)
.setDescription(`${description}`)
message.channel.send({ embeds: [embed] });
}
Or state the embed before and then use the return function.
if(image === undefined) return message.channel.send({ embeds: [embed] });
I realize that posts about this kind of topic exists, but I'm really new to JS and wouldn't really be able to understand if it's not about what I'm doing specifically. I'm trying to make a music bot for discord following along and trying to learn from a tutorial, and it didn't recognize that I was in a voice channel, so it wouldn't play anything. Then this error started showing up after a little looking around to see what I did wrong. It also gives me this error message: UnhandledPromiseRejectionWarning: Unhandled promise rejection. Which I'm not really sure how to fix. It says "This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()." But again, as I'm new to this I really don't understand what that means.
Ignore the ill-mannered Swedish by the way, but here is the entire thing:
const Discord = require('discord.js');
const {
prefix,
token,
} = require('./config.json');
const ytdl = require('ytdl-core');
const client = new Discord.Client();
const queue = new Map();
client.once('ready', () => {
console.log('Ready!');
});
client.once('reconnecting', () => {
console.log('Reconnecting!');
});
client.once('disconnect', () => {
console.log('¨Disconnect!');
});
client.on('message', async message => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const serverQueue = queue.get(message.guild.id);
if (message.content.startsWith(`${prefix}play`)) {
execute(message, serverQueue);
return;
} else if (message.content.startsWith(`${prefix}play`)) {
skip(message, serverQueue);
} else if (message.content.startsWith(`${prefix}stop`)) {
stop(message, serverQueue);
return;
}
});
async function execute(message, serverQueue) {
const args = message.content.split(" ");
const voiceChannel = message.member.voice.Channel;
if (!voice.channel)
return message.channel.send(
"Hur fan ska jag kunna spela musik om du inte är i en kanal? Jävla mongo."
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"Ok, så du vill att jag spelar upp musik, men ger mig inte tillåtelse att spela upp musik? Fixa dina perms dumfan."
);
}
let song;
if (ytdl.validateURL(args[1])) {
const songInfo = await ytdl.getInfo(args[1]);
song = {
title: songInfo.title,
url: songInfo.video_url
};
} else {
const {videos} = await yts(args.slice(1).join(" "));
if (!videos.length) return message.channel.send("No songs were found!");
song = {
title: videos[0].title,
url: videos[0].url
};
}
if (!serverQueue) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true,
};
queue.set(message.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
}else {
serverQueue.songs.push(song);
return message.channel.send(`${song.title}? Ok, lägger till den i kön.`);
}
}
function skip(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"Du måste var i en röstkanal för att stoppa musik din dumma jävel."
);
if (!serverQueue)
return message.channel.send("Det finns ingen låt att skippa dtt sär.");
serverQueue.connection.dispatcher.end();
}
function stop(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"Du måste var i en röstkanal för att stoppa musik din dumma jävel."
);
if (!serverQueue)
return message.channel.send("Det finns ingen låt att stoppa dtt sär.");
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const dispatcher = serverQueue.connection
.play(ytdl(song.url))
.on("finish", () => {
serverQueue.songs-shift();
play(guild, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolume.Logarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Nu spelar jag: **${song.title}** din hora`);
}
client.login(token);
Don't know if I did this post right...
And sorry about the formatting.
Thanks in advance though!
I am trying to make a music Discord Bot with a queue. Currently, the play command work and I can add music to the queue (displayed with my playlist command). The problem is when the first music ends, the bot completly stops and do not play the next song (it do not disconnect and looks like it's playing something).
I use Discord.js v12, ffmpeg-static and the Youtube API.
if (command === "play" || command === "p") {
const args = message.content.split(" ");
const searchString = args.slice(1).join(" ");
if (!args[1]) {
return message.channel.send('Il faut spécifier une URL !')
.catch(console.error);
}
const url = args[1] ? args[1].replace(/<(.+)>/g, "$1") : "";
const serverQueue = queue.get(message.guild.id);
var voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send("Tu dois être dans un salon vocal pour utiliser cette commande !");
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT")) {
return message.channel.send("J'ai besoin de la permission **`CONNECT`** pour cette commande");
}
if (!permissions.has("SPEAK")) {
return message.channel.send("J'ai besoin de la permission **`SPEAK`** pour parler");
}
if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
const playlist = await youtube.getPlaylist(url);
const videos = await playlist.getVideos();
for (const video of Object.values(videos)) {
const video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
await handleVideo(video2, message, voiceChannel, true); // eslint-disable-line no-await-in-loop
}
return message.channel.send(`:white_check_mark: **|** Playlist: **\`${playlist.title}\`** a été ajouté à la playlist !`);
} else {
try {
var video = await youtube.getVideo(url);
} catch (error) {
try {
var videos = await youtube.searchVideos(searchString, 10);
let index = 0;
// eslint-disable-next-line max-depth
try {
} catch (err) {
console.error(err);
return message.channel.send("Annulation de la commande...");
}
const videoIndex = parseInt(1);
var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
} catch (err) {
console.error(err);
return message.channel.send("🆘 **|** Je n'obtiens aucun résultat :pensive:");
}
}
return handleVideo(video, message, voiceChannel);
}
}
async function handleVideo(video, message, voiceChannel, playlist = false) {
const serverQueue = queue.get(message.guild.id);
const song = {
id: video.id,
title: Util.escapeMarkdown(video.title),
url: `https://www.youtube.com/watch?v=${video.id}`
};
console.log(song.url)
if (!serverQueue) {
const queueConstruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
queue.set(message.guild.id, queueConstruct);
queueConstruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueConstruct.connection = connection;
play(message.guild, queueConstruct.songs[0]);
} catch (error) {
console.error(`Je ne peux pas rejoindre le salon vocal : ${error}`);
queue.delete(message.guild.id);
return message.channel.send(`Je ne peux pas rejoindre le salon vocal : **\`${error}\`**`);
}
} else {
serverQueue.songs.push(song);
if (playlist) return undefined;
else return message.channel.send(`:white_check_mark: **|** **\`${song.title}\`** a été ajouté à la playlist !`);
}
return undefined;
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
const dispatcher = serverQueue.connection.play(ytdl(song.url))
.on("end", reason => {
if (reason === "Stream is not generating quickly enough.") console.log("Musique terminée.");
else console.log(reason);
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`🎶 **|** En cours de lecture : **\`${song.title}\`**`);
};
Try replacing "end" with "finish":
const dispatcher = serverQueue.connection.play(ytdl(song.url)).on("end", reason => {
to
const dispatcher = serverQueue.connection.play(ytdl(song.url)).on("finish", reason => {
I'm coding a Discord bot using Discord.js and i'm trying to make a .clear command, to clear messages. The problem is that I can't delete the messages because i'm getting a await is only valid in async function when trying to use bulkDelete. I'm coding that in the bot.on('message', msg => { section. Here is my code:
if (msg.content.startsWith('.clear')) {
if(msg.member.hasPermission('MANAGE_MESSAGES')) {
const args = msg.content.split(' ').slice(1);
const amount = args.join(' ');
if(!amount) {
const noNumbers = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(':no_entry: Vous n\'avez pas précisé combien de messages devraient être supprimés !')
msg.channel.send(noNumbers)
}
if(isNaN(amount)) {
const notNumber = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(':no_entry: Ce paramètre n\'est pas un nombre !')
msg.channel.send(notNumber)
}
if(amount > 100) {
const tooMuch = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(':no_entry: Vous ne pouvez pas supprimer plus de 100 messages à la fois !')
msg.channel.send(tooMuch)
}
if(amount < 1) {
const tooLess = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(':no_entry: Vous ne pouvez pas supprimer moins d\'un message !')
msg.channel.send(tooLess)
}
else {
await msg.channel.messages.fetch({limit: amount}).then(messages => {
msg.channel.bulkDelete(messages)
});
}
}
}
Thanks ! (Don't mind about the embed descriptions, I'm french)
Try:
bot.on('message', async (msg) => {
// your code
}