🎉 使用 Node.js 实现 WhatsApp 消息自动化发送新年祝福 🎉
发布: (2025年12月29日 GMT+8 04:46)
3 min read
原文: Dev.to
Source: Dev.to
概览
使用 Node.js 和 whatsapp-web.js 自动在 WhatsApp 上发送新年快乐祝福。
整个自动化过程在本地电脑上运行,确保你的 WhatsApp 账户隐私和凭证安全。
前置条件
- Node.js v18 LTS 或更高版本
- (可选)macOS 上的 Homebrew,便于快速安装 Node.js
安装
macOS(Homebrew)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew install node@18
echo 'export PATH="/usr/local/opt/node@18/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
验证安装:
node -v
npm -v
Windows / 手动安装
从 nodejs.org 下载 Node.js LTS(v18 或更高),并确保勾选 “Add to PATH”。
node -v
npm -v
项目设置
创建项目文件夹并安装所需依赖。
macOS / Linux
mkdir ~/whatsapp-bot
cd ~/whatsapp-bot
npm init -y
npm install whatsapp-web.js qrcode-terminal formdata-node
Windows
mkdir C:\whatsapp-bot
cd C:\whatsapp-bot
npm init -y
npm install whatsapp-web.js qrcode-terminal formdata-node
脚本:contacts2025_send.js
在项目文件夹中新建 contacts2025_send.js 并粘贴以下代码:
// contacts2025_send.js
const { Client, LocalAuth } = require('whatsapp-web.js');
const client = new Client({
authStrategy: new LocalAuth({ clientId: 'default' }),
puppeteer: { headless: false } // Opens Chrome for authentication
});
client.on('ready', async () => {
console.log('✅ WhatsApp Web authenticated');
const chats = await client.getChats();
const contacts2025 = [];
for (const chat of chats) {
if (chat.isGroup) continue; // skip groups; remove this line to include groups
const messages = await chat.fetchMessages({ limit: 50 });
for (const msg of messages) {
if (!msg.fromMe) {
const msgDate = new Date(msg.timestamp * 1000);
if (msgDate.getFullYear() === 2025) {
contacts2025.push({
id: chat.id._serialized,
name: chat.name || chat.id._serialized
});
break;
}
}
}
}
console.log('Contacts who messaged you in 2025:');
contacts2025.forEach(c => console.log(c.name));
for (const contact of contacts2025) {
await client.sendMessage(contact.id, '🎉 Happy New Year! 🎉');
console.log(`Message sent to ${contact.name}`);
await new Promise(r => setTimeout(r, 5000)); // 5‑second delay
}
client.destroy();
});
client.initialize();
运行脚本
macOS / Linux
cd ~/whatsapp-bot
node contacts2025_send.js
Windows
cd C:\whatsapp-bot
node contacts2025_send.js
首次运行时,终端会显示二维码。使用 WhatsApp → 已链接设备 → 添加设备 扫描二维码。会话信息会保存在本地的 LocalAuth 中,后续运行无需再次扫描。
自定义
包含群组
删除或注释掉以下代码行:
if (chat.isGroup) continue;
个性化消息
将静态消息替换为模板:
await client.sendMessage(contact.id, `🎉 Happy New Year, ${contact.name}! 🎉`);
调整延迟
增加超时时间以遵守 WhatsApp 的速率限制:
await new Promise(r => setTimeout(r, 8000)); // 8‑second delay
日志记录
可以将已发送的消息追加到日志文件中,以便追踪:
const fs = require('fs');
...
await client.sendMessage(contact.id, '🎉 Happy New Year! ��');
fs.appendFileSync('sent_log.txt', `${new Date().toISOString()} - Sent to ${contact.name}\n`);