1

Sorry if title was a bit unclear, what I want to do is catch the member.send, but I don't know how to use try and catch when also using timeinterval. It gives me an error saying that I haven't handled it.

  message.guild.members.forEach(member => {
      try {
        setInterval(() => {
          member.send("hello");         
        }, 2000)
      }
      catch(e) {
        console.log("couldnt send dm to a user!");
      }

Second problem: Cannot read property of 'guild' of undefined, and UnhandledPromiseRejection

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
// create an async function and run it
(async function(message) {
  for (const [id, member] of message.guild.members) {
      try {
          // await will throw any error found and allow try/catch to work
          await member.send("hello");
      } catch (err) {
          console.log("Found error", err);
      }
      await sleep(2000);
  }
})();

1 Answers1

2

try/catch doesn't work for promise rejections, nor does it work when wrapped around a setInterval. Just catch the promise:

member.send("hello").catch(err => {
    console.error(`Got error ${err}.`);
});

If you want to send a message to each person then the best way is to use a promise-based sleep function:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
// create an async function and run it
(async function() {
    for (const [id, member] of message.guild.members) {
        try {
            // await will throw any error found and allow try/catch to work
            await member.send("hello");
        } catch (err) {
            console.log("Found error", err);
        }
        await sleep(2000);
    }
})();
Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • Thank you very much that worked. Now I have another problem, I want it to send 1 message to everyone in the server, but it loops around, and sends the same message to the same person over and over again (every 2 seconds since interval) – Erik Johansson Nov 25 '20 at 19:42
  • @ErikJohansson I've edited some code into my answer. – Aplet123 Nov 25 '20 at 19:47
  • I've edited my question, sorry if I made a obvious misstake never done this before – Erik Johansson Nov 25 '20 at 20:17
  • The `async function` part is supposed to go in your actual message handler where `message` is defined, and not as an argument to the function. – Aplet123 Nov 25 '20 at 20:18