英文:
Delay only working 1 time in foreach loop (whatsapp.js)
问题
I am making a WhatsApp bot using WhatsApp Web.js, and I am sending bulk messages to my contact.
我正在使用WhatsApp Web.js制作一个WhatsApp机器人,并向我的联系人发送大量消息。
I have saved numbers in number.js
but I want to add a delay in foreach
to avoid getting banned by WhatsApp, but it only works one time.
我已经将号码保存在number.js
中,但我想在foreach
中添加延迟以避免被WhatsApp封禁,但它只能工作一次。
There are two numbers in my array, there should be a 20-second delay between them, but there is only a delay while sending the first message. Then, both messages are sent together.
我的数组中有两个号码,它们之间应该有20秒的延迟,但只有在发送第一条消息时才有延迟。然后,两条消息一起发送。
All help is appreciated.
感谢所有的帮助。
英文:
I am making a WhatsApp bot using WhatsApp Web.js, and I am sending bulk messages to my contact.
I have saved numbers in number.js
but I want to add a delay in foreach
to avoid getting banned by WhatsApp, but it only works one time.
There are two numbers in my array, there should be a 20 second delay between them, but there is only a delay while sending the first message. Then, both messages are sent together.
All help is appreciated.
const sleep = ms => new Promise(r => setTimeout(r, ms))
const smsg = () => {
Numbers.forEach(async (item) => {
let final_num = item.substring(1);
let currnum = 1;
let count = currnum;
const messagetosend = "hello";
let getuser = await user.getNumberId(final_num);
if (getuser) {
await sleep(20000)
var newn = count + 1
let currnum = newn
console.log(currnum)
console.log('Message sent to ' + final_num)
const msg = await user.sendMessage(getuser._serialized, messagetosend)
}
else { console.log("Number not found") };
})
}
user.on('message', message => {
if (message.body === '!start 2005') {
smsg()
}
});
user.initialize();
答案1
得分: 1
Array methods, be default (see further info below), do not support async functions, so the easiest solution is to replace your forEach with a for...of loop and make your smsg function async:
const smsg = async () => {
for(let item of Numbers){ ...do async stuff, await...
However, you can make array methods like forEach (and map, reduce, every, etc.) support async. I've written an answer about that here:
英文:
Array methods, be default (se further info below) does not support async functions, so the easiest solution is to replace your forEach with a for...of-loop an make your smsg function async:
const smsg = async () => {
for(let item of Numbers){ ...do async stuff, await...
However you can make array methods like forEach (and map, reduce, every etc) support async, I've written an answer about that here:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论