Ruby WhatsApp SDK

repository·main·Indexed 42 days ago

https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk

A Ruby SDK for interacting with the WhatsApp Cloud API. It provides high-level abstractions for sending various message types (text, media, templates, interactive buttons), managing media uploads and downloads, configuring business profiles and accounts, and handling phone number registration.

Tokens
12.4K
Snippets
45
Records
56
Agent score
53%

What's inside ruby_whatsapp_sdk

  1. Initialize the WhatsappSdk client

    main

    The SDK is centered around three primary resources: Messages, Media, and PhoneNumbers. To access these, you must initialize a WhatsappSdk::Api::Client with your authentication credentials.

    There are two ways to configure the client:

    Option 1: Global Configuration (Initializer)

    Use this method for long-running applications (like Rails) to set up global settings once.

    WhatsappSdk.configure do |config|
      config.access_token = ACCESS_TOKEN
      config.api_version = API_VERSION
      config.logger = Logger.new(STDOUT) # optional
      config.logger_options = { bodies: true } # optional Faraday options
    end

    Option 2: Manual Client Instance

    Use this method to create specific client instances with unique credentials or configurations.

    # Basic usage
    client = WhatsappSdk::Api::Client.new("<ACCESS TOKEN>")
    
    # With optional logger and API version
    logger = Logger.new(STDOUT)
    logger_options = { bodies: true }
    client = WhatsappSdk::Api::Client.new("<ACCESS TOKEN>", "<API VERSION>", logger, logger_options)
    # Option 1: Global Configuration
    WhatsappSdk.configure do |config|
      config.access_token = ACCESS_TOKEN
      config.api_version = API_VERSION
      config.logger = Logger.new(STDOUT)
      config.logger_options = { bodies: true }
    end
    
    # Option 2: Manual Client Instance
    client = WhatsappSdk::Api::Client.new("<ACCESS TOKEN>", "<API VERSION>", logger, logger_options)
  2. Configure the WhatsappSdk gem

    main

    You can configure the global settings for the WhatsappSdk using the configure method. This method yields a Configuration object, allowing you to set up your credentials and preferences in a block, typically within a Rails initializer.

    WhatsappSdk.configure do |config|
      # Set configuration options here
    end
  3. Troubleshoot undelivered WhatsApp messages

    main

    If the API returns a success response but the message is not delivered, check the following:

    • Template Requirements: You cannot start a chat with a user by sending a direct text message unless you have a pre-approved message template in your Meta control panel. You can only send direct text if the user has messaged you first.
    • WhatsApp Version: Ensure the recipient's device is using a supported WhatsApp version.
    • API Version: Ensure your Meta App is configured to use an API version greater than or equal to v.14.
    • Meta Dashboard: Check the Facebook dashboard for any displayed errors.
    • Delays: Note that message delivery may sometimes be delayed per Meta's performance guidelines.
  4. Manage media using the Media API

    main

    The Media resource is used to upload files to WhatsApp so they can be sent as messages. You need to provide the sender_id, the local file_path, and the MIME type (e.g., image/png, image/webp).

    Once uploaded, the returned object contains an id which is used by the Messages API to send the content.

    # Upload a photo
    image = client.media.upload(
      sender_id: SENDER_ID, 
      file_path: "test/fixtures/assets/whatsapp.png", 
      type: "image/png"
    )
    
    # Upload a sticker
    sticker = client.media.upload(
      sender_id: SENDER_ID, 
      file_path: "test/fixtures/assets/sticker.webp", 
      type: "image/webp"
    )
    
    # Use the IDs to send
    client.messages.send_image(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, image_id: image.id)
    client.messages.send_sticker(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, sticker_id: sticker.id)
  5. Manage Phone Numbers

    main

    Use the client.phone_numbers API to manage registered phone numbers. You can list all numbers for a business, retrieve a specific number by ID, register a new number using a PIN, or deregister an existing number.

    # Get the list of phone numbers registered
    client.phone_numbers.list(BUSINESS_ID)
    
    # Get a phone number by id
    client.phone_numbers.get(SENDER_ID)
    
    # Register a phone number
    client.phone_numbers.register_number(SENDER_ID, pin)
    
    # Deregister a phone number
    client.phone_numbers.deregister_number(SENDER_ID)
  6. Manage Media Files

    main

    The Media API allows you to upload, retrieve, download, and delete media files (like images or documents) on WhatsApp.

    # Upload a media
    client.media.upload(sender_id: SENDER_ID, file_path: "tmp/whatsapp.png", type: "image/png")
    
    # Get a media
    media = client.media.get(media_id: MEDIA_ID)
    
    # Download media
    client.media.download(url: MEDIA_URL, file_path: 'tmp/downloaded_whatsapp.png', media_type: "image/png")
    
    # Delete a media
    client.media.delete(media_id: MEDIA_ID)
  7. Send Interactive Reply Buttons

    main

    Interactive Reply Buttons allow users to respond by clicking one of several buttons. You can build this using WhatsappSdk::Resource::Interactive and WhatsappSdk::Resource::InteractiveActionReplyButton objects, or by passing an interactive_json hash.

    # Using Resource objects
    interactive_action = WhatsappSdk::Resource::InteractiveAction.new(type: "reply_button")
    interactive_action.add_reply_button(WhatsappSdk::Resource::InteractiveActionReplyButton.new(title: "Button 1", id: "btn_1"))
    
    interactive = WhatsappSdk::Resource::Interactive.new(
      type: "reply_button",
      header: WhatsappSdk::Resource::InteractiveHeader.new(type: "text", text: "Header"),
      body: WhatsappSdk::Resource::InteractiveBody.new(text: "Body"),
      action: interactive_action
    )
    
    client.messages.send_interactive_reply_buttons(
      sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, interactive: interactive
    )
    
    # Using JSON
    client.messages.send_interactive_reply_buttons(
      sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, interactive_json: { ... }
    )
  8. Send Various Message Types

    main

    The client.messages API supports a wide range of message types. You can send text, reactions, replies, locations, images, audio, documents, stickers, and contacts.

    For media types (image, audio, document, sticker), you can provide either a direct link or a previously uploaded id (e.g., image_id, audio_id).

    To reply to a message, include the message_id of the original message in your request.

    # Send a text message
    client.messages.send_text(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, message: "hola")
    
    # Send a reaction
    client.messages.send_reaction(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, message_id: "12345", emoji: "&#x1F550;")
    
    # Reply to a message
    client.messages.send_text(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, message: "I'm a reply", message_id: "wamid.1234")
    
    # Send a location message
    client.messages.send_location(
      sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER,
      longitude: 45.4215, latitude: 75.6972, name: "nacho", address: "141 cooper street"
    )
    
    # Send an image (via link or ID)
    client.messages.send_image(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, link: "image_link", caption: "Caption")
    client.messages.send_image(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, image_id: "1234", caption: "Caption")
    
    # Send a contact (via object or JSON)
    client.messages.send_contacts(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, contacts: [contact_object])
    client.messages.send_contacts(sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER, contacts_json: { ... })
  9. Send messages using the Messages API

    main

    The Messages resource allows you to send various types of content to recipients. You must provide a sender_id (your WhatsApp phone number ID) and a recipient_number.

    Common message types include:

    • Text: send_text
    • Location: send_location
    • Image: send_image (requires an image_id from a previously uploaded media object)
    • Sticker: send_sticker (requires a sticker_id from a previously uploaded media object)

    Note: For images and stickers, you typically use the Media API to upload the file first to obtain an ID.

    # Send a text message
    client.messages.send_text(
      sender_id: SENDER_ID, 
      recipient_number: RECIPIENT_NUMBER, 
      message: "Hey there! it's Whatsapp Ruby SDK"
    )
    
    # Send a location
    client.messages.send_location(
      sender_id: SENDER_ID, 
      recipient_number: RECIPIENT_NUMBER, 
      longitude: -75.6898604, 
      latitude: 45.4192206, 
      name: "Ignacio", 
      address: "My house"
    )
    
    # Send an image (after uploading)
    image = client.media.upload(sender_id: SENDER_ID, file_path: "path/to/image.png", type: "image/png")
    client.messages.send_image(
      sender_id: SENDER_ID, 
      recipient_number: RECIPIENT_NUMBER, 
      image_id: image.id
    )