mcpField
W
whatsapp-web-js

whatsapp-web-js

github.com/goncy开发15147 次安装33 周前更新
代码仓库

关于 whatsapp-web-js

whatsapp-web-js 是一项使用 whatsapp-web.js 库,通过 Puppeteer 控制 Chromium 浏览器来自动化 WhatsApp Web 的指导技能,面向开发机器人程序的开发者,涵盖认证、消息、媒体、事件和运行注意事项。

主要功能

  1. 01认证策略指导
  2. 02文本与媒体消息示例
  3. 03投票、表情回应和位置支持
  4. 04消息与客户端事件模式
  5. 05运行注意事项和 ID 格式

适用场景

  1. 01构建 WhatsApp Web 机器人
  2. 02选择持久化或远程认证
  3. 03处理接收与发送消息事件
  4. 04发送媒体、投票或位置消息

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/goncy/skills --skill whatsapp-web-js

安装后在 Claude Code 中输入/whatsapp-web-js确认已加载。

附带文件references/detailed-guide.md

详细介绍

WhatsApp Web.js

为 whatsapp-web.js 提供专业指导,这是一个通过 Puppeteer 控制 Chromium 浏览器实例来自动化 WhatsApp Web 的库。

快速开始

使用身份验证策略初始化客户端并监听事件:

const { Client, LocalAuth } = require('whatsapp-web.js');

const client = new Client({
    authStrategy: new LocalAuth(),
    puppeteer: { headless: true }
});

client.on('qr', (qr) => console.log('Scan QR:', qr));
client.on('ready', () => console.log('Client ready'));
client.on('message', async (msg) => {
    if (msg.body === 'ping') await msg.reply('pong');
});

client.initialize();  // Non-blocking - listen for 'ready' event

要求:Node.js >= 18.0.0,puppeteer(必需),ffmpeg(贴纸功能可选)。

ID 格式约定

聊天操作始终使用正确的 ID 格式:

电话号码不包含 + 和前导零。例如:美国号码 +1 (234) 567-8901 应写作 [email protected]。

身份验证策略

根据部署模式进行选择:

// No persistence - QR scan every restart
new NoAuth()

// Local filesystem - recommended for single-instance bots
new LocalAuth({ clientId: 'bot1' })

// Remote store - for cloud/multi-instance deployments
new RemoteAuth({ store: myStore, clientId: 'bot1', backupSyncIntervalMs: 60000 })
配对码身份验证

使用手机号配对,跳过 QR 码扫描:

const client = new Client({
    authStrategy: new LocalAuth(),
    pairWithPhoneNumber: {
        phoneNumber: '5511999999999',  // country code + number, no symbols
        showNotification: true,
        intervalMs: 180000
    }
});
client.on('code', (code) => console.log('Pairing code:', code));

基本模式

发送消息
// Text message
await client.sendMessage('[email protected]', 'Hello!');

// Reply to received message
await msg.reply('Got it!');

// With mentions
await client.sendMessage(chatId, 'Hi @5511999999999', {
    mentions: ['[email protected]']
});

// Quote specific message
await client.sendMessage(chatId, 'Replying to this', {
    quotedMessageId: msg.id._serialized
});
媒体处理
const { MessageMedia } = require('whatsapp-web.js');

// From file
const media = MessageMedia.fromFilePath('/path/to/image.png');
await client.sendMessage(chatId, media, { caption: 'Check this out' });

// From URL
const media = await MessageMedia.fromUrl('https://example.com/image.png');
await client.sendMessage(chatId, media);

// Download received media
if (msg.hasMedia) {
    const media = await msg.downloadMedia();
    // Access: media.mimetype, media.data (base64), media.filename
}
媒体发送变体

使用特定选项控制媒体的发送方式:

// As sticker (requires ffmpeg)
await client.sendMessage(chatId, media, { sendMediaAsSticker: true });

// As voice note
await client.sendMessage(chatId, audio, { sendAudioAsVoice: true });

// As HD quality
await client.sendMessage(chatId, media, { sendMediaAsHd: true });

// As view-once
await client.sendMessage(chatId, media, { isViewOnce: true });

// As document
await client.sendMessage(chatId, media, { sendMediaAsDocument: true });
投票、回应、位置
const { Poll, Location } = require('whatsapp-web.js');

// Poll (single choice)
await client.sendMessage(chatId, new Poll('Question?', ['A', 'B']));

// Poll (multiple choice)
await client.sendMessage(chatId, new Poll('Pick', ['A', 'B', 'C'], 
    { allowMultipleAnswers: true }));

// React to message
await msg.react('👍');   // add reaction
await msg.react('');      // remove reaction

// Send location
await client.sendMessage(chatId, 
    new Location(37.422, -122.084, { name: 'Googleplex' }));
消息操作
// Edit sent message
const sent = await client.sendMessage(chatId, 'Original');
await sent.edit('Edited text');

// Delete message
await sent.delete(true);  // true = delete for everyone

// Pin message
await msg.pin(86400);     // Pin for 24h (86400|604800|2592000 seconds)
await msg.unpin();

关键注意事项

  • client.initialize() 不会阻塞 — 使用客户端前,始终监听 ready 事件
  • message 事件仅对收到的消息触发 — 使用 message_create 同时捕获发出的消息
  • 消息 ID 需要 ._serialized — 使用 msg.id._serialized 获取字符串表示
  • 群组管理员操作 — 机器人必须是管理员才能调用 setSubject、removeParticipants 等操作
  • 速率限制 — 批量发送时添加延迟,以避免临时封禁
  • fetchMessages() 从缓存加载 — 调用 chat.syncHistory() 以完整同步历史记录
  • 贴纸转换需要 ffmpeg — 将其安装到系统 PATH 中以支持贴纸
  • 内存注意事项 — 运行真实的 Chromium 实例;规划多客户端部署时需考虑这一点
  • 状态消息 — 将 status@broadcast 作为 chatId 发送

关键事件

机器人逻辑所需的基本事件:

事件用途
ready客户端已准备就绪
message仅收到的消息
message_create所有消息(包括自己发送的消息)
message_ack跟踪送达状态(0=待处理,1=服务器,2=设备,3=已读,4=已播放)
qr用于身份验证的 QR 码
authenticated身份验证成功
disconnected处理重新连接逻辑

参考资料

实现特定功能时,请参阅以下详细资料:

  • detailed-guide.md — 实现任何 WhatsApp Web.js 功能时阅读。包含按类别整理的完整 API 参考:消息、媒体、聊天、群组、频道、联系人、事件。涵盖所有方法签名、选项、返回类型和代码示例。遇到不熟悉的操作或调试异常行为时,请从这里开始。

评论

支持 Markdown