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
}
Related
I'm trying to create a Discord Reaction Role and I would like to assign a role when a user clicks on the message emoji in the channel. Here is my code, it doesn't work from messageReactionAdd :
const Discord = require('discord.js');
const client = new Discord.Client();
const { token } = require('./config.json');
client.on("ready", () => {
console.log("Bot opérationnel");
});
// Permet d'ajouter une réaction à un message
client.on('messageCreate', message => {
if (message.content === '!roles') {
const reactionEmoji = message.guild.emojis.cache.find(emoji => emoji.name === 'FR');
message.react(reactionEmoji);
// console.log(reactionEmoji)
}
});
client.on("messageReactionAdd", (reaction, user) => {
if (user.bot) return;
console.log("Réaction ajoutée");
if (reaction.message.id === "1036663050276704346") { //ID du message
console.log(reaction.message.id);
if (reaction.emoji.name === message.guild.emojis.cache.find(emoji => emoji.name === 'FR')) {
var member = reaction.message.guild.members.cache.find(member => member.id === user.id); // Va récuperer le membre du serveur
member.roles.add("1036583426620399647").then(mbr => { // Assigne le role avec ID France
console.log("Role attribué avec succès pour" + mbr.displayName);
}).catch(err => {
console.log("Le role n'a pas pu etre attribué :" + err);
});
}
}
});
client.login(token);
Thank you in advance.
Activate the SERVER MEMBERS INTENT and the MESSAGE CONTENT INTENT from the Discord Developer Portal
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'm trying to make a script that can nickname all the people on a discord server I would like it to rename all the members and not only the active ones for the moment I have this
module.exports.run = async (client, msg, args, config) => {
msg.delete();
const guild = client.guilds.get("888868333498290176");
if(!msg.guild.me.hasPermission("MANAGE_NICKNAMES")) return console.log('Cette commande a besoin de permissions')
await msg.guild.members.cache;
let members = msg.guild.id
if (args.join(" ").length > 32) return msg.reply('Le nom ne peut pas dépasser 32 caractères.')
console.log('Modifier le surnom de ' + members.length + ' member(s), attendez un moment.')
for(let i = 0; i < members.length; i++) {
await members[i].setNickname(args.join(" "))
}
console.log(' [+] Le surnom de tout le monde sur le serveur a été changé !'.green)
}
and this error
C:\Users\PC\Desktop\discord\1140\commands\nickall.js:12
await members[i].setNickname(args.join(" "))
^
TypeError: members[i].setNickname is not a function
You can use forEach() and change nicknames for all members in the guild. Example:
try {
message.guild.members.forEach((member) => {
member.setNickname("nickname")
})
} catch (error) {
console.error(error)
return message.channel.send(`Error changing nicknames: \`${error}\``)
}
So I wanted to code a command on my bot. And I added reaction but I want that when the user who did the command, click on a certain reaction so it can display a different message. But what I did doesn't work so I please help me because I need this to be done.
Here is the code:
const Discord = require('discord.js')
module.exports = {
run: (message, reaction, user) => {
message.channel.send(new Discord.MessageEmbed()
.setTitle("**COMBAT**")
.setDescription("*Choisissez votre mode de combat*")
.setColor('#CD5C5C')
.addField("🗡️", ' `est pour le mode de combat avec une arme non magique` ')
.addField("🪄", ' `est pour un mode de combat utilisant la magie` '))
},
name: "fight",
setDescription: "Cette commande sert à executer un combat"
}
and here is the command handler that I wrote down for the code :
client.on('messageReactionAdd', (reaction, user) => {
if (message.content === "~fight"){
message.react'🗡️'),
message.react('🪄')
if (reaction.emoji.name === '🗡️') {
message.reply('nice')
}
else {
message.reply('cool')
}
}
})
it's not showing me any error but it's not working
and this is my command handler
client.commands = new Discord.Collection()
console.log("Bot en ligne")
fs.readdir('./commands', (err, files) => {
if (err) throw err
files.forEach(file => {
if (!file.endsWith('.js')) return
const command = require(`./commands/${file}`)
client.commands.set(command.name, command)
})
})
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 => {