简体   繁体   中英

Send a direct message to the author

The code that I provided below this message works. However, when I close my DM it sends both message, could not be DMed! and Sent a message . How could I possibly make the bot send one message if the message has been sent?

message.author.send("hi").catch(() => message.channel.send("could not be DMed!")).then(() => message.channel.send(`Sent a message`));

You seem to be getting some sort of error when the dm is closed, try using the async await syntax to see what error pops up when you close the dm and go from there

  (
    async () => {
      try {
        const response = await message.channel.send('sent a message')
        console.log(response)
      } catch(err) {
        console.log(err)
        await message.channel.send("could not be DMed!")
      } 
    }
  )()

Just reverse the order of .then() and .catch() . If you attach the .then() after your .catch() , it will run like a "finally" - ie as long as the promise returned by the catch doesn't reject it is guaranteed to run.

message.author.send("hi")
  .then(() => message.channel.send(`Sent a message`))
  .catch(() => message.channel.send("could not be DMed!"));

If you want the .catch() to only run if the original promise was rejected and not also if the .then() promise rejects, you can make use of the second argument to .then() :

message.author.send("hi")
  .then(() => message.channel.send(`Sent a message`), () => message.channel.send("could not be DMed!"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM