I am trying to create a bot where after a button is pressed it edits the embed, showing the selected player in the relevant team. My problem is that I have tried to look at several options on internet and particularly stack overflow but to no avail. So I am asking instead. I am attaching the code below. It prints "I am here", which I added just to make sure the button click was being registered but does not edit the embed.
P.S. I am not great at Discord.js or JS in general so apologies if I have done something dumb.
const embed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Match Maker 3v3')
.setDescription('Lobby ' + gameID)
.addField('Team 1', team1.join('\n'))
.addField('Team 2', team2.join('\n'))
.addField('Players to choose from', players.join(' '));
message.channel.send({embeds: [embed]}).then((m) => {
const row = new MessageActionRow();
for (let i = 0; i < players.length; i++) {
row.addComponents(
new MessageButton()
.setCustomId(`${i}`)
.setLabel(`${playerNames.standard[i]}`)
.setStyle('PRIMARY'),
);
}
const collector = message.channel.createMessageComponentCollector({
max: 4,
});
collector.on('collect', interaction => {
interaction.reply(`Clicked button ${interaction.customId}`);
team1.push(players[parseInt(interaction.customId)]);
players.splice(interaction.customId, 1);
const embed2 = new MessageEmbed()
.setColor('#ffffff')
.setTitle('Match Maker 3v3')
.setDescription('Lobby ' + gameID)
.addField('Team 1', team1.join('\n'))
.addField('Team 2', team2.join('\n'))
.addField('Players to choose from', players.join(' '));
m.edit({embed: [embed2]});
console.log('I am here');
});
Try the the collector
Interaction.message.edit({embeds:[])
Related
I am working on trying to filter events for only 1 server rather than all servers the bot is in, but I'm trying to figure out how to exactly save each guild the bot is in as an collection so I can just filter events based on a guild ID I desire. Is this even possible? This is a snippet of the code I have to date, it's able to display the server names and ID's the bot is currently in, the events are working properly but triggering for all servers rather than the one I desire, how would I go about filtering for one guild collection?
const Discord = require('discord.js')
const bot = new Discord.Client()
const config = require('./config.json')
bot.on('ready', () => {
console.log(`Logged in as ${bot.user.tag}!`);
//Sets Activity
//client.user.setStatus('invisible')
bot.user.setActivity("Discord Cooks", { type: "WATCHING"})
console.log("Set User Activity!");
//Online Webhook
const webhookClient = new Discord.WebhookClient('','');
const embed = new Discord.MessageEmbed()
.setTitle(`${bot.user.tag} is online`)
.setColor('#FFFF00')
.setTimestamp()
webhookClient.send(embed);
bot.guilds.cache.forEach((guild) => {
console.log(guild.name, guild.id);
});
});
bot.on("channelCreate", (channel) => {
console.log(`channelCreate: ID: ${channel.id} Name: ${channel.name}`);
});
bot.on("channelUpdate", (oldChannel, newChannel) => {
console.log(`channelUpdate -> ${oldChannel.name} to ${newChannel.name}`);
});
bot.on("channelDelete", (channel) => {
console.log(`channelDelete: ID: ${channel.id} Name: ${channel.name}`);
});
bot.login(config.bottoken)
You can only execute code if event happened on exact server in much easier way:
if(guild.id == "GUILD_ID") {
// code
}
Also as #MrMythical said, you can just use if (message.guild.id !== "GUILD_ID") return; if you only need to run your code for 1 guild!
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);
I created a discord bot with the goal to generate reactive embeds with emoji-buttons. My problem is all the embeds created with the bot are modified simultaneously once a 'button' is pressed.
Below a pseudo-code of my bot:
const raidEmbed = new Discord.MessageEmbed() //create the embed
//some code to fill the embed
message.channel.send(raidEmbed).then(embedMessage => {
embedMessage.react('❌')
.then(()=>embedMessage.react('⭕')
//more react to create all the 'buttons'
client.on('messageReactionAdd', (reaction, user) => {
//some code to do stuff when the right 'button' is pressed
//then reset the button with this code:
if (user.id !== client.user.id) {
reaction.users.remove(user.id);
}
const newEmbed = new Discord.MessageEmbed()
//code to create the new embed
embedMessage.edit(newEmbed);
}
})
I don't understand why all my embeds are linked together and how to fix this issue.
Your embeds are not all linked together. The issue here is that you are using a global event to check for reactions. This is the part of your code that is the issue:
client.on('messageReactionAdd', (reaction, user) => {
//some code to do stuff when the right 'button' is pressed
//then reset the button with this code:
if (user.id !== client.user.id) {
reaction.users.remove(user.id);
}
const newEmbed = new Discord.MessageEmbed()
//code to create the new embed
embedMessage.edit(newEmbed);
}
What this part of your code is doing is whenever a reaction is added to any message, all of your embeds are edited. This means that even adding a reaction to a message that is not an embed will cause all of your embeds to be modified. messageReactionAdd is a global event, meaning it applies to all messages, not just your embed messages.
The best solution is to use a reaction collector instead of a reaction event. Reaction collectors are created on specific messages, so only the embed you reacted on will be modified.
Here is an example with your code, it may not necessarily be a working example but it should give you a general idea of how to accomplish this:
const raidEmbed = new Discord.MessageEmbed() //create the embed
//some code to fill the embed
message.channel.send(raidEmbed).then(embedMessage => {
embedMessage.react('❌')
.then(()=>embedMessage.react('⭕')
//more react to create all the 'buttons'
const filter = (reaction, user) => (r.emoji.name == "❌" || r.emoji.name == "⭕") && user.id === message.author.id;
const collector = embedMessage.createReactionCollector(filter, { time: 15000 });
collector.on('collect', reaction => {
//some code to do stuff when the right 'button' is pressed
//then reset the button with this code:
reaction.users.remove(message.author.id);
const newEmbed = new Discord.MessageEmbed()
//code to create the new embed
embedMessage.edit(newEmbed);
}
})
You can also use the filter to narrow down which users' reactions should be collected as well as what specific reactions you want to collect.
When a user joins the server the bot will send an embed. Everything works fine except the image and thumbnail.
Client.on('guildMemberAdd', member => {
const embed = new Discord.MessageEmbed()
.setTitle(`Welcome ***${member.displayName}***`)
.setColor("#2163D7")
.addFields({ name: `**${member.displayName}**`, value: 'Please read the **rules**'},{ name: `You are our ` , value: `***${member.guild.memberCount}*** member!`})
.setImage(member.user.avatarURL)
.setThumbnail(member.user.avatarURL)
console.log(member.user.avatarURL);
let channel = member.guild.channels.cache.find(channel => channel.name === "🚪┊𝙱𝚒𝚎𝚗𝚟𝚎𝚗𝚞𝚎");
channel.send(embed);
});
Image of what it returns
Thanks for your help :)
In Discord JS v12, avatarURL is a method. So you'll have to use:
member.user.avatarURL()
How can I edit an sent embed with my bot? First I contructed an embed:
const countdownEmbed = {
color: 0x0099ff,
title:('Countdown'),
author: {
name:`${user_name}`,
icon_url: `${user_pfp}`,
},
description: 'Your countdown starts in **3 seconds**',
thumbnail: {
url: `${client_pfp}`,
},
timestamp: new Date(),
footer: {
text: `© ${client_name}`,
icon_url: `${client_pfp}`,
},
};
Then I made a new embed:
const countdownEmbed2 = {
title:("New title!"),
description: 'Your countdown starts in **2 seconds**',
};
After creating the "updated" embed I tried to send the message and then edit it after a second:
message.channel.send({ embed: countdownEmbed })
.then((msg)=> {
setTimeout(function(){
msg.edit(countdownEmbed2);
}, 1000)
});
My code only sends the initial embed and does not edit it. But if I change the CountEmbed2 in msg.edit(countdownEmbed2) to a string, it will edit the message itself in Discord, but not the embed. Is there a way to fix this? Or is there an easier way to edit an embed?
I am unsure why but after my test, I concluded that your issue is caused by the way you're writing your embeds.
if you use the MessageEmbed constructor (if you're using discord.js v11 it's RichEmbed) it'll work.
This worked while testing it out:
const countdownEmbed = new MessageEmbed()
.setDescription('test1')
const countdownEmbed2 = new MessageEmbed()
.setDescription('test2')
.setColor('RED')
message.channel.send({ embed: countdownEmbed }).then((msg) => {
setTimeout(function () {
msg.edit(countdownEmbed2);
}, 1000)
})
Here is an example of an edit
const editEmbed = new Discord.MessageEmbed()
.setDescription('this is the old description')
message.channel.send(editEmbed).then((m) =>
m.edit(editEmbed.setDescription('this is the new description')))
let me know if this worked