embed adding the same line multiple times - javascript

I'm currently working on a command show a user's profile using and embed but every time the command gets used the text gets added again. so if you use the command twice you see the text twice and so on. I've tried to find a solution for about an hour but I can't find anything. I've also tried to rewrite the code multiple times and I currently have this
const { discord, MessageEmbed } = require('discord.js');
const embed = new MessageEmbed();
const users = require('../users.json');
const stand = require('../standsInfo.json');
module.exports = {
name: 'profile',
description: 'show the users profile',
execute(message, args) {
var user = message.author;
var xpNeeded = (users[user.id].level+(users[user.id].level+1))*45;
embed.setTitle(`${user.username}'s profile`);
embed.setThumbnail(user.displayAvatarURL());
embed.addField('level', `${users[user.id].level}`);
embed.addField('experience', `${users[user.id].xp}/${xpNeeded}`);
message.channel.send({embeds: [embed] });
}
}
edit: so. I just realized what was wrong I used addField instead of setField

Move const embed = new MessageEmbed(); to inside the execute scope. Otherwise you will keep editing the same embed and sending again, with added fields
const { discord, MessageEmbed } = require('discord.js');
const users = require('../users.json');
const stand = require('../standsInfo.json');
module.exports = {
name: 'profile',
description: 'show the users profile',
execute(message, args) {
var user = message.author;
var xpNeeded = (users[user.id].level+(users[user.id].level+1))*45;
const embed = new MessageEmbed();
embed.setTitle(`${user.username}'s profile`);
embed.setThumbnail(user.displayAvatarURL());
embed.addField('level', `${users[user.id].level}`);
embed.addField('experience', `${users[user.id].xp}/${xpNeeded}`);
message.channel.send({embeds: [embed] });
}
}

Related

Discord.js Adding Emojis to a send message and grab the message id

Hey Stack Overflow Community,
I have another question in regard to discord.js.I want to send a message and add an emoji to it, from which I later want to get the list of users who have reacted. In order to do so I have 2 questions:
-How can I add an emoji? Do I need a separate event listener for a message or can I do it within my interactionCreate event? I have tried pannel.react("👍") which gives me the error: 'TypeError: pannel.react is not a function'. Does anyone know how to let this work?
-My other question is if there is a way to access the message id from the send message, in order to check who has participated later on in another command?
I have an index file with my command and event handlers. The script is from my "setup.js" command in the "commands" folder:
const { SlashCommandBuilder } = require("#discordjs/builders");
const Discord = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup Tweet to be rewarded")
.addChannelOption(option =>
option
.setName('destination')
.setDescription('Select a channel for the reward pannel')
.setRequired(true)
)
.addStringOption(option =>
option
.setName("twitterlink")
.setDescription("Enter the Twitter Link")
.setRequired(false)
),
async execute(interaction) {
interaction.reply({
content: "Pannel send",
ephemeral: true
}).then( function () {
const channel = interaction.options.getChannel("destination");
const channelid = channel.id;
const twitterlink = interaction.options.getString("twitterlink");
const pannel = interaction.guild.channels.cache.get(channelid).send(twitterlink);
});
}
};
Thank you very much for your assistance in advance.
Cleaned it up a bit and this should work for you
const {
SlashCommandBuilder,
} = require("#discordjs/builders");
const Discord = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup Tweet to be rewarded")
.addChannelOption(option =>
option
.setName('destination')
.setDescription('Select a channel for the reward pannel')
.setRequired(true),
)
.addStringOption(option =>
option
.setName("twitterlink")
.setDescription("Enter the Twitter Link")
.setRequired(false),
),
async execute(interaction) { // Fixed below here and simplified it
const channel = interaction.guild.channels.cache.get(interaction.options.getChannel("destination").id);
const twitterlink = interaction.options.getString("twitterlink");
channel.send(twitterlink).then(msg => {
msg.react('🍎'),
});
return interaction.reply({
content: "Pannel send",
ephemeral: true,
});
},
};
Okay with the help from #Gh0st I was able to find a solution:
The problem in order to send a message is that the .get() function need the channel id. I have accessd it to interaction.options.getChannel("destination").id);.
I couldnt add a reaction because my .send command was not await: const pannel = await channel.send(twitterlink).
The message id is easiy to find by using .id on the variable of the message:
const pannelid = pannel.id.
The resulting code can be found below:
const { SlashCommandBuilder } = require("#discordjs/builders");
const Discord = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup Tweet to be rewarded")
.addChannelOption(option =>
option
.setName('destination')
.setDescription('Select a channel for the reward pannel')
.setRequired(true)
)
.addStringOption(option =>
option
.setName("twitterlink")
.setDescription("Enter the Twitter Link")
.setRequired(false)
),
async execute(interaction) { // Fixed below here and simplified it
const channel = interaction.guild.channels.cache.get(interaction.options.getChannel("destination").id);
const twitterlink = interaction.options.getString("twitterlink");
const pannel = await channel.send(twitterlink)
pannel.react('🍎');
const pannelid = pannel.id
return interaction.reply({
content: "Pannel send",
ephemeral: true,
});
},
};

How to .deferReply to specified channel?

How can I have it so that the bot sends a message to a specific channel, while using .deferReply and .editReply? Currently, I'm getting an error saying that suggestionChannel.deferReply is not a function. Here's my code:
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("suggest")
.setDescription("Send your suggestion to the specified channel")
.addStringOption((option) =>
option
.setName("suggestion")
.setDescription("Your suggestion")
.setRequired(true)
),
async execute(interaction, client) {
var suggestionChannelID = "900982140504793109";
var suggestionChannel = client.channels.cache.get(suggestionChannelID);
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${interaction.options.getString("suggestion")}`);
await suggestionChannel.deferReply();
await suggestionChannel
.editReply({
embeds: [embed],
})
.then(function (interaction) {
interaction.react(`👍`).then(interaction.react(`👎`));
});
},
};
How can I have it so that the bot sends a message to a specific
channel, while using .deferReply and .editReply?
Well, the short answer is; you can't. But you can do this:
As the error already says, deferReply() is not a method of the TextBasedChannels class, defined by your suggestionChannel.
Instead, try sending a message to the channel instead of replying. Replies can only be executed in the interaction's channel:
var suggestionChannelID = "900982140504793109";
var suggestionChannel = client.channels.cache.get(suggestionChannelID);
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${interaction.options.getString("suggestion")}`);
// use this instead
await suggestionChannel.send({
embeds: [embed],
});
P.S side note, deferReply() starts a 15-minute timer before the interaction expires and triggers that 'x is thinking...' text to appear when the client is calculating stuff, so try to call it as soon as possible. By default, interactions expire after 3 seconds, so if your bot fails to finish whatever it needs to accomplish within that timeframe, that interaction will fail.

Discord avatar display code is not running

I wanted to use the command "-ava #(user)" to display the avatar of the specified user. I created this code but I'm not sure why when I type the command in discord where the bot is, nothing is returned. This is the following code for my discord bot:
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
module.exports = {
name: 'ava',
description: 'Provide user with certain avatar as requested.',
execute(message, args) {
if (args[0]) {
const user = message.mentions.users.first();
if (!user) return message.reply('Please mention a user to access their avatar');
const otherIconEmbed = new Discord.RichEmbed()
.setTitle(`${user.username}'s Avatar`)
.setImage(user.displayAvatarURL);
message.channel.send(otherIconEmbed).catch(err => console.log(err));
}
const myIconEmbed = new Discord.RichEmbed()
.setTitle(`${message.author.username}'s avatar!`)
.setImage(message.author.displayAvatarURL);
message.channel.send(myIconEmbed).catch(err => console.log(err));
}
}
Simply you have to put () after displayAvatarURL so it gives displayAvatarURL () and if you want to make it animated you must put displayAvatarURL ({dynamic: true}) 🙂

Discord | How do I make it where an avatar command is made it works using ID's not only mentioning

As the question says, because I would like to use ID's as well to get someones avatar not only by pinging them.
const Discord = require("discord.js");
module.exports = {
name: 'avatar',
aliases: ["av"],
run: (bot, messages, args) => {
let member = messages.mentions.users.first() || messages.author;
let avatar = member.avatarURL({ format: 'png', size: 4096, dynamic: true});
const embed = new Discord.MessageEmbed()
.setImage(avatar)
.setTitle(member.tag)
.setDescription(member.id)
.setFooter("Šī¸ 2021 Yeet Yeet", "https://media.discordapp.net/attachments/647213722762215434/776935761807147028/staff_one.jpg")
.setColor("#FD1C03")
messages.channel.send(embed);
}
}
The thing with defining a certain variable with different code lines is that it would find the best match for the user's input. So let's take your request - We would first want to check if the first argument was an ID and if it can be turned into a user object. Then, if it can't be turned into a user object, we'd like to look for a user mention inside of the message. If it doesn't exist, then we'll finally result in getting the message author's user object. From that logic, we can simply use:
const member = client.users.cache.get(args[0]) || message.mentions.users.first() || message.author;
// checks for ID checks for mention checks for message author
Final code
const Discord = require("discord.js");
module.exports = {
name: 'avatar',
aliases: ["av"],
run: (bot, messages, args) => {
let member = client.users.cache.get(args[0]) || messages.mentions.users.first() || messages.author;
let avatar = member.avatarURL({ format: 'png', size: 4096, dynamic: true});
const embed = new Discord.MessageEmbed()
.setImage(avatar)
.setTitle(member.tag)
.setDescription(member.id)
.setFooter("Šī¸ 2021 Yeet Yeet", "https://media.discordapp.net/attachments/647213722762215434/776935761807147028/staff_one.jpg")
.setColor("#FD1C03")
messages.channel.send(embed);
}
}

How to fix Discord API: Unknown Message error?

I'm trying to make a meme command but whenever I try to use it I get this error "DiscordAPIError: Unknown Message".
This was working earlier but when I came back to my PC it started glitching out.
Here's my code
const { RichEmbed } = require("discord.js");
const randomPuppy = require("random-puppy");
const usedCommandRecently = new Set();
module.exports = {
name: "meme",
aliases: ["memes", "reddit"],
category: "fun",
description: "Sends a random meme",
run: async (client, message, args) => {
if (message.deletable) message.delete();
var Channel = message.channel.name
//Check it's in the right channel
if(Channel != "memes") {
const channelembed = new RichEmbed()
.setColor("BLUE")
.setTitle(`Use me in #memes`)
.setDescription(`Sorry ${message.author.username} this command is only usable in #memes !`)
return message.channel.send(channelembed);
}
//Check cooldown
if(usedCommandRecently.has(message.author.id)){
const cooldownembed = new RichEmbed()
.setColor("GREEN")
.setTitle("Slow it down, pal")
.setDescription(`Sorry ${message.author.username} this command has a 30 second cooldown per member, sorry for any inconvenice this may cause`)
message.channel.send(cooldownembed)
} else{
//Post meme
const subReddits = ["dankmeme", "meme", "me_irl"];
const random = subReddits[Math.floor(Math.random() * subReddits.length)];
const img = await randomPuppy(random);
const embed = new RichEmbed()
.setColor("RANDOM")
.setImage(img)
.setTitle(`From /r/${random}`)
.setURL(`https://reddit.com/r/${random}`);
message.channel.send(embed);
}
}
}
Im not sure, but maybe problem in your require block.
const { RichEmbed } = require("discord.js");
the right way its:
const Discord = require("discord.js");
let cooldownembed = new Discord.RichEmbed();
and why you use return here
return message.channel.send(channelembed);

Categories

Resources