whatsmeow Go Library

repository·main·Indexed 27 days ago

https://github.com/tulir/whatsmeow

A 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.

Tokens
23.1K
Snippets
40
Records
171
Agent score
92%

What's inside whatsmeow

  1. Overview of whatsmeow

    main
    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.
  2. Core features of whatsmeow

    main

    The 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.
  3. Access documentation and examples for whatsmeow

    main

    For 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/whatsmeow
  4. Initialize a new WhatsApp client with NewClient

    main

    To create a new WhatsApp web client, use NewClient. You must provide a *store.Device (the device store) and an optional waLog.Logger. A default SQL-backed implementation for the store is available in the store/sqlstore package.

    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)
  5. Complete the Passkey pairing flow

    main

    To pair a device using Passkeys, you must handle a sequence of events and API calls. The typical workflow is:

    1. Listen for events.PairPasskeyRequest: This event is dispatched by the client when a passkey pairing request is received. It contains the PublicKey required to request a WebAuthn response from the user's authenticator.
    2. Get WebAuthn Response: Use the PublicKey from the event to prompt the user's authenticator for a response.
    3. Call SendPasskeyResponse: Send the resulting *types.WebAuthnResponse back to the server.
    4. Listen for events.PairPasskeyConfirmation: After sending the response, the client will dispatch this event. It contains a Code (e.g., XXXX-XXXX) that should be shown to the user for manual confirmation, and a SkipHandoffUX boolean indicating if the code can be skipped.
    5. Call SendPasskeyConfirmation: Once the user confirms the code, call this method to finalize the pairing process.
  6. Use GetQRChannel to handle WhatsApp pairing via QR code

    main

    To pair a WhatsApp account using a QR code, call GetQRChannel(ctx) on a Client instance. This method must be called before calling Connect().

    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.

  7. Handle Media Retry 404/410 errors

    main

    A 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)
        }
    }
  8. Handle device pairing via QR codes

    main

    When initiating a pairing session, the Client handles pair-device requests by generating QR code data. The events.QR event 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.QR event in your application logic.

  9. Use UseRetryMessageStore for persistent retries

    main

    When UseRetryMessageStore is enabled on the Client, outgoing messages are marshaled and stored in the cli.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 Store implementation providing an EventBuffer that supports AddOutgoingEvent, GetOutgoingEvent, and DeleteOldOutgoingEvents.

  10. Configure Automatic Message Rerequest from Phone

    main

    If 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 AutomaticMessageRerequestFromPhone to true on your Client.

    Note: This feature is disabled if MessengerConfig is set. The delay before requesting the message from the phone is controlled by the global variable RequestFromPhoneDelay (defaults to 5 seconds).

  11. Send a reaction to a Newsletter message

    main

    Use NewsletterSendReaction to send a reaction to a channel message. To remove a previously sent reaction, pass an empty string as the reaction parameter.

    Parameters:

    • jid: The JID of the newsletter.
    • serverID: The types.MessageServerID of the message being reacted to.
    • reaction: The reaction code (e.g., emoji code). Pass an empty string to remove the reaction.
    • messageID: The types.MessageID of the reaction itself. If left empty, a random ID will be generated.
  12. Download media with specific parameters to a file

    main

    Use DownloadMediaWithPathToFile for fine-grained control over the download process. This method allows you to provide the directPath, encryption/file hashes (encFileHash, fileHash), the mediaKey, and the mediaType. It handles host rotation and retries internally.

    err := client.DownloadMediaWithPathToFile(
        ctx, 
        directPath, 
        encFileHash, 
        fileHash, 
        mediaKey, 
        mediaType, 
        mmsType, 
        allowNoHash, 
        file,
    )