Multistep command and message collector discord.js - discord

I'm trying to create a multistep command and after the last edit of the embed I want to collect what the user reply. I tried await message , message collector but I did not succeed.
This is the last part of the command. Thanks for your help
.then(collected => {
var date = collected.first().emoji.name
switch (date){
case '1️⃣':
message.channel.send(`:white_check_mark: Tu as choisis d'ajouter un devoir pour lundi`).then(m => m.delete({ timeout: 2000 }));
var date = 'lundi'
break;
case '2️⃣':
message.channel.send(`:white_check_mark: Tu as choisis d'ajouter un devoir pour mardi`).then(m => m.delete({ timeout: 2000 }));
var date = 'mardi'
break;
case '3️⃣':
message.channel.send(`:white_check_mark: Tu as choisis d'ajouter un devoir pour mercredi`).then(m => m.delete({ timeout: 2000 }));
var date = 'mercredi'
break;
case '4️⃣':
message.channel.send(`:white_check_mark: Tu as choisis d'ajouter un devoir pour jeudi`).then(m => m.delete({ timeout: 2000 }));
var date = 'jeudi'
break;
case '5️⃣':
message.channel.send(`:white_check_mark: Tu as choisis d'ajouter un devoir pour vendredi`).then(m => m.delete({ timeout: 2000 }));
var date = 'vendredi'
break;
}setTimeout(() => 5000)
m.reactions.removeAll()
const newEmbed = new Discord.MessageEmbed()
.setColor('RED')
.setTitle('Entrer le descriptif du devoir')
setTimeout(() => 7000)
m.edit(newEmbed)
const filter = m => m.author.id === message.author.id;
message.channel.awaitMessages(filter,{time:10000}).then(collected =>{
console.log(m)
})

The TextChannel.awaitMessages() method returns a Collection (a Map).
Since you want the output to be an array of strings, you can do something like this:
message.channel.awaitMessages(filter,{time:10000}).then(collected =>{
const list = [];
collected.forEach((message) => {
list.push(message.content);
});
console.log(list); // ["hello", "world"]
});
If you only want a single message, you can use the MessageCollectorOptions's max property and set it to 1:
message.channel.awaitMessages(filter,{time:10000, max:1}).then(collected =>{
// in case the user did not answer
if (typeof collected.first() === "undefined") {
return;
}
const string = collected.first().content;
console.log(string); // "hello"
});

Related

Random gif and icon

I made a script that, when a user updates their profile, sends their new avatar to a channel based on the image extension. It's working when the extension is .png, but when it's .gif it sends it in the same channel where it sends the .pngs. My code is below:
Versao Pt
fiz um script pra quando um usuario alterar seu avatar o bot enviar ele em um canal, ta funcionando mas quando é .png o bot envia certinho, mas qunado é .gif ele envia no canal do .png e na mesma embed.
client.on('userUpdate', (oldUser, newUser) => {
const oldAvatarURL = oldUser.displayAvatarURL({ size: 2048, dynamic: true });
const newAvatarURL = newUser.displayAvatarURL({ size: 2048, dynamic: true });
if (oldAvatarURL === newAvatarURL) return;
const avatarExtension = newAvatarURL.split('.').pop();
const canalgif = client.channels.cache.get("1076541628405272667");
const canalicon = client.channels.cache.get("1076541589062692874");
//-----------------------------// GIFS //-----------------------------//
if (avatarExtension === 'gif') {
const embedgif = new Discord.EmbedBuilder()
.setImage(newAvatarURL)
.setColor('#360d60')
.setTitle('Teste gif');
canalgif.send({ embeds: [embedgif] });
} else {
//-----------------------------// Icon //-----------------------------//
const embedicon = new Discord.EmbedBuilder()
.setImage(newAvatarURL)
.setColor('#360d60')
.setTitle('teste icon');
canalicon.send({ embeds: [embedicon] });
}
});
you just need to remove the size parameter of both oldAvatarURL and newAvatarURL variable.
Indeed, with your code, a gif will be shown as gif?size=4096...
If you use .displayAvatarURL() with the size option, the URL returned will append a query string at the end. It means the avatar won't end with .gif, .png, .webp etc but with .webp?size=2048.
The way you're currently getting the extension of the URL won't work as you just split that by a . and check the last part.
// ⛔️ won't work
let url = `https://cdn.discordapp.com/avatars/827997777303699467/55b85c4fe590a54c53183990b030f128.webp?size=2048`
let extension = url.split('.').pop();
console.assert(extension === 'webp', `extension is not "webp", but "${extension}"`);
Instead of removing the size option where you end up with the default size of 128px, you could update the way you grab the extension. First, you could split by that . you already tried, then you could split again by ?:
// ✅ works as expected
let url1 = `https://cdn.discordapp.com/avatars/827997777303699467/55b85c4fe590a54c53183990b030f128.webp?size=2048`;
let url2 = `https://cdn.discordapp.com/avatars/827997777303699467/55b85c4fe590a54c53183990b030f128.png`;
let extension1 = url1.split('.').pop().split('?')[0];
let extension2 = url2.split('.').pop().split('?')[0];
console.log(extension1);
console.log(extension2);
So, the following should work as expected:
client.on('userUpdate', (oldUser, newUser) => {
const options = { size: 2048, dynamic: true };
const oldAvatarURL = oldUser.displayAvatarURL(options);
const newAvatarURL = newUser.displayAvatarURL(options);
if (oldAvatarURL === newAvatarURL) return;
const avatarExtension = newAvatarURL.split('.').pop().split('?')[0];
const embed = new Discord.EmbedBuilder()
.setImage(newAvatarURL)
.setColor('#360d60');
if (avatarExtension === 'gif') {
const canalGif = client.channels.cache.get('1076541628405272667');
canalGif.send({ embeds: [embed.setTitle('Teste gif')] });
} else {
const canalIcon = client.channels.cache.get('1076541589062692874');
canalIcon.send({ embeds: [embed.setTitle('Teste icon')] });
}
});

How to fetch mongoDB data in multiples nested array with conditions?

i'm struggling with mongoDB API, This is my representation of my data :
I'd like to get one list that is stored in userlists correpsonding to his title
Basicaly, i want to fetch only one data that corresponds to a userID and a listTitle
This is my current request and this is not working
exports.getOneMoviesListOfUser = (req, res) => {
const uid = req.params.uid;
const titrelist = req.params.titrelist;
if(uid && titrelist) {
var condition = {"uid": {$regex : new RegExp(uid), $options: "i"}, "userlists.titrelist": {$regex : new RegExp(titrelist), $options: "i"}}
} else {
var condition = {}
}
MoviesDB.find(condition)
.then((data) => {
if (!data)
res
.status(404)
.send({
message:
"Liste de films non trouvée " + uid + "liste = " + titrelist,
});
else res.send(data);
})
.catch((err) => {
res
.status(500)
.send({
message:
"Erreur pendant la récupération de la liste " +
uid +
"liste = " +
titrelist,
});
});
};
Ty if you can help me with this.

Change avatar size Discord.js

I want to change the size of the profile photo when the photo is a gif, how can I do it?
I have tried user.displayAvatarURL ({size: 2048, dynamic: true}); but the bot crashes D:
the error is the following:: (node:15836) UnhandledPromiseRejectionWarning: TypeError: user.displayAvatarURL is not a function
module.exports = {
nombre: "avatar",
alias: ["foto"],
descripcion: "Este comando muestra la foto de perfil de un usuario",
run: (client, message, args) => {
const user = message.mentions.users.first() || message.author;
const avatarEmbed = new Discord.RichEmbed()
avatarEmbed.setColor(0x333333)
avatarEmbed.setAuthor(user.username)
avatarEmbed.setImage(user.displayAvatarURL);
message.channel.send(avatarEmbed);
}
}
I have found a way to fix the crash, I attach code :D
const user = message.mentions.users.first() || message.author;
if(user.displayAvatarURL.endsWith(".gif")){
const avatarEmbed = new Discord.RichEmbed()
avatarEmbed.setColor(0x333333)
avatarEmbed.setAuthor(user.username)
avatarEmbed.setImage(user.displayAvatarURL + "?size=1024");
message.channel.send(avatarEmbed);
} else {
const avatarEmbed = new Discord.RichEmbed()
avatarEmbed.setColor(0x333333)
avatarEmbed.setAuthor(user.username)
avatarEmbed.setImage(user.displayAvatarURL);
message.channel.send(avatarEmbed);
}

Discord.js - Give role a all channel

Hello I would like to create an order (! Giverole) so that it gives the roles (mute) to all the channels of the server or to be made the order.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
var mute_role = message.guild.roles.find(r => r.name == 'mute', {READ_MESSAGES: true, SEND_MESSAGES: false})
if (!mute_role) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.overwritePermissions(channel => channel.addRole(mute_role));
var lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
thank you in advance
At the fist - try always get role with role ID, its more safely.
If I understand your question correctly and you need a certain role on all channels to establish certain rights. So you can use this code.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
let muteRole = message.guild.roles.get('ROLEID')
if (!muteRole) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.map(channel => {
if(channel.type === 'text') {
channel.overwritePermissions(muteRole, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
})
.then(console.log)
.catch(console.log);
}
})
let lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
}
})
```

Cannot read the property 'roles' of undefined

I'm making a bot and I have an error that I don't understand in this code : pas
const Discord = require("discord.js");
const client = new Discord.Client();
const token = "";
client.login(token)
client.on("message", async(message) => {
let staffRole = message.guild.roles.find("name", "Staff");
let staff = message.guild.member(message.author);
if (message.author.id === "424974772959444993" || message.member.roles.has(staffRole.id)) {
return;
}
var badWords = [
'asd',
'legionmods',
'verga',
'vrga',
'nmms',
'alv',
'electromods',
'remake'
];
var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
var containsBadWord = words.some(word => {
return badWords.includes(word);
});
if (containsBadWord) {
message.delete();
message.author.send({embed: {
color: 3447003,
description: `Has dicho una palabra que no esta permitida en este servidor`
}
message.channel.send(`${prefix}tempmute ${message.author}`+" 5m palabra prohibida")
}
});
This is an error I get :
(node:4952) UnhandledPromiseRejectionWarning: TypeError: Cannot read property
'roles' of null
at Client.client.on (C:\Users\Francisco\Desktop\role\app.js:8:33)
Could someone help me please ? I am not good in debugging errors.
message.guild is probably returning null because the message was sent in a dm conversation, not a guild.
You can avoid this problem by writing:
if (message.channel.type !== 'text') return;
Also, a few GuildMemberRoleManager methods have changed a bit since discord.js v12+. You should replace:
let staffRole = message.guild.roles.find("name", "Staff");
With:
let staffRole = message.guild.roles.cache.find(role => role.name === "Staff");
And replace:
message.member.roles.has(staffRole.id)
With:
message.member.roles.cache.has(staffRole.id)

Resources