Home > OS >  Sending a message to user
Sending a message to user

Time:12-08

I have this code I want the bot to send the message every 1 minute to a user not to send every 1 minute to all users

  guild.members.cache.forEach(member => {
 setInterval(() => {
      member.send('hello').catch(error => {message.channel.send(`**dm closed**`)});
   }, 60000)
  })
   }) 
  }
})

I tried the code below but it doesnt work its holding 1 minute and sending the message to all users

CodePudding user response:

Form the looks of it looks like you are looping through a list of guild members and for each member int that list you are sending 'hello' every minute. If you want to send 'hello' to a specific user every minute you have to specify a member in below code(replace specificMember with that member)

 setInterval(() => {
   specificMember.send('hello')
   .catch(error => {message.channel.send(`**dm closed**`)});
 }, 60000)

CodePudding user response:

So, for what I understood, for every member on a list, you want to send a message to each one one minute separated from each other.

You can use one interval for all members, saving on memory usage and CPU usage, by keeping a reference to the index of the last member that was sent a message.

let members = guild.members.cache
let index = -1;
let timer = setInterval(() => {
    if (index   1 >= members.length) index = 0;
    else index  ;
    
    let member = members[index];
    if (member) member.send('hello').catch(error => {message.channel.send(`**dm closed**`)});
}, 60000)
  • Related