Username in embed footer discord bot - javascript

I want that the username of the user, who requested the command gets displayed in the footer. I have tried many things, but I dont know how I am supposed to do it.
My code is here:
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#000033')
.setTitle('```Help```')
.setDescription('For more help, type .help (command)')
.addFields(
{ name: '.list', value: 'Opens list of all the achievements' },
{ name: '.profile', value: 'Opens achievement statistics from a member', },
{ name: '.leaderbord', value: 'Opens a leaderbord of the members with most achievements', },
{ name: '.bot', value: 'Opens bot links and information about the bot', },
{ name: '.setup', value: 'Starts the setup of the bot (only for administrators)', }
)
.setTimestamp()
.setFooter("here should the name stand")
client.on("message", (message) => {
if (message.content == ".help") {
message.channel.send(exampleEmbed)
console.log(message.member.user.tag +' executed command .HELP')
}
})

You are looking for .setFooter(message.author.username)
Full Code:
client.on("message", (message) => {
if (message.content == ".help") {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#000033')
.setTitle('```Help```')
.setDescription('For more help, type .help (command)')
.addFields(
{ name: '.list', value: 'Opens list of all the achievements' },
{ name: '.profile', value: 'Opens achievement statistics from a member', },
{ name: '.leaderbord', value: 'Opens a leaderbord of the members with most achievements', },
{ name: '.bot', value: 'Opens bot links and information about the bot', },
{ name: '.setup', value: 'Starts the setup of the bot (only for administrators)', }
)
.setTimestamp()
.setFooter(message.author.username);
message.channel.send(exampleEmbed)
console.log(message.member.user.tag +' executed command .HELP')
}
})
as mentioned below, you need to put your embed inside the message event listener

Related

Discord.js select menu interaction failed after selecting an option

I have a select menu where once a menu item is selected, it should send an embed with some info but it doesn't, only "This interaction failed" is displayed. There is no error in the console.
Here is my code:
if (!args[0]) {
const home = new EmbedBuilder()
.setAuthor({
name: `Welcome to the help panel.`,
iconURL: client.user.displayAvatarURL({ dynamic: true, size: 512 }),
})
.setColor(COLORS)
.setDescription(
`You can start streaming music straight away without any setup, just run the \`${PREFIX}play\` command, give it something to search for and you're good to go! \n\nUnlock exclusive benefits by purchasing a premium membership: **[Buy Premium](https://www.patreon.com/join/EliMusic)** \n\n**All Link:** [WebSite](https://elimusic.top/) | [Vote](https://top.gg/bot/944606401219690516/vote) | [Support](https://discord.gg/Q4RWKU2UqB)`,
)
.setFooter({
text: `© MihaiT`,
iconURL: message.author.displayAvatarURL(),
});
const info = new EmbedBuilder()
.setColor(COLORS)
.setAuthor({
name: `Eli's Commands`,
iconURL: client.user.displayAvatarURL({ dynamic: true, size: 512 }),
})
.addFields(
{
name: `<:Eli_Bot:972786663078105128> Info`,
value: `Detailed help for an order: \`${PREFIX}help [commands]\` \nFor more help, visit our [support server](https://discord.gg/Q4RWKU2UqB)`,
},
{
name: `<:Eli_ADD:972784975172751380> Comandos`,
value: `\`${PREFIX}about\`: Stats and bots details. \n\`${PREFIX}help\`: Help commands. \n\`${PREFIX}invite\`: You receive a link so you can invite me to any server you manage. \n\`${PREFIX}vote\`: Vote for Nakano on Top.gg \n\`${PREFIX}support\`: To join communities.`,
},
)
.setFooter({
text: `© MihaiT`,
iconURL: message.author.displayAvatarURL(),
});
const components = (state) => [
new ActionRowBuilder().addComponents(
new SelectMenuBuilder()
.setCustomId('help-menu')
.setPlaceholder('Please Select a Category')
.setDisabled(state)
.addOptions([
{
label: `Home`,
value: `home`,
description: `Go home`,
emoji: `<:EliOfficial:972798080393052191>`,
},
{
label: `Info`,
value: `info`,
description: `See info commands`,
emoji: `<:Eli_Bot:972786663078105128>`,
},
]),
),
];
message.reply({
embeds: [home],
allowedMentions: { repliedUser: false },
components: components(true),
});
const filter = (interaction) => interaction.user.id === message.author.id;
const collector = message.channel.createMessageComponentCollector({
filter,
componentType: 'SELECT_MENU',
max: 10,
});
collector.on('collect', (interaction) => {
if (interaction.values[0] === 'home') {
interaction.reply({ embeds: [home], ephemeral: true });
} else if (interaction.values[0] === 'info') {
interaction.reply({ embeds: [info], ephemeral: true });
}
});
}
If you look at the image below, you will see that it doesn't give me anything after I select an option. I use discord.js v14.
The createMessageComponentCollector's componentType option should be an enum. You should use ComponentType.SelectMenu and it will work:
const collector = message.channel.createMessageComponentCollector({
filter,
componentType: ComponentType.SelectMenu,
max: 10,
});
Related answer: Discord.js v13 code breaks when upgrading to v14

Discord JS v12 Add Field Issues

let xp = db.get(`xpchannel_${message.guild.id}`)
let wel = db.get(`welchannel_${message.guild.id}`)
let px = db.get(`prefix_${message.guild.id}`)
let defaultprefix = '.'
let disabled = ':white_circle: Disabled'
let embed = new Discord.MessageEmbed()
.setColor(ee.color)
.setAuthor('Database Settings', client.user.avatarURL())
.setThumbnail(ee.thumbnail)
.addFields(
{ name: '__**XP Channel**__', value: `${xp || `${disabled}`}`, inline: true },
{ name: '__**Welcomer Channel**__', value: `${wel || `${disabled}`}`, inline: true },
{ name: '__**Set Prefix**__', value: `\`${px || `${defaultprefix}`}\``, inline: true },
)
if (!message.member.permissions.has('ADMINISTRATOR')) {
return message.channel.send("<:warning:943421375526355024> | **You Need `ADMINISTRATOR` Permissions To Use This Command!**");
}
message.channel.send(embed)
Whenever I use this command and theres a xp channel or welcomer channel in the database it returns the channel id instead of the channel itself, I have tried to fix this by adding <# > at the front and end of the variable but then when theres no channel in the database it returns <#null> instead of the disabled variable. How would i fix that?
You should check if the values of those variables (xp and wel) are truthy. If they are, the channel ID is returned from the database, you can squeeze them beetween <# and >. If the returned value is null, you can simply pass the disabled variable:
.addFields(
{
name: '__**XP Channel**__',
value: xp ? `<#${xp}>` : disabled,
inline: true,
},
{
name: '__**Welcomer Channel**__',
value: wel ? `<#${wel}>` : disabled,
inline: true,
},
{
name: '__**Set Prefix**__',
value: `\`${px || defaultprefix}\``,
inline: true,
},
);

How to edit a message with discord.js?

What I want:
I want to make this interval edit the message every minute to update the server stats for my fivem server, all though I don't know how to edit the message. I've tried multiple ways, I am wondering if I declared channelStat incorrectly or the method to edit a message with discord.js is different than what I am trying.
Any help would be greatly appreciated.
I've tried the .edit() function, which is in the code sample
Code:
var serverStats = setInterval(function () {
const channelStat = client.channels.cache.get('902678733977157632').messages.fetch('902682557789908992')
Gamedig.query({
type: 'fivem',
host: config.ipabs,
port: config.port
}).then((state) => {
const embed = new Discord.MessageEmbed()
.setTitle('Logic RP Stats:')
.setImage('https://images-ext-2.discordapp.net/external/PaPGVPWBJVWcsboWGg9IWOfE0U0QSj1sb3UEwYIHYcA/https/images-ext-1.discordapp.net/external/zcWeRc4OUGdU4UKejuGPzrBt2CvqZY8iIqPZtcrUc84/https/images-ext-2.discordapp.net/external/QyWWFfOXuBL0VfdsZNJJdwoLQKQcvmpXo9IHRZoDM6U/https/cdn-longterm.mee6.xyz/plugins/reaction_roles/images/873023096611799080/911344681e6437aff9cc5e8a6660412e8733a43cde7dc38d01649a557a5e46d8.gif')
.addFields(
{
name: "Status:",
value: `Online`,
inline: true
},
{
name: "Queue:",
value: `${state}`,
inline: true
},
{
name: "IP:",
value: `${state.connect}`,
inline: true
},
{
name: "Next Restart:",
value: `12:00 PM EST`,
inline: true
},
{
name: "Players:",
value: `${state.raw.clients}/${state.maxplayers}`,
inline: true
},
{
name: "Ping:",
value: `${state.ping}`,
inline: true
},
{
name: "Inhabitants:",
value: liste,
inline: false
},
)
.setColor(`AQUA`)
.setFooter(`Logic RP | ${versionNumber}`)
channelStat.edit({embeds: [embed]})
}).catch((error) => {
const embed = new Discord.MessageEmbed()
.setTitle('The Server Is Currently Down')
.setImage('https://images-ext-2.discordapp.net/external/PaPGVPWBJVWcsboWGg9IWOfE0U0QSj1sb3UEwYIHYcA/https/images-ext-1.discordapp.net/external/zcWeRc4OUGdU4UKejuGPzrBt2CvqZY8iIqPZtcrUc84/https/images-ext-2.discordapp.net/external/QyWWFfOXuBL0VfdsZNJJdwoLQKQcvmpXo9IHRZoDM6U/https/cdn-longterm.mee6.xyz/plugins/reaction_roles/images/873023096611799080/911344681e6437aff9cc5e8a6660412e8733a43cde7dc38d01649a557a5e46d8.gif')
.setColor('AQUA')
.setFooter(`Logic RP | ${versionNumber}`)
channelStat.edit({embeds: [embed]})
});
}, 60000);
In this example, I will use channelStat to get the channel messages.
Then, I'll use the fetch API to edit the msg, and add the response to it:
const channelStat = client.channels.cache.get('902678733977157632').messages.fetch('902682557789908992').then((msg) => {
msg.edit({embeds: [embed]});
});

finding an embed created by a bot (discord.js)

This might be a little bit complicated...
I have made on my server a report system, where if a user reacts with an "❗", this message gets reported in a channel only the owner sees. This is my code so far:
client.on("messageReactionAdd", (messageReaction, user) => {
const msg = messageReaction.message;
if (messageReaction.emoji.name == "❗") {
if (messageReaction.count > 1) {
// code missing here
} else {
const embed = new Discord.MessageEmbed()
.setColor("#ff9e00")
.setDescription("§ Report")
.setFooter(`${msg.member.user.tag}`, msg.member.user.displayAvatarURL())
.setTimestamp()
.addFields(
{name: "Message", value: `[${msg.cleanContent}](${msg.url})`, inline: false},
{name: "Amount", value: messageReaction.count, inline: true},
{name: "Channel", value: `${msg.channel.name}`, inline: true});
msg.member.guild.channels.cache.get(config.channels.report).send((embed));
}
};
});
so, everytime someone reports a message, and he was the first one reporting it, my bot will send a new bot, but I want now if a reaction is not the first, I want that the bot edits the according embed, and increases/updates the messageReaction.count.
Anyone an idea how I find the initial message without having a database?
Thanks in advance!
I have modified the code to keep a collection of message IDs from reports that have been sent.
When a report needs to be edited, its ID is fetched from the collection and used to get the actual message, then a new embed is then created from the old embed with the second field incremented. Finally, the message is edited with the new embed containing the incremented field.
client.on("messageReactionAdd", async (messageReaction, user) => {
const msg = messageReaction.message;
if (messageReaction.emoji.name == "❗") {
if (messageReaction.count > 1) {
const message = (await msg.guild.channels.cache.get(config.channels.report).messages.fetch()).find(message => message.embeds[0].fields[3].value === msg.id);
const embed = new Discord.MessageEmbed(message.embeds[0])
.spliceFields(1, 1, {name: "Amount", value: messageReaction.count, inline: true});
message.edit(embed);
} else {
const embed = new Discord.MessageEmbed()
.setColor("#ff9e00")
.setDescription("§ Report")
.setFooter(`${msg.member.user.tag}`, msg.member.user.displayAvatarURL())
.setTimestamp()
.addFields(
{name: "Message", value: `[${msg.cleanContent}](${msg.url})`, inline: false},
{name: "Amount", value: messageReaction.count, inline: true},
{name: "Channel", value: `${msg.channel.name}`, inline: true},
{name: "Message ID", value: msg.id, inline: false});
msg.guild.channels.cache.get(config.channels.report).send(embed);
}
};
});
Here is some extra code if you want to edit reports when the original message gets deleted:
client.on("messageDelete", async (msg) => {
const message = (await msg.guild.channels.cache.get(config.channels.report).messages.fetch()).find(message => message.embeds[0].fields[3].value === msg.id);
if (message) {
const embed = new Discord.MessageEmbed(message.embeds[0])
.spliceFields(0, 1, {name: "Message", value: `[${msg.cleanContent}](*deleted*)`, inline: false})
.spliceFields(3, 1, {name: "Message ID", value: '*deleted*', inline: false})
.setDescription("§ Report\n**The user deleted their message, but here is its content.**");
message.edit(embed);
}
});

Again the error "SyntaxError", but now I follow the answer of my past question

I have asked about "SyntaxError" in my previous question (Erro:SyntaxError: Unexpected token ':' in MUSIC BOT). I have follow the answer, but in another code, and the error appeared again... I think I went wrong in something on the code... I followed what #Emre responded in the music bot, and it worked. But I did it in this code and it didn't work:
const Commando = require('discord.js-commando');
const RichEmbed = require('discord.js').RichEmbed;
const Discord = require('discord.js');
class AddCommand extends Commando.Command {
constructor(client) {
super(client, {
name: 'add',
aliases: ['create', 'new', 'add-suggestion', 'suggestion', 'add-feedback', 'feedback'],
group: 'suggestions',
memberName: 'add',
description: 'Add a suggestion',
examples: ['add "Add music bot" "Please add a music bot to the server, because it\'s fun!"'],
guildOnly: true,
throttling: {
usages: 2,
duration: 60
},
args: [
{
key: 'title',
prompt: 'What is the title of your suggestion?',
type: 'string',
min: 4,
max: 50,
wait: 60
},
{
key: 'description',
prompt: 'Please provide a description of your suggestion.',
type: 'string',
min: 10,
wait: 300
}
],
argsSingleQuotes: false,
});
}
module.exports.run = async ((msg, args) => ({ //here what his responded for me make, put "(" before the "{"
let channel = msg.guild.settings.get('channel');
if (!channel || !(channel = messege.guild.channels.get(channel))) {
msg.react('❌');
return msg.reply('Sorry, we are not taking new suggestions for the moment.');
}
const id = msg.guild.settings.get('next_id', 1);
const formattedId = String(id).length >= 4 ? '' + id : (String('0').repeat(4) + id).slice(-4);
const embed = new RichEmbed();
embed.setAuthor(`Feedback #${form.attedId}`, msg.guild.iconURL)
.addField('Title', args.title)
.addField('Description', args.description)
.setFooter(`Posted by ${msg.author.username}#${msg.author.discriminator}`, msg.author.displayAvatarURL)
.setTimestamp();
const suggestion = await channel.sendEmbed(embed);
suggestion.react('👍').then(() => suggestion.react('👎'));
msg.guild.settings.set(`feedback#${id}`, suggestion.id);
msg.guild.settings.set('next_id', id + 1);
if (!msg.promptCount) msg.react('✅');
let reply = 'Thanks you for your feedback.';
if (channel.permissionsFor(msg.member).hasPermission('READ_MESSAGES')) {
reply += ` You can see it in ${channel} (ID #${formattedId}).`;
}
reply = await msg.reply(reply);
if (!msg.promptCount && msg.deletable && reply.deletable) {
msg.delete(10000);
reply.delete(10000);
}
return reply;
}); //and here ")" after "}"
}
module.exports = AddCommand;
I apologize for asking everything about discord.js all the time, I'm a very beginner ... lol... If someone can help me, I will be grateful...
EDIT: Sorry for errors, I'm not speak english so much...
You seem to be using RichEmbed, which has been replaced with MessageEmbed.

Categories

Resources