Get channel ID after cloning DiscordJS - javascript

I'm working on a DiscordJS bot, and I want to move my user to the a channel I cloned. For this I need to get the ID of the channel, and I don't know how to do that.
bot.on("voiceStateUpdate", (oldMember, newMember) => {
let newUserChannelID = newMember.voiceChannelID
let newUserName = newMember.username
let channel = bot.channels.get("626043862397354025")
if(newUserChannelID == "534437314231926804") {
channel.clone('Salon privé de ' + newUserName, true, false, 'Création channel privé.')
.then(clone => console.log(`Clone du channel ${channel.name} pour faire un nouveau channel nommé ${clone.name}`))
.catch(console.error);
let newPrivateChannel = clone.voiceChannelID
newMember.setVoiceChannel(newPrivateChannel)
}
});
The clone method is returning a GuildChannel object.
Do you have an idea ?

more like this:
if(newUserChannelID == "534437314231926804") {
channel.clone('Salon privé de ' + newUserName, true, false, 'Création channel privé.')
.then(clone => {
console.log(`Clone du channel ${channel.name} pour faire un nouveau channel nommé ${clone.name}`)
// clone is available
let newPrivateChannel = clone.voiceChannelID
newMember.setVoiceChannel(newPrivateChannel)
})
.catch(console.error);
}

Related

Discord Reaction Role doesn't attribute roles

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

Nickname all members in a discord server

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}\``)
}

I'm having trouble making a discord bot that plays music

The bot successfully connects to the voice channel, but does not play the song from the URL I typed, the code is:
if(message.content.startsWith(prefix + "join"))
{
message.channel.send("Entrando a " + message.member.voiceChannel);
if (message.member.voiceChannel)
{
const permissions = message.member.voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT'))
{
return message.channel.send('No me puedo conectar a ese canal')
}
if (!permissions.has('SPEAK')) {
return message.channel.send('No puedo hablar en ese canal')
}
let connection = await message.member.voiceChannel.join();
let dispatcher = connection.playStream(ytdl('https://www.youtube.com/watch?v=PLRrL9OsAF8&t=18s'))
.on('start', () => {
message.reply('Empieza la musica');
})
.on('end', () => {
message.reply('Termino la musica');
message.member.voiceChannel.leave();
})
.on('error', error => {
message.reply('Error al intentar reproducir la cancion');
});
dispatcher.setVolumeLogarithmic(5 / 5);
}
else
{
message.reply('Tenes que estar dentro de un chat de voz');
}
}
Can anyone identify a potential cause for this?
From what i can tell you are using Discord.js V11 which isn't the recomennded version(V12)
From the docs though it seems that maybe you have to pass a optional argument to ytdl
// Play streams using ytdl-core
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1 };
voiceChannel.join()
.then(connection => {
const stream = ytdl('https://www.youtube.com/watch?v=XAWgeLF9EVQ', { filter : 'audioonly' });
const dispatcher = connection.playStream(stream, streamOptions);
})
.catch(console.error);
If that doesn't work Discord.js's Support server can be found here. They officially moved to V12 in march but they might still help you

Javascript then error (await messages) discord

I want to create a command that create an announcement which is carried out in several stages. First, I type *annonce channelID then the bot asks me for the title, then the message (in theory)
Unfortunately, once *annonce channelID typed, the bot does not continue and writes this (it does the .catch)
Can you help me ?
Bot react :
Entre le titre de ton annonce :
title error
msg error
react error
const Discord = require('discord.js');
const delay = require('delay');
const NO = '❌';
const YES = '✅';
module.exports.run = async(bot, message, args) => {
const userN = message.member;
const msgFilter = m => m.author.id === message.author.id;
const userDepotAnnonce = message.author.username;
if(!message.member.hasPermission('ADMINISTRATOR')) {return message.channel.send("Vous ne pouvez pas passer d'annonces !");}
const channelID = args[0];
let sendchannel = bot.channels.get(channelID);
if(message.content !== `*annonce ${channelID}`) {return message.channel.send('Utilise ***annonce ``channelID``** puis valide');}
message.channel.send("Entre le titre de ton annonce :");
await delay(100);
message.channel.awaitMessages(msgFilter, { max: 1, time: 15000, errors: ['time'] })
.then(titleCollected => {
const msgTitle = titleCollected.first().content;
message.channel.send("Entrez le contenu de l'annonce et joint ton fichier :");
})
.catch(titleCollected => {
message.channel.send('*title error*');
console.log('Pas de titre');
})
message.channel.awaitMessages(msgFilter, { max: 1, time: 30000, errors: ['time'] })
.then(msgCollected => {
const messageToSend = msgCollected.first().content;
if(message.attachments.size > 0){
let attachment = message.attachments.first()
const url = attachment.url
var annonceFinal = new Discord.RichEmbed()
.setColor("03CD43")
.setTitle(`Nouvelle annonce : **${msgTitle}**`)
.setAuthor(userDepotAnnonce, message.author.avatarURL, url)
.addField('Annonce', messageToSend)
.addField('Lien', url)
.setFooter("Annonces by PDC")
}
else{
var annonceFinal = new Discord.RichEmbed()
.setColor("03CD43")
.setTitle(`Nouvelle annonce : **${msgTitle}**`)
.setAuthor(userDepotAnnonce, message.author.avatarURL)
.addField('Annonce', messageToSend)
.setFooter("annonces by pdc")
}
message.channel.send(`Vous vous désirez passer l'annonce **${msgTitle}** contenant **${messageToSend}** dans ${sendchannel}.\nPour confirmer, utilisez les reactions.` +YES +NO);
})
.catch(msgCollected => {
message.channel.send('*msg error*');
console.log('Pas de message');
})
const filter = (reaction, user) => {return ['✅', '❌'].includes(reaction.emoji.name) && user.id === message.author.id;};
message.react('✅').then(() => message.react('❌'));
message.awaitReactions(filter, { max: 1, time: 10000, errors: ['time'] })
.then(collected => {
const reaction = collected.first();
if (reaction.emoji.name === '✅'){
sendchannel.send(annonceFinal)
}
else if (reaction.emoji.name === '❌'){
message.channel.send('Alors arrête de me faire chier !');
}
})
.catch(collected => {
message.channel.send('*react error*');
console.log('*react error*');
})
};
module.exports.help = {
name: 'annonce'
};

Await is only valid in async function for bulkDelete

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
}

Categories

Resources