Change avatar size Discord.js - 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);
}

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

discord.js canvas image manipulation

I wan't to make a command that put the user avatar in my wanted image
const { createCanvas, loadImage } = require('canvas')
const { MessageAttachment } = require('discord.js');
const Command = require('../../structures/Command')
module.exports = class extends Command {
constructor(client) {
super(client, {
name: 'wanted',
description: 'Coloca a cabeça de um usuário valendo $2000.',
options: [
{
name: 'user',
description: 'Usuário que terá a cabeça posta num cartaz de procurado',
type: 'USER',
required: true
}
]
})
}
run = async (interaction) => {
const canvas = createCanvas(239, 338)
const ctx = canvas.getContext('2d')
const wantedImg = await loadImage("imgs/wanted.png")
const userAv = interaction.options.getUser('user')
const Avatar = userAv.avatarURL()
interaction.reply(wantedImg)
}
}
I put the wantedImg in interaction.reply to see if the client return in chat the wanted image, but it's getting error...
Cannot find module
'C:\Users\pulse\OneDrive\Documentos\Cynthia\JS\src\commands\imgs\imgs'
I would recommend using jimp instead:
const user = message.mentions.users.first() //get The first user mentioned
if (!user) return message.reply("Who is wanted?")//return if no user was mentioned
var wantedImage = "wanted image url goes here"
var pfp = user.avatarURL({ format: 'png', dynamic: true, size: 128 }) //Get link of profile picture
var image = await Jimp.read(pfp)//read the profile picture, returns a Jimp object
//Composite resized bars on profile picture
image.composite((await Jimp.read(bars)).resize(128, 128), 0, 0)
//Create and attachment using buffer from edited picture and sending it
var image = new Discord.MessageAttachment(await image.getBufferAsync(Jimp.MIME_PNG))
message.reply(image) //replies to original command with image
It has far more options than canvas.
Make sure your path is correct, it seems that the path won't get resolved correctly. To be sure about your paths, consider using.
const {join} = require("path");
const wantedImg = loadImage(join(__dirname, "imgs/wanted.png"));

Multistep command and message collector discord.js

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"
});

TypeError: Cannot read property 'roles' of undefined at Object.module.exports.run

I am trying to make a tempmute command which saves data to JSON then reads it every 3 seconds to see is the time experied. I made the mute command but I recive an error TypeError: Cannot read property 'roles' of undefined. I delete the if(!message.member.roles.has("675376537272582154")) return message.channel.send('Bu komutu kullanabilmek için「🔪」Mute Premission rolüne sahip olmasınız.') but this time it said TypeError: Cannot read property 'members' of undefined. Can someone help me?
Information
Discord.js Version: v11.6.1
Node.js Version: 12.0.0
Code
const { RichEmbed } = require('discord.js');
const fs = require('fs');
module.exports.run = async (message, args, bot) => {
if(!message.member.roles.has("675376537272582154")) return message.channel.send(`Bu komutu kullanabilmek için \`「🔪」Mute Premission\` rolüne sahip olmasınız.`);
let toMute = message.mentions.member.first() || message.guild.members.get(args[0])
if(!toMute) return message.channel.send(`:x: Susturulacak kullanıcıyı etiketlemelisin!`)
let timeMute = args[1]
if(!timeMute) return message.channel.send(':x: Susturma süresini dakika cinsinden yazmalısın!')
if(isNaN(args[1])) return message.channel.send(':x: Senin de bildiğin gibi süre sadece sayı olabilir!')
let reason = args.slice(2).join(" ")
if(!reason) return message.channel.send(':x: Susturma sebebini yazmalısın!')
if(toMute.id === message.author.id) return message.channel.send(`:x: Kendini susturamazsın bea!`)
if(toMute.roles.has('675376537272582154')) return message.channel.send(`:x: \`「🔪」Mute Premission\` rolüne sahip olan birini susturamazsın!`)
let role = message.guild.roles.find(x => x.name === '「🔇」Muted')
if(!role) return message.channel.send(':x: `「🔇」Muted` adlı rolü bulamıyorum!')
if(toMute.roles.has(role.id)) return message.channel.send(':x: Bu kullanıcı zaten susturulmuş!')
let modlog = message.guild.channels.find(c => c.name === '『🔰』punishment')
if(!modlog) return message.channel.send(':x: Mod-Log kanalını bulamıyorum!')
const embed = new RichEmbed()
.setTitle('Susturma')
//.setThumbnail(`${toMute.avatarURL}`)
.setDescription(`**Susturlan Kişi: \`${toMute.tag}\`** \n **ID Numarası: \`${toMute.id}\`**\n **Susturan Yetkili: \`${message.author.tag}\`**\n **Süre: \`${timeMute}\`** **Sebep: \`${reason}\`** `)
.setColor("#ff0000")
.setFooter('Kurallara Uymayanın Sonu')
.setTimestamp();
bot.mutes[toMute.id] = {
guild: message.guild.id,
time: Date.now() + parseInt(args[1]) * 10000
}
await toMute.addRole(role)
fs.writeFile("./mutes.json", JSON.stringify(bot.mutes, null, 4), err => {
if(err) throw err;
modlog.send(embed)
})
}
module.exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['sustur'],
permLevel: 0
};
module.exports.help = {
name: 'mute',
description: 'Sustur gitsin',
usage: '!sustur #kullanıcı süre sebep'
}
member and guild are most likely undefined because your bot is receiving a DM message. Check if the message is from a guild before continuing with your code:
module.exports.run = async (message, args, bot) => {
if(!message.guild) return
// rest of code
}

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