Handle incoming messages and save media
masterUse the onMessageReceived callback in the Whatsapp constructor to react to incoming messages.
Inside the callback, you can:
- Check if a message is from yourself or a status update using
msg.key.fromMeormsg.key.remoteJid. - Read the message using
whatsapp.readMessage. - Trigger a typing indicator.
- Reply to a message using the
answeringoption insendTextto quote the original message. - Save media files (images, videos, documents) directly from the message object using
msg.saveImage(path),msg.saveVideo(path), ormsg.saveDocument(path)(note:saveDocumentpath should not include the extension).
const whatsapp = new Whatsapp({
adapter: new RedisAdapter({
url: "redis://localhost:6379",
}),
onMessageReceived: async (msg) => {
if (msg.key.fromMe || msg.key.remoteJid?.includes("status")) return;
const sender = msg.key.participant || msg.key.remoteJid!;
// Read message
await whatsapp.readMessage({
sessionId: msg.sessionId,
key: msg.key,
});
// Save media if available
if (msg.message?.imageMessage) {
msg.saveImage("./myimage.jpg");
}
// Reply to user
await whatsapp.sendText({
sessionId: msg.sessionId,
to: sender,
text: `You said: ${msg.message?.conversation || ""}`,
answering: msg,
});
},
});