0

I've been struggling with it a bit and I can't think of anything. Namely, I need to get the id of the message (embed) sent by the bot and save it as a parseInt() variable. I have no idea how to do it, and my attempts so far ended in failure. Below is my code and console logs.

[code...]

let msgID = parseInt()

msg.channel.send(smnyEmbed).then(e => {
  console.log(e.id)

  msgID = e.id
})

console.log(msgID)

Logs:

NaN <- msgID
82243920***9184779 <- e.id
VLAZ
  • 26,331
  • 9
  • 49
  • 67
olios
  • 69
  • 7

2 Answers2

1

The reason why you are getting NaN from msgID is because you didn't pass the method anything to parse into an integer. To get the message ID as an integer, you can do

var msgID;
msg.channel.send(smnyEmbed).then(e => {
  console.log(e.id);
  msgID = parseInt(e.id);
})

console.log(msgID)
SirArchibald
  • 476
  • 2
  • 7
  • 23
  • I am getting an error `ReferenceError: msgID is not defined` – olios Mar 19 '21 at 12:12
  • Try moving the definition outside of the `.then`. I have updated my answer to show this. – SirArchibald Mar 19 '21 at 12:15
  • @SirArchibald changing the declaration doesn't really help. The main problem is that it's asynchronous code. `msgID = parseInt(e.id); will always run after `console.log(msgID)` See [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – VLAZ Mar 19 '21 at 12:17
  • Does the nodejs version matter because I get the `undefined` error ? – olios Mar 19 '21 at 12:19
  • No, the node version shouldn't matter. As VLAZ said, the issue is that JavaScript is run asynchronously. To get around this you may be able to `await` the `msg.channel.send` but you will need to add the code to an `async` function. – SirArchibald Mar 19 '21 at 12:22
0

what you need is:

let msgID;

msg.channel.send(smnyEmbed).then(e => {
  console.log(e.id);
  msgID = parseInt(e.id);
}).then(
    console.log(msgID);
);
Rajan
  • 625
  • 7
  • 19