Skip to content

Sending Messages

Once the client is ready, every message operation is a method call. You can send to a chat ID you already know, or to a phone number that the client resolves for you. Incoming and sent messages are Pam\WhatsApp\Message objects with methods to reply, edit, react, forward, and more.

All sending methods require the client to be in the Ready state. Calling them earlier throws LogicException, so send from an onReady() listener or after Ready has fired.

WhatsApp identifies chats with serialized IDs:

Kind Format Example
Person {country code and number}@c.us [email protected]
Group {group id}@g.us [email protected]
Channel {channel id}@newsletter 120363000000000001@newsletter

Take IDs from the objects you receive ($message->from, $chat->id->serialized) rather than building them by hand. To turn a phone number into a verified ID, use getNumberId(), which returns null when the number is not on WhatsApp:

$contactId = $client->getNumberId('15555550123');
if ($contactId !== null) {
$client->sendMessage($contactId->serialized, 'Hello Alice!');
}
use Pam\WhatsApp\Event\Ready;
$client->onReady(static function (Ready $event) use ($client): void {
$message = $client->sendMessage('[email protected]', 'Your order has shipped.');
echo "Sent {$message->id->serialized}\n";
});

sendMessageToNumber() accepts a human-readable international number. It strips everything except digits (7 to 15 digits, country code included), checks that the number is registered, resolves its current WhatsApp ID, and sends:

use Pam\WhatsApp\Exception\ContactNotFoundException;
try {
$client->sendMessageToNumber('+1 (555) 555-0123', "Hello!\nThis message has two lines.");
} catch (ContactNotFoundException $exception) {
echo "{$exception->phoneNumber} is not on WhatsApp\n";
}

Sends are attempted once by default, because retrying an ambiguous failure can deliver the message twice. Opt in to bounded retries with exponential backoff when that trade-off is acceptable:

use Pam\WhatsApp\RetryOptions;
$client->sendMessageToNumber(
'+1 555 555 0123',
'Your verification code is 482913',
retry: new RetryOptions(
maxAttempts: 3, // 1 to 10
initialDelayMs: 250,
multiplier: 2.0,
maximumDelayMs: 5_000,
),
);

When all attempts fail, the client throws Pam\WhatsApp\Exception\OperationException with the operation, target, and attempt that failed, and the original error as previous.

Pass MessageSendOptions as the third argument of sendMessage() or sendMessageToNumber():

use Pam\WhatsApp\MessageSendOptions;
$client->sendMessage($chatId, 'See https://example.com/changelog', new MessageSendOptions(
linkPreview: false,
sendSeen: true,
));
Option Default Description
sendSeen true Mark the chat as read when sending.
linkPreview true Generate link previews.
quotedMessageId null Serialized ID of a message to quote.
mentions [] Contact IDs mentioned in the text.
groupMentions [] GroupMentionSend objects for group mentions.
caption null Caption for media.
sendAudioAsVoice false Send audio as a voice note.
sendVideoAsGif false Send video as a GIF.
sendMediaAsSticker false Convert media to a sticker.
sendMediaAsDocument false Send media as a document.
sendMediaAsHd false Send images in HD quality.
isViewOnce false Send media as view-once.
stickerName, stickerAuthor, stickerCategories null, null, [] Sticker metadata.
waitUntilMsgSent false Wait until WhatsApp confirms the message was sent.

The remaining options (parseVCards, ignoreQuoteErrors, invokedBotWid, media, extra) mirror whatsapp-web.js.

reply() quotes the original message and answers in the same chat:

use Pam\WhatsApp\Event\MessageReceived;
$client->onMessage(static function (MessageReceived $event): void {
if ($event->message->body === '!hours') {
$event->message->reply('We are open 9:00 to 18:00, Monday to Friday.');
}
});

reply() also accepts any content object (media, location, poll) and an optional target chat ID and MessageSendOptions.

$message = $client->getMessageById($serializedId); // ?Message
$message->react('👍');
$message->forward('[email protected]'); // a chat ID or a Chat object
$message->star();
$message->unstar();
$message->pin(86_400); // pin duration in seconds
$message->unpin();
$edited = $message->edit('Corrected text'); // only your own messages; otherwise null
$message->delete(everyone: true); // delete for everyone
$quoted = $message->getQuotedMessage(); // ?Message
$chat = $message->getChat();
$contact = $message->getContact();
$info = $message->getInfo(); // delivery and read details, or null

Commonly used properties of Message: id, chatId, from, to, author (the sender in groups), body, fromMe, timestamp, type (MessageType), ack (MessageAck), hasMedia, hasQuotedMsg, isForwarded, location, mentionedIds, and links.

To search across chats, use $client->searchMessages('invoice'). To read a chat’s history, use $chat->fetchMessages(new MessageSearchOptions(limit: 50)).

use Pam\WhatsApp\GroupMentionSend;
use Pam\WhatsApp\MessageSendOptions;
$client->sendMessage($groupId, 'Welcome @15555550123!', new MessageSendOptions(
mentions: ['[email protected]'],
));
$client->sendMessage($groupId, 'Questions go to @Support', new MessageSendOptions(
groupMentions: [new GroupMentionSend('Support', '[email protected]')],
));
use Pam\WhatsApp\Poll;
use Pam\WhatsApp\PollSendOptions;
$client->sendMessage($chatId, new Poll(
'Where should the team lunch be?',
['Pizza', 'Sushi', 'Salad'],
new PollSendOptions(allowMultipleAnswers: true),
));

A poll needs a name and at least two options. Vote on a received poll with $pollMessage->vote(['Pizza']), and read results with $client->getPollVotes($messageId) or by listening for EventType::VoteUpdated.

use Pam\WhatsApp\Location;
use Pam\WhatsApp\LocationSendOptions;
$client->sendMessage($chatId, new Location(
40.7128,
-74.0060,
new LocationSendOptions(name: 'Acme HQ', address: 'New York, NY'),
));

Received locations are available as $message->location, with latitude and longitude.

use Pam\WhatsApp\ContactList;
$alice = $client->getContactById('[email protected]');
$client->sendMessage($chatId, new ContactList([$alice]));

Buttons and ListMessage exist for source compatibility, but WhatsApp deprecated these formats and current builds may reject them. Do not depend on them in new code.

Register one listener per delivery stage. Each receives an Event\MessageAcknowledged with the message and its ack:

$client->onMessageSent(fn ($event) => printf("Sent %s\n", $event->message->id->serialized));
$client->onMessageDelivered(fn ($event) => printf("Delivered %s\n", $event->message->id->serialized));
$client->onMessageRead(fn ($event) => printf("Read %s\n", $event->message->id->serialized));
$client->onMessageFailed(fn ($event) => printf("Failed %s\n", $event->message->id->serialized));

These are derived from the acknowledgement level: Server is sent, Device is delivered, Read and Played are read, and Error is failed. The raw event remains available as EventType::MessageAcknowledged.

$client->sendPresenceAvailable();
$client->sendPresenceUnavailable();
$chat = $client->getChatById($chatId);
$chat->sendStateTyping(); // "typing..."
$chat->sendStateRecording();
$chat->clearState();
$client->sendSeen($chatId); // mark as read