whatsmeow Go Library
repository·main·Indexed 27 days ago
https://github.com/tulir/whatsmeowA Go library for interacting with the WhatsApp web multidevice API. It enables automated messaging, group management, and state synchronization, supporting features such as sending text and media, handling presence and status, and managing app state. The library includes tools for decoding Armadillo messages (Facebook and Instagram) and provides a client implementation with event handling and proxy support.
What's inside whatsmeow
- whatsmeow is a Go library designed for interacting with the WhatsApp web multidevice API. It allows developers to build applications that can send and receive messages, manage groups, and handle various WhatsApp protocol features.
Core features of whatsmeow
mainThe library supports the following core WhatsApp functionalities:
- Messaging: Sending text and media messages to private chats and groups; receiving all incoming messages.
- Group Management: Managing groups, receiving group change events, and joining via invite messages or links (creating/using invite links).
- Presence & Status: Sending and receiving typing notifications; sending and receiving delivery and read receipts.
- App State: Reading and writing app state, including contact lists and chat pin/mute status.
- Reliability: Sending and handling retry receipts if message decryption fails.
- Experimental: Sending status messages (may have limitations with large contact lists).
Currently unsupported features:
- Sending broadcast list messages.
- Making or receiving calls.
Access documentation and examples for whatsmeow
mainFor detailed information on how to use the library, refer to the official Go documentation (godoc). It contains comprehensive documentation for all methods and event types, as well as a simple package example at the top of the documentation page.
https://pkg.go.dev/go.mau.fi/whatsmeowInitialize a new WhatsApp client with NewClient
mainTo create a new WhatsApp web client, use
NewClient. You must provide a*store.Device(the device store) and an optionalwaLog.Logger. A default SQL-backed implementation for the store is available in thestore/sqlstorepackage.Example usage:
// Using a SQL-backed store container, err := sqlstore.New(context.Background(), "sqlite3", "file:yoursqlitefile.db?_foreign_keys=on", nil) if err != nil { panic(err) } deviceStore, err := container.GetFirstDevice() if err != nil { panic(err) } client := whatsmeow.NewClient(deviceStore, nil)container, err := sqlstore.New(context.Background(), "sqlite3", "file:yoursqlitefile.db?_foreign_keys=on", nil) if err != nil { panic(err) } // If you want multiple sessions, remember their JIDs and use .GetDevice(jid) or .GetAllDevices() instead. deviceStore, err := container.GetFirstDevice() if err != nil { panic(err) } client := whatsmeow.NewClient(deviceStore, nil)Complete the Passkey pairing flow
mainTo pair a device using Passkeys, you must handle a sequence of events and API calls. The typical workflow is:
- Listen for
events.PairPasskeyRequest: This event is dispatched by the client when a passkey pairing request is received. It contains thePublicKeyrequired to request a WebAuthn response from the user's authenticator. - Get WebAuthn Response: Use the
PublicKeyfrom the event to prompt the user's authenticator for a response. - Call
SendPasskeyResponse: Send the resulting*types.WebAuthnResponseback to the server. - Listen for
events.PairPasskeyConfirmation: After sending the response, the client will dispatch this event. It contains aCode(e.g.,XXXX-XXXX) that should be shown to the user for manual confirmation, and aSkipHandoffUXboolean indicating if the code can be skipped. - Call
SendPasskeyConfirmation: Once the user confirms the code, call this method to finalize the pairing process.
- Listen for
Use GetQRChannel to handle WhatsApp pairing via QR code
mainTo pair a WhatsApp account using a QR code, call
GetQRChannel(ctx)on aClientinstance. This method must be called before callingConnect().It returns a read-only channel of
QRChannelItem. The channel will emit new QR codes automatically as they expire, and will emit a final status item (like success or error) before closing. You should listen to this channel in a loop to display QR codes to the user and handle the pairing lifecycle.Handle Media Retry 404/410 errors
mainA complete workflow for handling media download failures due to missing files on the server (404/410) involves detecting the error, requesting a retry, and updating the media path upon receiving the decrypted notification.
// Full workflow example var mediaRetryCache map[types.MessageID]*waE2E.ImageMessage // ... inside message processing ... imageMsg := evt.Message.GetImageMessage() data, err := cli.Download(imageMsg) if errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith404) || errors.Is(err, whatsmeow.ErrMediaDownloadFailedWith410) { err = cli.SendMediaRetryReceipt(ctx, &evt.Info, imageMsg.GetMediaKey()) if err == nil { // You must store the event data to handle the retry response mediaRetryCache[evt.Info.ID] = imageMsg } } // ... in your event loop ... func eventHandler(rawEvt any) { switch evt := rawEvt.(type) { case *events.MediaRetry: imageMsg, ok := mediaRetryCache[evt.MessageID] if !ok { return } retryData, err := whatsmeow.DecryptMediaRetryNotification(evt, imageMsg.GetMediaKey()) if err != nil || retryData.GetResult != waMmsRetry.MediaRetryNotification_SUCCESS { return } // Update path and retry download imageMsg.DirectPath = retryData.DirectPath data, err := cli.Download(imageMsg) } }Handle device pairing via QR codes
mainWhen initiating a pairing session, the
Clienthandlespair-devicerequests by generating QR code data. Theevents.QRevent is dispatched containing one or more QR code strings. These strings follow the format:https://wa.me/settings/linked_devices#<ref>,<noise>,<identity>,<adv>,<clientType>.To handle pairing, listen for the
events.QRevent in your application logic.Use UseRetryMessageStore for persistent retries
mainWhen
UseRetryMessageStoreis enabled on theClient, outgoing messages are marshaled and stored in thecli.Store.EventBuffer. This allows the client to recover and resend messages even after a restart if a retry receipt is received later.This relies on the
Storeimplementation providing anEventBufferthat supportsAddOutgoingEvent,GetOutgoingEvent, andDeleteOldOutgoingEvents.Configure Automatic Message Rerequest from Phone
mainIf a message is received that requires a retry (e.g., due to encryption issues), the client can automatically request the message from the sender's phone.
To enable this, set
AutomaticMessageRerequestFromPhonetotrueon yourClient.Note: This feature is disabled if
MessengerConfigis set. The delay before requesting the message from the phone is controlled by the global variableRequestFromPhoneDelay(defaults to 5 seconds).Send a reaction to a Newsletter message
mainUse
NewsletterSendReactionto send a reaction to a channel message. To remove a previously sent reaction, pass an empty string as thereactionparameter.Parameters:
jid: The JID of the newsletter.serverID: Thetypes.MessageServerIDof the message being reacted to.reaction: The reaction code (e.g., emoji code). Pass an empty string to remove the reaction.messageID: Thetypes.MessageIDof the reaction itself. If left empty, a random ID will be generated.
Download media with specific parameters to a file
mainUse
DownloadMediaWithPathToFilefor fine-grained control over the download process. This method allows you to provide thedirectPath, encryption/file hashes (encFileHash,fileHash), themediaKey, and themediaType. It handles host rotation and retries internally.err := client.DownloadMediaWithPathToFile( ctx, directPath, encFileHash, fileHash, mediaKey, mediaType, mmsType, allowNoHash, file, )