Discord avatar display code is not running - javascript

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}) 🙂

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 do I get the bot to write user's name

This is the code, I want it to write user's name and then auction word (p.s I am new to this)
const Discord = require('discord.js')
const client = new Discord.Client()
const { MessageEmbed } = require('discord.js');
const channel = client.channels.cache.get('889459156782833714');
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
var message = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle() // want user's name + "Auction"
.addField('Golden Poliwag', 'Very Pog', true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction')
if (msg.content === "d.test") {
msg.reply(message)
}
})
You can access the user's username by using msg.author.tag. So. the way to use the user's tag in an embed would be:
const { MessageEmbed, Client } = require("discord.js");
const client = new Client();
const channel = client.channels.cache.get("889459156782833714");
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
var message = new Discord.MessageEmbed()
.setColor("#FF0000")
.setTitle(`${msg.author.tag} Auction`)
.addField("Golden Poliwag", "Very Pog", true)
.setImage("https://graphics.tppcrpg.net/xy/golden/060M.gif")
.setFooter("Poliwag Auction");
if (msg.content === "d.test") {
msg.reply(message);
}
});
I suggest you to read the discord.js documentation, almost all you need to interact with Discord API is from there.
You can't control the bot if you don't login to it. Get the bot's token from Developer Portal and login to your bot by adding client.login('<Your token goes here>') in your project.
You can't get the channel if it's not cached in the client. You need to fetch it by using fetch() method from client's channels manager:
const channel = await client.channels.fetch('Channel ID goes here');
P/s: await is only available in async function
message event is deprecated if you are using discord.js v13. Please use messageCreate event instead.
You are able to access user who sent the message through msg object: msg.author. If you want their tag, you can get the tag property from user: msg.author.tag, or username: msg.author.username or even user ID: msg.author.id. For more information about discord message class read here.
The reply options for message is not a message. You are trying to reply the message of the author with another message which is wrong. Please replace the reply options with an object that includes embeds:
msg.reply({
embeds: [
// Your array of embeds goes here
]
});
From all of that, we now have the final code:
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
client.on("ready", () => {console.log(`Logged in as ${client.user.tag}!`)});
client.on("messageCreate", async (msg) => {
const channel = await client.channels.fetch('889459156782833714');
const embed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle(`${msg.author.tag} Auction`)
.addField('Golden Poliwag','Very Pog',true)
.setImage('https://graphics.tppcrpg.net/xy/golden/060M.gif')
.setFooter('Poliwag Auction');
if (msg.content === "d.test") {
msg.reply({
embeds: [ embed ],
});
}
});
client.login('Your bot token goes here');
Now your bot can reply to command user with an rich embed.

embed adding the same line multiple times

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

Discord js giveaway command

I am currently trying to make a Discord.js command where the first person who reacts wins the prize. There are 2 issues that I am encountering right now. First, the bot is picking up the last prize that was entered through with the command rather than the current one. Secondly, the giveaway sent before a bot restart won't work after the bot restarts.
Here is the code:
const DropModel = require('../modules/DropModel');
const { MessageEmbed, ReactionCollector } = require("discord.js")
const { COLOR, MONGO } = require("../util/BotUtil");
module.exports = {
name: "drop",
description: "First to react wins the giveaway!",
async execute(message, args) {
let prizes = args.slice(0).join(' ').toString()
if (!prizes) return message.channel.send("You didn't provide a prize.");
const newDrop = new DropModel({
guildId: message.guild.id,
prize: prizes,
channelId: message.channel.id,
createdBy: message.author,
timeCreated: new Date(),
});
newDrop.save();
let Drops = await DropModel.findOne({ guildId: message.guild.id, channelId: message.channel.id });
if (!Drops) return;
const { prize, createdBy } = Drops;
const DropEmbed = new MessageEmbed()
.setTitle(`${prize}`)
.setDescription(`First to React with 🎁 wins the giveaway
Hosted by: ${createdBy}`)
.setColor(COLOR)
.setTimestamp();
const dropMsg = await message.channel.send(`🎁 **giveaway** 🎁`, DropEmbed);
await Drops.remove();
await dropMsg.react('🎁');
const filter = (reaction, user) => !user.bot;
const reaction = new ReactionCollector(dropMsg, filter, { max: 1 });
reaction.on('collect', async (reaction, user) => {
const { embeds } = dropMsg;
const embed = embeds[0];
embed.setTitle(`Someone called giveaway!`);
embed.setDescription(`Winner: ${user.toString()}
Please contact ${createdBy} to claim your giveaway!`);
await dropMsg.edit(embed);
dropMsg.channel.send(`${user.toString()} won **${prize}**!`);
});
}
}
Any help regarding the issues mentioned above would be appreciated! Thanks!
You can save the giveaway end timestamp in JSON file or whatever database and then delete it when it's finished.

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