I've been trying to make my bot's embed color update dynamically (using random color, editing HSV value). However, using msg.embeds[0] seems to give me the previous shown embed.
Here's a snippet of my code:
collector.on('end', () => {
currentEmbed = msg.embeds[0]
const rowAgain = msg.components[0]
for (c of rowAgain.components) {
c.disabled = true;
}
let colorHex = `#${vb2Hex(currentEmbed.color)}`;
const colorHsv = hex.hsv(colorHex);
const val = colorHsv[2] - 5;
colorHsv.splice(2, 1, val);
colorHex = hsv.hex(colorHsv);
color = parseInt(colorHex, 16);
currentEmbed.color = color;
msg.edit({ embeds: [currentEmbed], components: [row] });
});
I'm using the color-convert library and this script (minus the substr()) to edit the colors. I'm still new-ish to bots, so I might've missed something. How can I fix/improve it? I'll gladly share more info if needed.
I fixed it, had to put msg = in front of msg.edit() during an interaction to keep it up to date.
await i.deferUpdate();
await wait(0);
msg = await msg.edit({ embeds: [newEmbed], components: [row] });
Related
I'm new to working with discord bot and decided to try it out, to start I just wanted to make the bot send an attachment (image, video, etc) when for example, "sendpicture" is written in chat.
I've changed the code several times yet I get the same error everytime, "Attachment is not a constructor" or "Discord.Attachment is not a constructor".
My current code looks like this:
const client = new Discord.Client();
client.once(`ready`, () => {
console.log("online");
});
const PREFIX = "!"
//replying with a text message
client.on('message', msg => {
if (msg.content === 'test1') {
msg.channel.send('working');
}
});
//replying with attachment
client.on("message", function(message){
let args = message.content.substring(PREFIX.lenght).split(" ");
switch(args[0]) {
case "test2":
message.channel.send(new Discord.Attachment(`.a/this/bestpic.png`, `bestpic.png`) )
.then(msg => {
//aaaaaaaa
})
.catch(console.error);
break;
}
})
tyia
Had you tried looking at the official documentation ?
I don't think you should use new Discord.Attachment(), try this instead :
switch(args[0]) {
case "test2":
message.channel.send({
files: [{
attachment: '.a/this/bestpic.png',
name: 'bestpic.png'
}]
}).then(msg => {
//aaaaaaaa
}).catch(console.error);
break;
}
Discord.Attachment() is not a thing, i believe the answer you are looking for is this :)
new Discord.MessageAttachment()
Try this code, short and simple to use.
if (message.content.toLowerCase() === 'word') { //only word, without prefix
message.channel.send({ files: ['./path_to_your_file'] })
}
You should try using MessageAttachment because Discord.Attachment is not a thing, then add the attachment into the files property
I would consider making the attachment a variable instead of putting it directly into the function, it is optional tho
const { MessageAttachment } = require("discord.js");
const attachment = new MessageAttachment("url", "fileName(optional)", data(optional));
message.channel.send({ files: [attachment] }).then(//code...)
Let me know if it works
is there any way to put the user who created the channel in .setAuthor? I searched in https://discord.js.org/#/docs/main/stable/class/GuildChannel but found nothing
client.on("channelCreate", function(channel) {
const logchannel = channel.guild.channels.cache.find(ch => ch.name === "logchannel")
if (!logchannel) return
const embed = new Discord.MessageEmbed()
.setTitle("Channel created)
.setDescription(`Channel <#${channel.id}> has created.`)
.setTimestamp()
.setAuthor(//user who created the channel)
logchannel.send(embed)
})
I think it's best to use the AuditLogs, you may want to take a look at it.
I'm working on semi-gacha bot command where you can pull characters and so on. I want to display the characters image after the user pulls and here is where I get stuck, it just doesn't display anything and I found what looked like the answer on here, but it didn't help, as I would get the same result and I don't get any errors, so I don't know what exactly is wrong. I have tried printing out the result of MessageAttachment first:
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
console.log(attachment);
and I get: undefined, anybody has any ideas of what am I doing wrong? And yes, I have discord.js library imported.
Relevant part of the code:
collector.on('collect', reaction => {
//new embd
const newEmbd = new Discord.MessageEmbed();
// gacha logic
if (reaction.emoji.name === '✅') {
const values = Object.values(chars);
const randomChar = values[parseInt(Math.floor(Math.random()*values.length))];
const attachment = new Discord.MessageAttachment('./chars/1.Jakku.png', '1.Jakku.png');
const charData = randomChar.split('.');
newEmbd
.setTitle(`You pulled: ${charData[1]}!`)
.setColor('YELLOW')
.attachFiles(attachment)
.setImage(`attachment://1.Jakku.png`);
embdReact.edit(newEmbd);
pulled = true;
} else if (reaction.emoji.name === '❌') {
newEmbd
.setTitle('Time for gacha!')
.setColor('YELLOW')
.addFields(
{ name: 'Result:', value: 'You decided against pulling' }
);
embdReact.edit(newEmbd);
};
});
You need to use the correct syntax for attaching files as per this guide
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('Some title')
.attachFiles(['./chars/1.Jakku.png'])
message.channel.send(exampleEmbed);
Making a command to take a random photo of a waifu in this case, and posting it in the channel
Code here:
if (command === 'waifu') {
const waifu = new Discord.MessageEmbed()
got('https://waifu.pics/api/sfw/waifu').then(response => {
let content = JSON.parse(response.body);
let waifuUrl = content[0].data.children[0].data.url;
let waifuImage = content[0].data.children[0].data.url;
waifu.setImage(`${waifuImage}`)
waifu.setURL(`${waifuUrl}`)
waifu.setColor('#ffb9f4')
waifu.setFooter(`Requested by ${message.author.user}`)
waifu.setTimestamp()
waifu.setAuthor(`waifu.pics`, `https://waifu.pics/`)
message.channel.send(waifu)
});
};
The API should be correct. After a few small changes, I tried console logging the JSON and it did output the correct thing. But when running the code in discord, it outputted a TypeError: Cannot read property 'data' of undefined error. I cannot seem to figure out the problem
if (command === 'waifu') {
const waifu = new Discord.MessageEmbed()
get('https://waifu.pics/api/sfw/waifu').then(response => {
let content = response.body;
let waifuUrl = content.url;
let waifuImage = content.url;
waifu.setImage(`${waifuImage}`)
waifu.setURL(`${waifuUrl}`)
waifu.setColor('#ffb9f4')
waifu.setFooter(`Requested by ${message.author.username}`)
waifu.setTimestamp()
waifu.setAuthor(`waifu.pics`, `https://waifu.pics/`)
message.channel.send(waifu)
});
};
You thought a little bit complicated ^^ You had something with children and data, although the API just gives an URL. You don't even have to parse it. And you have used the function got(), which you have to replace with get().
I fixed your code just copy it from above.
So I have this command that shows the riches users in a server this command worked yesterday however recently it has stopped working.
const { MessageEmbed } = require("discord.js");
const { stripIndents } = require("common-tags");
const { prefix } = require("../../botconfig.json");
const db = require('quick.db')
let bal = require('../../database/balance');
let rep = require('../../database/rep');
let work = require('../../database/works');
module.exports = {
config:{
name: "rich",
aliases: ["r"],
category: "currency",
description: "Tells who is rich",
usage: ""
},
run: async (client, message, args) => {
// Get all members of the server before doing anything
message.guild.members.fetch().then(guildMembers => {
let board = [];
for (let key of Object.keys(bal)) {
// Checks if the collection of GuildMembers contains the key.
if (guildMembers.has(key)) {
let value = Object.assign({user: guildMembers.get(key).user}, bal[key]);
board.push(value);
}
}
const emojis = [':first_place:', ':second_place:', ':third_place:', ':small_blue_diamond:', ':small_blue_diamond:']
board = board.sort((a,b) => b.balance-a.balance).splice(0, 5);
let top = board.map((x, i) => `${emojis[i]} **${x.balance.toLocaleString()}** - ${x.user.tag}`).join('\n');
let embed = new MessageEmbed()
.setColor("RANDOM")
.addField(`Richest users in **${message.guild.name}**`, `${top}`)
.setFooter('Switch Version 1.1');
return message.channel.send(embed);
}).catch(console.error)
}
}
The error code when the !rich command is used is as follows:
Guild_Members_Timeout: Members didn't arrive in time
I don't know if this is an issue within the bot or if it is an issue with discord.
Okay I have found the answer to my own problem it seems I needed to add intents to my discord bot to fetch the members.
All I did was add this line of code and it worked.
const intents = new Intents([
Intents.NON_PRIVILEGED, // include all non-privileged intents, would be better to specify which ones you actually need
"GUILD_MEMBERS", // lets you request guild members (i.e. fixes the issue)
]);
const client = new Client({ ws: { intents } });
None of my discord.js guildmember events are emitting, my user caches are basically empty, and my functions are timing out? . In this post it is explained in great detail and that helped me out a lot.TLDR:go to discord developer portal on your particular application ,go to bot , on bot permissions tick whatever is needed and copy the number.Then use this number as a constructor parameter for new Discord.Intents('insert the number here').This worked for me.