英文:
send message every "x" seconds
问题
I would like to send messages every 5 seconds on different numbers with this code:
const send_message = ["34123456789", "34123456789", "34123456789"];
client.on("ready", () => {
console.log("Client is ready!");
send_message.map((value) => {
const chatId = value + "@c.us";
const message = 'This is a test message';
client.sendMessage(chatId, message);
});
});
Where or how can I add this code to create a correct loop?
await sleep(5000);
我想要使用这段代码每隔5秒发送消息到不同的号码:
const send_message = ["34123456789", "34123456789", "34123456789"];
client.on("ready", () => {
console.log("Client is ready!");
send_message.map((value) => {
const chatId = value + "@c.us";
const message = 'This is a test message';
client.sendMessage(chatId, message);
});
});
请问在哪里或如何添加这段代码以创建正确的循环?
await sleep(5000);
英文:
I would like to send messages every 5 seconds on differents numbers with this code:
const send_message = ["34123456789","34123456789","34123456789"];
client.on("ready", () => {
console.log("Client is ready!");
send_message.map((value) => {
const chatId = value + "@c.us";
const message = 'This is a test message';
client.sendMessage(chatId, message);
});
});
Where or how can I add this code to create a correct bucle?
await sleep(5000);
答案1
得分: 2
请使用 for...of 循环,将客户端的 client.on 回调函数改为 async
,如下所示:
const send_message = ["34123456789", "34123456789", "34123456789"];
client.on("ready", async () => {
console.log("Client is ready!");
for (let value of send_message) {
const chatId = value + "@c.us";
const message = 'This is a test message';
client.sendMessage(chatId, message);
await sleep(5000);
}
});
如果你需要进一步的帮助,请告诉我。
英文:
use a for...of loop instead and make the client.on callback async
Something like
const send_message = ["34123456789", "34123456789", "34123456789"];
client.on("ready", async () => {
console.log("Client is ready!");
for (let value of send_message) {
const chatId = value + "@c.us";
const message = 'This is a test message';
client.sendMessage(chatId, message);
await sleep(5000);
}
});
答案2
得分: 0
你只能在异步上下文中使用 await
。例如,你可以像这样使用 for .. of
替代 map
:
client.on("ready", async () => {
for (let value of send_message) {
const chatId = value + "@c.us";
const message = 'This is a test message';
client.sendMessage(chatId, message);
await sleep(5000);
}
})
另外,自 Node 16 起,你不再需要自己创建 sleep
(或类似)方法了。你可以使用 timers/promises
模块 中的 setTimeout
。
英文:
You can use await
only in an async context. So you can do like this for instance, using for .. of
instead of map
client.on("ready", async () => {
for (let value of send_message) {
const chatId = value + "@c.us";
const message = 'This is a test message';
client.sendMessage(chatId, message);
await sleep(5000);
}
})
BTW since node 16 you don't need to create your own sleep
(or similar) method anymore. You can use setTimeout
from the timers/promises
module
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论