Embed error setTitle cannot read property null [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I have been trying to create embeds following the guide on discord.js but after writing the code properly, while executing that embed command it gives an error in terminal.
this bot is still need a huge amount of implementations but code just gives error which are a little weird as the implementation seems to be correct
currently dealing with embeds
i need help , please
const {SlashCommandBuilder, EmbedBuilder} = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName("embed")
.setDescription("Returns an Embed"),
async execute(interaction,client){
const embed = new EmbedBuilder()
const user = interaction.options.getUser('target')
.setTitle('This is totally an embed')
.setDescription('This might Work ? Maybe')
.setColor(0x18e1ee)
.setImage(client.user.displayAvatarURL())
.setThumbnail(client.user.displayAvatarURL())
.setTimestamp(Date.now())
.setAuthor({
url: `https://ww4.gogoanimes.org/`,
iconURL: interaction.user.displayAvatarURL(),
name: interaction.user.tag
})
.setFooter({
iconURL: client.user.displayAvatarURL(),
text: client.user.tag
})
.setURL('https://discord.gg/kMb9XZAq')
.addFields([
{
name: 'Field 1',
value: 'Field value 1',
inline: true
},
{
name: `Field 2`,
value: `Field value 2`,
inline: true
}
]);
await interaction.reply({embeds: [embed]})
},
}
and the error i get in the terminal is : (https://i.stack.imgur.com/IAox0.png)
i just want that embed code to work well, so that i can use it's good UI on all different commands

You're trying to set the title of null, but it has to be an EmbedBuilder(). This is very easy to fix.
const embed = new EmbedBuilder()
const user = interaction.options.getUser('target') // This line should not be here
.setTitle('This is totally an embed')
.setDescription('This might Work ? Maybe')
// ...
Should become:
const user = interaction.options.getUser('target')
const embed = new EmbedBuilder()
.setTitle('This is totally an embed')
.setDescription('This might Work ? Maybe')
// ...
Here we move the const user = ... line above so .setTitle() actually sets the title of the EmbedBuilder(). Here's a different way to see it:
Before:
const user = interaction.options.getUser('target').setTitle('This is totally an embed')
After:
const embed = new EmbedBuilder().setTitle('This is totally an embed')

After you initialize the embed, you initialize another variable. You should initialize the user variable first and then the embed.
const user = interaction.options.getUser('target')
const embed = new EmbedBuilder()
.setTitle('This is totally an embed')
.setDescription('This might Work ? Maybe')
.setColor(0x18e1ee)
.setImage(client.user.displayAvatarURL())
.setThumbnail(client.user.displayAvatarURL())
.setTimestamp(Date.now())
.setAuthor({
url: `https://ww4.gogoanimes.org/`,
iconURL: interaction.user.displayAvatarURL(),
name: interaction.user.tag
})
.setFooter({
iconURL: client.user.displayAvatarURL(),
text: client.user.tag
})
.setURL('https://discord.gg/kMb9XZAq')
.addFields([
{
name: 'Field 1',
value: 'Field value 1',
inline: true
},
{
name: `Field 2`,
value: `Field value 2`,
inline: true
}
]);
Hope it helps

Related

i can't assign a role to an user, via my code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
const Discord = require("discord.js");
require('dotenv').config();
module.exports = {
name: "manuallyverify",
description: "Manually verifies an User.",
limits: {
owner: false,
permission: ["MANAGE_ROLES"],
cooldown: "10s",
},
options: [
{
name: "user",
description: "The User that will be affected by this action.",
type: 6,
required: true,
}
],
run: (client, interaction) => {
let member = interaction.options.getUser("user").toString()
let role = interaction.guild.roles.cache.find(role => role.id == process.env.verified_role_id)
let embed = new Discord.MessageEmbed()
.setTitle(":white_check_mark: ・ Manually Verified the User.")
.addFields(
{
name: "User affected",
value: interaction.options.getUser("user").toString(),
inline: true,
},
{
name: "Role given",
value: `${role}`,
inline: true,
}
)
.setColor("#95eda4");
try {
interaction.guild.member.roles.cache.add(role)
interaction.reply({ embeds: [embed] });
} catch (e) {
interaction.reply({content:`I encountered an error: ${e}`, ephemeral: true});
}
},
};
so, this is my code, i'm making a simple verification bot that will be a template on github , but when i run the command, it gives me this error:
TypeError: Cannot read properties of undefined (reading 'roles')
so, i guess the error is because something is undefinited between interaction.guild, or guild.member. i didnt code for a while so i'm probably missing / forgetting something
also, sorry if my framework is bad
edit: i got this code to work thanks to a guy in the comments, so, thanks for coming here and have a good day
There isn't any property called interaction.guild.member and I assume what you are trying to do is to add the role to the user provided. Therefore, what you could do is use interaction.options.getMember("user") to get the user in the option and then add the role to that GuildMember. A small example:
const Discord = require("discord.js");
require('dotenv').config();
module.exports = {
name: "manuallyverify",
description: "Manually verifies an User.",
limits: {
owner: false,
permission: ["MANAGE_ROLES"],
cooldown: "10s",
},
options: [
{
name: "user",
description: "The User that will be affected by this action.",
type: 6,
required: true,
}
],
run: (client, interaction) => {
let memberToAddRole = interaction.options.getMember("user")
let role = interaction.guild.roles.cache.find(role => role.id == process.env.verified_role_id)
let embed = new Discord.MessageEmbed()
.setTitle(":white_check_mark: ・ Manually Verified the User.")
.addFields(
{
name: "User affected",
value: memberToAddRole.user.toString(),
inline: true,
},
{
name: "Role given",
value: `${role}`,
inline: true,
}
)
.setColor("#95eda4");
try {
memberToAddRole.roles.cache.add(role)
interaction.reply({ embeds: [embed] });
} catch (e) {
interaction.reply({content:`I encountered an error: ${e}`, ephemeral: true});
}
},
};
Note: the code you provided was a bit inefficient and redundant in some parts, so I have changed that accordingly
The error message tells you exactly where and what your issues is. The error message indicates that roles is undefined, so either interaction.guild.roles or interaction.guild.member.roles is undefined.

Discord /commands 'This command is outdated, please try again in a few minutes'

I have been trying to fix this issue for a while and cant find the right answer this is my code,
const { SlashCommandBuilder } = require("#discordjs/builders");
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('Get info about a user or a server!')
.addStringOption(option =>
option.setName('category')
.setDescription('The gif category')
.setRequired(true)
.addChoices(
{ name: 'Funny', value: 'funny is funny' },
{ name: 'Meme', value: 'Meme is a meme' },
{ name: 'Movie', value: 'Movie is a Movie' },
))
,
async execute(interaction) {
interaction.options.getString('category');
}
}
Heres a pic of whats happening
I've seen this happen time to time. Discord takes some amount of time for slash commands to work their way into the system when you start up your code. If your code hits lots of guilds, it could take an hour. If you only specify one guild, it is usually fairly instant but in some cases it may take 5 min. Let your code run for 5-10 min and check back, it will probably fix this error.

How do you disable a button after 5 seconds (discord.js)

I'm not very familiar with discord.js buttons and need help disabling a button after 5 seconds to avoid spam but I don't know how. Here is my code:
const newEmbed = new Discord.MessageEmbed()
.setColor('#2ACAEA')
.setTitle("Commands")
.setDescription("Page 1 of 2")
.addFields(
{name: '!jn help', value: 'This command'},
{name: '!jn ping', value: 'Ping the bot.'},
{name: '!jn coinflip', value: 'Flip a coin :D'},
{name: '!jn amiadmin', value: 'Are you an admin? We can see!'}
)
.setFooter('Need more help? Join the support discord server.')
.setImage('https://i.imgur.com/Ta0yst7.png');
const row = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('2')
.setLabel('>>')
.setStyle('SUCCESS'),
);
message.channel.send({embeds: [newEmbed], components: [row]});
setTimeout(function () {
row.components[0].setDisabled(true);
}, 5000);
When I try, it doesn't output any errors. I think I'm just missing something.
Can someone help me?
You're on the right track - you've done the first step, which is to change the button to be disabled after 5 seconds locally, but now you need to edit your message to reflect those changes online.
First, you have to store your sent message in a variable:
const sentMessage = await message.channel.send({ embeds: [newEmbed], components: [row] });
Then, in your setTimeout, you can edit the sentMessage like Dregg said in his comment:
// After you disable the button
sentMessage.edit({ embeds: [newEmbed], components: [row] });

Discord Bot won't run pass certain point in my if statement | Javascript

I can't figure out why my code doesn't run anything past the first
if statement.
I can make it run completely if I predefine the time
variable.
Although I'm not sure when I try to take the user input,
it won't continue.
I don't code much in JavaScript so I'm probably missing something
obvious. All help is appreciated.
if (msg.content === "$set") {
time = msg.content.split("$set ")[1]
if(!time)return msg.reply("how many minutes / hours will you set the alarm")
// Nothing runs past here unless I predefine the time variable
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#26aaff')
.setTitle('Custom Alert Set')
.setAuthor('Temp', 'https://i.imgur.com/XX6I7Hj.jpeg', 'https://imgur.com/')
.setDescription(`Time: ${time}`)
.setThumbnail('https://i.imgur.com/XX6I7Hj.jpeg')
.addFields(
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
)
.setTimestamp()
.setFooter('Built by', 'https://i.imgur.com/XX6I7Hj.jpeg');
msg.channel.send(exampleEmbed)
}
First of all you should use startsWith command for checking if the msg.content starts with $set. Then, the split command should have a valid parameter, so, here you can use a space " ".
if (msg.content.startsWith("$set")) {
time = msg.content.split(" ")[1]
if(!time) return msg.reply("how many minutes / hours will you set the alarm");
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#26aaff')
.setTitle('Custom Alert Set')
.setAuthor('Temp', 'https://i.imgur.com/XX6I7Hj.jpeg', 'https://imgur.com/')
.setDescription(`Time: ${time}`)
.setThumbnail('https://i.imgur.com/XX6I7Hj.jpeg')
.addFields(
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
)
.setTimestamp()
.setFooter('Built by', 'https://i.imgur.com/XX6I7Hj.jpeg');
msg.channel.send(exampleEmbed);
}
Tell me if this works!
Happy coding!
It looks like you're checking if msg.content is exactly "$set"
I think you want to be checking if msg.content contains "$set"
So try changing if (msg.content === "$set") to if (msg.content.startsWith("$set"))

Welcome message with embed is not showing

So I made a bot that will send welcome messages in a channel to new members.
My code is supposed to work because it didn't send any errors in my console, but my bot didn't send the welcome message.
I tried many things:
Made the embed an object (nope)
Made 4 long different codes (all not working)
Searched the web and watched some tuts (no error in the console but not sending)
I'm using discord.js#v12
Code:
client.on('guildMemberAdd', member => {
// Finds the channel name from the array
function channelNamesFilter(channel) {
let channelNames = ['name', 'welcome', 'welcoming', 'greeting', 'general', 'hello'];
if (channelNames.includes(channel.name)) {
return true;
}
return false;
}
const welcome = new Discord.MessageEmbed()
.setColor('#F2CC0D')
.setTitle('Welcome To The Server!')
.addFields({
name: member.nickname
}, {
name: '\n ',
value: 'Make sure to visit the FAQ and Rules channel (if there are)!'
})
.setImage(member.user.avatarURL)
let filteredChannels = member.guild.channels.cache.filter(channelNamesFilter);
filteredChannels.forEach(element => element.send(welcome));
});
Ok I just solved it after like researching for more than 10 hours! I finally got it!
client.on('guildMemberAdd', member =>{
const channel = member.guild.channels.cache.find(channel => channel.name.includes('welcome'));
if (!channel) return;
//send through channel
const welcomegreet = {
color: 0xF2CC0D,
title: `**WELCOME TO THE SERVER, ${member.user.tag} !!**`,
description: `I hope you will enjoy it here! \n A place full of chaos and wonder!`,
thumbnail: {
url: member.user.avatarURL(),
},
fields:[
{
name: 'Need Help?',
value: 'Please read the FAQ and Rules Channels (if there are)! \n Have Fun at the Server! CHEERS 🥂 !',
inline: false
},
{
name: 'Join Me!',
value: 'Do: `h.help` for entertainment and profanities!',
inline: false
}
],
timestamp: new Date(),
};
//send through dm
const welcome = {
color: 0xF2CC0D,
title: `**WELCOME TO THE SERVER, ${member.user.tag} !!**`,
description: `I hope you will enjoy it here! \n A place full of chaos and wonder!`,
thumbnail: {
url: member.user.avatarURL(),
},
timestamp: new Date(),
};
member.send({ embed: welcomegreet });
channel.send({ embed: welcome });
Thanks guys for trying to help me, even though It didn't get too close to the amswer.
I tested this out and it worked splendidly!
note:
This only works if the channel has the word "welcome"

Categories

Resources