Home > Software design >  Discord.js TypeError: Cannot read property '0' of undefined
Discord.js TypeError: Cannot read property '0' of undefined

Time:01-19

hi i got issues in this code any help?

client.on("message", message => { 
  if(message.content.startsWith(prefix "test")) {
      
let json = require('./json.json')
      
let channel = message.guild.channels.cache.get(json.channel);
let msg = channel.messages.fetch(json.msg);

let embed = msg.embeds[0];

embed.addField("User: ", message.author.username, true)


msg.edit({ embeds: [ embed ] });
  }
});

ERROR

let embed = msg.embeds[0];
TypeError: Cannot read property '0' of undefined

I want to add fields to that embed msg by the command but i got this error

CodePudding user response:

TextChannel.messages.fetch returns a Promise. So you have to put your code inside .then or use async/await. So the code would be:

client.on("message", message => { 
  if (message.content.startsWith(`${prefix}test`)) {
    let json = require('./json.json');
    let channel = message.guild.channels.cache.get(json.channel);
    channel.messages.fetch(json.msg).then(msg => {
      let embed = msg.embeds[0];
      embed.addField("User: ", message.author.username, true);
      msg.edit({ embeds: [embed] });
    });
  }
});
  •  Tags:  
  • Related