Javascript then error (await messages) discord - javascript

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'
};

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

Cannot read properties of undefined (reading 'permissions'). | Discord.js v13

I'm making a command called role info in slash command!
And came the error called: Cannot read properties of undefined (reading 'permissions').
const { MessageEmbed, MessageActionRow, MessageButton } = require("discord.js");
const moment = require("moment");
moment.locale("pt-BR");
module.exports = {
name: "role",
description: "「🙋│ Utilidades」 Obtenha informações de um cargo",
options: [
{
name: 'info',
description: "「🙋│ Utilidades」 Obtenha informações de um cargo",
type: "SUB_COMMAND",
options: [
{
name: "role",
type: "ROLE",
description: "O cargo que você deseja obter as informações!",
required: true,
}]
},
],
run: async (client, interaction, args) => {
const role = interaction.guild.roles.cache.get(args[0]);
const permissions = {
"ADMINISTRATOR": "Administrador",
"VIEW_AUDIT_LOG": "Ver Registro de Auditoria",
"VIEW_GUILD_INSIGHTS": "Exibir insights do servidor",
"MANAGE_GUILD": "Gerenciar Servidor",
"MANAGE_ROLES": "Gerenciar Cargos",
"MANAGE_CHANNELS": "Gerenciar Canais",
"KICK_MEMBERS": "Expulsar Membros",
"BAN_MEMBERS": "Banir Membros",
"CREATE_INSTANT_INVITE": "Criar convite",
"CHANGE_NICKNAME": "Mudar apelido",
"MANAGE_NICKNAMES": "Gerenciar apelidos",
"MANAGE_EMOJIS": "Gerenciar Emojis",
"MANAGE_WEBHOOKS": "Gerenciar webhooks",
"VIEW_CHANNEL": "Ler canais de texto e ver canais de voz",
"SEND_MESSAGES": "Enviar mensagens",
"SEND_TTS_MESSAGES": "Enviar mensagens TTS",
"MANAGE_MESSAGES": "Gerenciar mensagens",
"EMBED_LINKS": "Embed Links",
"ATTACH_FILES": "Anexar arquivos",
"READ_MESSAGE_HISTORY": "Leia o histórico da mensagem",
"MENTION_EVERYONE": "Mencione #everyone, #here e Todos os cargos",
"USE_EXTERNAL_EMOJIS": "Usar Emojis Externos",
"ADD_REACTIONS": "Adicionar Reações",
"CONNECT": "Conectar",
"SPEAK": "Falar",
"STREAM": "Video",
"MUTE_MEMBERS": "Mutar Membros",
"DEAFEN_MEMBERS": "Ensurdecer membros",
"MOVE_MEMBERS": "Mover membros",
"USE_VAD": "Usar atividade de voz",
"PRIORITY_SPEAKER": "Orador prioritário"
}
const yesno = {
true: '`Sim`',
false: '`Não`'
}
const rolePermissions = role.permissions.toArray();
const finalPermissions = [];
for (const permission in permissions) {
if (rolePermissions.includes(permission)) finalPermissions.push(`${client.emoji.success} ${permissions[permission]}`);
else finalPermissions.push(`${client.emoji.fail} ${permissions[permission]}`);
}
const position = `\`${interaction.guild.roles.cache.size - role.position}°\``;
const embed = new MessageEmbed()
.setTitle(`${role.name}`)
.addField(`${client.emoji.id} ID`, `\`${role.id}\``, true)
.addField(`${client.emoji.trophy} Posição`, `${position}`, true)
.addField(`${client.emoji.ping} Mencionável`, yesno[role.mentionable], true)
.addField(`${client.emoji.bot} Cargo de bot`, yesno[role.managed], true)
.addField(`${client.emoji.on} Visível`, yesno[role.hoist], true)
.addField(`${client.emoji.rcolor} Cor`, `\`${role.hexColor.toUpperCase()}\``, true)
.addField(`${client.emoji.calendar} Data de criação`, `${moment(role.createdAt).format('LLL')}(${moment(role.createdAt).startOf('day').fromNow()})`, true)
.setColor(`${role.hexColor.toUpperCase()}`)
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setLabel(`Permissões`)
.setEmoji(`${client.emoji.perms}`)
.setCustomId('perms') .setStyle('SECONDARY')
);
const m = await interaction.followUp({ embeds: [embed], components: [row] })
const iFilter = i => i.user.id === interaction.user.id;
const collector = m.createMessageComponentCollector({ filter: iFilter, time: 10 * 60000 });
collector.on('collect', async(i) => {
switch (i.customId) { //começo da mensagem
case `perms`:
i.reply({
embeds: [
new MessageEmbed()
.setTitle(`${client.emoji.perms} Permissões`)
.setDescription(`${finalPermissions.join('\n')}
`)
.setColor(`${role.hexColor.toUpperCase()}`)
],
ephemeral: true })
}
}) //Final da mensagem
}
}
Since before, the command was working, but I changed it to the second bot and then it gave the error!
If anyone knows, tell me the error, I would be very grateful!
TypeError: Cannot read properties of undefine
d (reading 'permissions')
at Object.run (/home/runner//Slash/Info/roleinfo.js:66:38)
at Client. (/home/runner//events/interactionCreate:24:13
InteractionCreate.js
const client = require("../index");
client.on("interactionCreate", async (interaction) => {
// Slash Command Handling
if (interaction.isCommand()) {
await interaction.deferReply({ ephemeral: false }).catch(() => {});
const cmd = client.slash.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "An error has occured " });
const args = [];
for (let option of interaction.options.data) {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
cmd.run(client, interaction, args);
}
// Context Menu Handling
if (interaction.isContextMenu()) {
// await interaction.deferReply({ ephemeral: true });
const command = client.slash.get(interaction.commandName);
if (command) command.run(client, interaction);
}
});
You aren't passing in the args parameter in your function execution. You can remove args and use <CommandInteraction>.options.getRole() to get the role argument. Now keeping that in mind we can go ahead and define role as that.
const role = interaction.options.getRole("role");

I can not launch my js Discord bot, error message

So I tried to follow a tutorial to make my own music discord bot but when I try to launch it I got some problems
I correctly installed the modules, and I've also made a json file that contain my token to make the bot,
There is the command prompt
and there is my code
const Discord = require('discord.js');
const client = new Discord.Client();
const DisTube = require('distube');
const distube = new DisTube(client, { searchSongs: false, emitNewSongs: true });
const { token } = require('./info.json');
const prefix = '!';
client.on("ready", () => {
console.log('${client.user.tag} va venir faire mousser tout ça!');
});
client.on("message", async(message) => {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift();
const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;
distube
.on("playSong", (message, queue, song) => message.channel.send(
`Joue :musical_note: et nique Brian \`${song.name}\` - \`${song.formattedDuration}\`\nDemandé par: ${song.user}\n${status(queue)}`
))
.on("addSong", (message, queue, song) => message.channel.send(
`Ajoutée! ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`
))
.on("playList", (message, queue, playlist, song) => message.channel.send(
`Joue :musical_note: \`${playlist.name}\` playlist (${playlist.songs.length} songs).\nDemandé par: ${song.user}\nJoue mtn \`${song.name}\` - \`${song.formattedDuration}\`\n${status(queue)}`
))
.on("addList", (message, queue, playlist) => message.channel.send(
`Ajouté \`${playlist.name}\` playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
))
.on("searchResult", (message, result) => {
let i = 0;
message.channel.send(`**Choisi en dessous**\n${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n*Tu as 60s pour choisir*`);
})
.on("searchCancel", (message) => message.channel.send(`Annulé batard`))
.on("error", (message, e) => {
console.error(e)
message.channel.send("Call Souf ça bug: " + e);
});
if (command =="play") {
if (!message.member.voice.channel) return message.channel.send('Tu ne peux pas entendre la douce mélodie.');
if (!args[0]) return message.channel.send('Décide toi frère!');
distube.play(message, args.join(" "));
}
if (command =="stop") {
const bot = message.guild.members.cache.get(client.user.id);
if (!message.member.voice.channel) return message.channel.send('Tu ne peux pas entendre la douce mélodie.');
if (bot.voice.channel !== message.member.voice.channel) return message.channel.send('Tu est pas dans le même channel que moi');
distube.stop(message);
message.channel.send('Tu as arreté la musique');
}
});
client.login(token);
In discord.js v13 all bots are required to define their intents in the Client constructor.
Example:
change your
const Discord = require('discord.js');
const client = new Discord.Client();
to
const {Client, Intents} = require('discord.js');
const client = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]});
You would obviously change the intents to what your bot would use.
More info can be found here

i'm trying to put a manipulated image to welcome people on my dicrod bo using jimp

I'm using this but it's not working. I don't know why please help me.
const Discord = require("discord.js");
const jimp = require("jimp");
const client = new Discord.Client();
const config = require("./config.json");
client.on("ready", () => {
console.log(`Bot foi iniciado`)
});
client.on("guildMemberAdd", async member => {
let canal = client.channels.get("750795877089804309")
let fonte = await jimp.loadFont(jimp.FONT_SANS_32_BLACK)
let mask = await jimp.read('mascara.png')
let fundo = await jimp.read('fundo.png')
jimp.read(member.user.defaultAvatarURL).then(avatar => {
avatar.resize(400, 400)
mask.resize(400, 400)
fundo.resize(270, 190)
avatar.mask(mask)
fundo.print(fonte, 05, 120, member.user.username)
avatar.composite(fundo, 80, 170).write('resultado.png')
canal.send(``, {
files: ["resultado.png"]
})
console.log('imagem enviada')
})
.catch(err => {
console.log('Deu erro aqui porra')
});
});
client.on("message", async message => {
if (message.author.bot) return;
if (message.channel.type === "dm") return;
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const comando = args.shift().toLowerCase();
if (comando === "ping") {
const m = await message.channel.send("Sifude");
m.edit(`A Latência é ${m.createdTimestamp - message.createdTimestamp}ms. A Latencia da API é ${Math.round(client.ping)}ms`);
}
});
client.login(config.token);
You need to use:
let canal = client.channels.cache.get("750795877089804309")
As client.channels return a ChannelManager object and not a collection.

Discord.js music bot with queue doesn't work

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 => {

Categories

Resources