Class: FlowChat::Whatsapp::Client

Inherits:
Object
  • Object
show all
Includes:
Instrumentation
Defined in:
lib/flow_chat/whatsapp/client.rb

Instance Method Summary collapse

Methods included from Instrumentation

#instrument, instrument, report_api_error

Constructor Details

#initialize(config) ⇒ Client

Returns a new instance of Client.



12
13
14
15
16
# File 'lib/flow_chat/whatsapp/client.rb', line 12

def initialize(config)
  @config = config
  FlowChat.logger.info { "WhatsApp::Client: Initialized WhatsApp client for phone_number_id: #{@config.phone_number_id}" }
  FlowChat.logger.debug { "WhatsApp::Client: API base URL: #{FlowChat::Config.whatsapp.api_base_url}" }
end

Instance Method Details

#build_message_payload(response, to) ⇒ Object

Build message payload for WhatsApp API This method is exposed so the gateway can use it for simulator mode



303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/flow_chat/whatsapp/client.rb', line 303

def build_message_payload(response, to)
  type, content, options = response

  case type
  when :text
    {
      messaging_product: "whatsapp",
      to: to,
      type: "text",
      text: {body: content}
    }
  when :interactive_buttons
    interactive_payload = {
      type: "button",
      body: {text: content},
      action: {
        buttons: options[:buttons].map.with_index do |button, index|
          {
            type: "reply",
            reply: {
              id: button[:id] || index.to_s,
              title: button[:title]
            }
          }
        end
      }
    }

    # Add header if provided (for media support)
    if options[:header]
      interactive_payload[:header] = options[:header]
    end

    {
      messaging_product: "whatsapp",
      to: to,
      type: "interactive",
      interactive: interactive_payload
    }
  when :interactive_list
    {
      messaging_product: "whatsapp",
      to: to,
      type: "interactive",
      interactive: {
        type: "list",
        body: {text: content},
        action: {
          button: options[:button_text] || "Choose",
          sections: options[:sections]
        }
      }
    }
  when :template
    {
      messaging_product: "whatsapp",
      to: to,
      type: "template",
      template: {
        name: options[:template_name],
        language: {code: options[:language] || "en_US"},
        components: options[:components] || []
      }
    }
  when :media_image
    {
      messaging_product: "whatsapp",
      to: to,
      type: "image",
      image: build_media_object(options)
    }
  when :media_document
    {
      messaging_product: "whatsapp",
      to: to,
      type: "document",
      document: build_media_object(options)
    }
  when :media_audio
    {
      messaging_product: "whatsapp",
      to: to,
      type: "audio",
      audio: build_media_object(options)
    }
  when :media_video
    {
      messaging_product: "whatsapp",
      to: to,
      type: "video",
      video: build_media_object(options)
    }
  when :media_sticker
    {
      messaging_product: "whatsapp",
      to: to,
      type: "sticker",
      sticker: build_media_object(options)
    }
  else
    # Default to text message
    {
      messaging_product: "whatsapp",
      to: to,
      type: "text",
      text: {body: content.to_s}
    }
  end
end

#download_media(media_id) ⇒ String

Download media content

Parameters:

  • media_id (String)

    Media ID from WhatsApp

Returns:

  • (String)

    Media content or nil on error



438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/flow_chat/whatsapp/client.rb', line 438

def download_media(media_id)
  media_url = get_media_url(media_id)
  return nil unless media_url

  uri = URI(media_url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(uri)
  request["Authorization"] = "Bearer #{@config.access_token}"

  response = http.request(request)

  if response.is_a?(Net::HTTPSuccess)
    response.body
  else
    FlowChat.logger.error { "WhatsApp::Client: Media download error: #{response.body}" }
    nil
  end
end

#get_media_mime_type(url) ⇒ Object

Get MIME type from URL without downloading (HEAD request)



460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/flow_chat/whatsapp/client.rb', line 460

def get_media_mime_type(url)
  require "net/http"

  uri = URI(url)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = (uri.scheme == "https")

  # Use HEAD request to get headers without downloading content
  response = http.head(uri.path)
  response["content-type"]
rescue => e
  FlowChat.logger.warn { "WhatsApp::Client: Could not detect MIME type for #{url}: #{e.message}" }
  nil
end

#get_media_url(media_id) ⇒ String

Get media URL from media ID

Parameters:

  • media_id (String)

    Media ID from WhatsApp

Returns:

  • (String)

    Media URL or nil on error



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/flow_chat/whatsapp/client.rb', line 416

def get_media_url(media_id)
  uri = URI("#{FlowChat::Config.whatsapp.api_base_url}/#{media_id}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(uri)
  request["Authorization"] = "Bearer #{@config.access_token}"

  response = http.request(request)

  if response.is_a?(Net::HTTPSuccess)
    data = JSON.parse(response.body)
    data["url"]
  else
    FlowChat.logger.error { "WhatsApp::Client: Media API error: #{response.body}" }
    nil
  end
end

#indicate_typing(message_id) ⇒ Hash?

Show a typing indicator in response to an inbound message.

Convenience wrapper around mark_as_read(message_id, typing: true). Note that WhatsApp ties the typing indicator to read-receipt delivery, so calling this also marks the message as read. There is no stop-typing call — the indicator auto-dismisses on the next outbound message or after ~25 seconds.

Parameters:

  • message_id (String)

    the inbound message id (wamid.*)

Returns:

  • (Hash, nil)

    parsed API response, or nil on failure



192
193
194
# File 'lib/flow_chat/whatsapp/client.rb', line 192

def indicate_typing(message_id)
  mark_as_read(message_id, typing: true)
end

#mark_as_read(message_id, typing: false) ⇒ Hash?

Mark an inbound message as read, optionally showing a typing indicator.

WhatsApp Cloud API ties the typing indicator to the mark-as-read call: passing typing: true adds a typing_indicator field to the same request. The indicator auto-dismisses on the next outbound message or after ~25 seconds; there is no separate "stop typing" call.

Parameters:

  • message_id (String)

    the inbound message id (wamid.*) to mark as read

  • typing (Boolean) (defaults to: false)

    when true, also show a typing indicator

Returns:

  • (Hash, nil)

    parsed API response, or nil on failure



171
172
173
174
175
176
177
178
179
180
# File 'lib/flow_chat/whatsapp/client.rb', line 171

def mark_as_read(message_id, typing: false)
  payload = {
    messaging_product: "whatsapp",
    status: "read",
    message_id: message_id
  }
  payload[:typing_indicator] = {type: "text"} if typing

  send_read_receipt_payload(payload, message_id)
end

#send_audio(to, audio_url_or_id, mime_type = nil) ⇒ Hash

Send audio message

Parameters:

  • to (String)

    Phone number in E.164 format

  • audio_url_or_id (String)

    Audio URL or WhatsApp media ID

  • mime_type (String) (defaults to: nil)

    Optional MIME type for URLs (e.g., 'audio/mpeg')

Returns:

  • (Hash)

    API response



146
147
148
149
# File 'lib/flow_chat/whatsapp/client.rb', line 146

def send_audio(to, audio_url_or_id, mime_type = nil)
  FlowChat.logger.debug { "WhatsApp::Client: Sending audio to #{to}" }
  send_media_message(to, :audio, audio_url_or_id, mime_type: mime_type)
end

#send_buttons(to, text, buttons) ⇒ Hash

Send interactive buttons

Parameters:

  • to (String)

    Phone number in E.164 format

  • text (String)

    Message text

  • buttons (Array)

    Array of button hashes with :id and :title

Returns:

  • (Hash)

    API response or nil on error



64
65
66
67
68
# File 'lib/flow_chat/whatsapp/client.rb', line 64

def send_buttons(to, text, buttons)
  FlowChat.logger.debug { "WhatsApp::Client: Sending interactive buttons to #{to} with #{buttons.size} buttons" }
  choices = buttons.each_with_object({}) { |button, hash| hash[button[:id]] = button[:title] }
  send_message(to, text, choices: choices)
end

#send_document(to, document_url_or_id, caption = nil, filename = nil, mime_type = nil) ⇒ Hash

Send document message

Parameters:

  • to (String)

    Phone number in E.164 format

  • document_url_or_id (String)

    Document URL or WhatsApp media ID

  • caption (String) (defaults to: nil)

    Optional caption

  • filename (String) (defaults to: nil)

    Optional filename

  • mime_type (String) (defaults to: nil)

    Optional MIME type for URLs (e.g., 'application/pdf')

Returns:

  • (Hash)

    API response



124
125
126
127
128
# File 'lib/flow_chat/whatsapp/client.rb', line 124

def send_document(to, document_url_or_id, caption = nil, filename = nil, mime_type = nil)
  filename ||= extract_filename_from_url(document_url_or_id) if url?(document_url_or_id)
  FlowChat.logger.debug { "WhatsApp::Client: Sending document to #{to} - filename: #{filename}" }
  send_media_message(to, :document, document_url_or_id, caption: caption, filename: filename, mime_type: mime_type)
end

#send_image(to, image_url_or_id, caption = nil, mime_type = nil) ⇒ Hash

Send image message

Parameters:

  • to (String)

    Phone number in E.164 format

  • image_url_or_id (String)

    Image URL or WhatsApp media ID

  • caption (String) (defaults to: nil)

    Optional caption

  • mime_type (String) (defaults to: nil)

    Optional MIME type for URLs (e.g., 'image/jpeg')

Returns:

  • (Hash)

    API response



107
108
109
110
111
112
113
114
115
# File 'lib/flow_chat/whatsapp/client.rb', line 107

def send_image(to, image_url_or_id, caption = nil, mime_type = nil)
  FlowChat.logger.debug { "WhatsApp::Client: Sending image to #{to} - #{url?(image_url_or_id) ? "URL" : "Media ID"}" }
  media = if url?(image_url_or_id)
    {type: :image, url: image_url_or_id}
  else
    {type: :image, id: image_url_or_id}
  end
  send_message(to, caption, media: media)
end

#send_list(to, text, sections, button_text = "Choose") ⇒ Hash

Send interactive list

Parameters:

  • to (String)

    Phone number in E.164 format

  • text (String)

    Message text

  • sections (Array)

    List sections

  • button_text (String) (defaults to: "Choose")

    Button text (default: "Choose")

Returns:

  • (Hash)

    API response or nil on error



76
77
78
79
80
81
82
# File 'lib/flow_chat/whatsapp/client.rb', line 76

def send_list(to, text, sections, button_text = "Choose")
  total_items = sections.sum { |section| section[:rows]&.size || 0 }
  FlowChat.logger.debug { "WhatsApp::Client: Sending interactive list to #{to} with #{sections.size} sections, #{total_items} total items" }
  choices = {}
  sections.each { |section| section[:rows]&.each { |row| choices[row[:id]] = row[:title] } }
  send_message(to, text, choices: choices)
end

#send_message(to, prompt, choices: nil, media: nil) ⇒ Hash

Send a message to a WhatsApp number

Parameters:

  • to (String)

    Phone number in E.164 format

  • response (Array)

    FlowChat response array [type, content, options]

Returns:

  • (Hash)

    API response or nil on error



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/flow_chat/whatsapp/client.rb', line 22

def send_message(to, prompt, choices: nil, media: nil)
  FlowChat.logger.info { "WhatsApp::Client: Sending message to #{to}" }
  FlowChat.logger.debug { "WhatsApp::Client: Message content: '#{prompt.to_s.truncate(100)}'" }

  # Use renderer to convert to structured response
  response = FlowChat::Whatsapp::Renderer.new(prompt, choices: choices, media: media).render
  type, content, _options = response

  result = instrument(Events::MESSAGE_SENT, {
    to: to,
    message_type: type.to_s,
    content_length: content.to_s.length,
    platform: :whatsapp
  }) do
    message_data = build_message_payload(response, to)
    send_message_payload(message_data)
  end

  if result
    message_id = result.dig("messages", 0, "id")
    FlowChat.logger.debug { "WhatsApp::Client: Message sent successfully to #{to}, message_id: #{message_id}" }
  else
    FlowChat.logger.error { "WhatsApp::Client: Failed to send message to #{to}" }
  end

  result
end

#send_sticker(to, sticker_url_or_id, mime_type = nil) ⇒ Hash

Send sticker message

Parameters:

  • to (String)

    Phone number in E.164 format

  • sticker_url_or_id (String)

    Sticker URL or WhatsApp media ID

  • mime_type (String) (defaults to: nil)

    Optional MIME type for URLs (e.g., 'image/webp')

Returns:

  • (Hash)

    API response



156
157
158
159
# File 'lib/flow_chat/whatsapp/client.rb', line 156

def send_sticker(to, sticker_url_or_id, mime_type = nil)
  FlowChat.logger.debug { "WhatsApp::Client: Sending sticker to #{to}" }
  send_media_message(to, :sticker, sticker_url_or_id, mime_type: mime_type)
end

#send_template(to, template_name, components = [], language = "en_US") ⇒ Hash

Send a template message

Parameters:

  • to (String)

    Phone number in E.164 format

  • template_name (String)

    Template name

  • components (Array) (defaults to: [])

    Template components

  • language (String) (defaults to: "en_US")

    Language code (default: "en_US")

Returns:

  • (Hash)

    API response or nil on error



90
91
92
93
94
95
96
97
98
99
# File 'lib/flow_chat/whatsapp/client.rb', line 90

def send_template(to, template_name, components = [], language = "en_US")
  FlowChat.logger.debug { "WhatsApp::Client: Sending template '#{template_name}' to #{to} in #{language}" }
  media = {
    type: :template,
    template_name: template_name,
    components: components,
    language: language
  }
  send_message(to, "", media: media)
end

#send_text(to, text) ⇒ Hash

Send a text message

Parameters:

  • to (String)

    Phone number in E.164 format

  • text (String)

    Message text

Returns:

  • (Hash)

    API response or nil on error



54
55
56
57
# File 'lib/flow_chat/whatsapp/client.rb', line 54

def send_text(to, text)
  FlowChat.logger.debug { "WhatsApp::Client: Sending text message to #{to}" }
  send_message(to, text)
end

#send_video(to, video_url_or_id, caption = nil, mime_type = nil) ⇒ Hash

Send video message

Parameters:

  • to (String)

    Phone number in E.164 format

  • video_url_or_id (String)

    Video URL or WhatsApp media ID

  • caption (String) (defaults to: nil)

    Optional caption

  • mime_type (String) (defaults to: nil)

    Optional MIME type for URLs (e.g., 'video/mp4')

Returns:

  • (Hash)

    API response



136
137
138
139
# File 'lib/flow_chat/whatsapp/client.rb', line 136

def send_video(to, video_url_or_id, caption = nil, mime_type = nil)
  FlowChat.logger.debug { "WhatsApp::Client: Sending video to #{to}" }
  send_media_message(to, :video, video_url_or_id, caption: caption, mime_type: mime_type)
end

#upload_media(file_path_or_io, mime_type, filename = nil) ⇒ String

Upload media file and return media ID

Parameters:

  • file_path_or_io (String, IO)

    File path or IO object

  • mime_type (String)

    MIME type of the file (required)

  • filename (String) (defaults to: nil)

    Optional filename for the upload

Returns:

  • (String)

    Media ID

Raises:

  • (StandardError)

    If upload fails



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/flow_chat/whatsapp/client.rb', line 202

def upload_media(file_path_or_io, mime_type, filename = nil)
  FlowChat.logger.info { "WhatsApp::Client: Uploading media file - type: #{mime_type}, filename: #{filename}" }

  raise ArgumentError, "mime_type is required" if mime_type.nil? || mime_type.empty?

  file_size = nil
  if file_path_or_io.is_a?(String)
    # File path
    raise ArgumentError, "File not found: #{file_path_or_io}" unless File.exist?(file_path_or_io)
    filename ||= File.basename(file_path_or_io)
    file_size = File.size(file_path_or_io)
    FlowChat.logger.debug { "WhatsApp::Client: Uploading file from path: #{file_path_or_io} (#{file_size} bytes)" }
    file = File.open(file_path_or_io, "rb")
  else
    # IO object
    file = file_path_or_io
    filename ||= "upload"
    FlowChat.logger.debug { "WhatsApp::Client: Uploading file from IO object" }
  end

  # Upload directly via HTTP
  uri = URI("#{FlowChat::Config.whatsapp.api_base_url}/#{@config.phone_number_id}/media")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  FlowChat.logger.debug { "WhatsApp::Client: Uploading to #{uri}" }

  # Prepare multipart form data
  boundary = "----WebKitFormBoundary#{SecureRandom.hex(16)}"

  form_data = []
  form_data << "--#{boundary}"
  form_data << 'Content-Disposition: form-data; name="messaging_product"'
  form_data << ""
  form_data << "whatsapp"

  form_data << "--#{boundary}"
  form_data << "Content-Disposition: form-data; name=\"file\"; filename=\"#{filename}\""
  form_data << "Content-Type: #{mime_type}"
  form_data << ""
  form_data << file.read

  form_data << "--#{boundary}"
  form_data << 'Content-Disposition: form-data; name="type"'
  form_data << ""
  form_data << mime_type

  form_data << "--#{boundary}--"

  body = form_data.join("\r\n")

  request = Net::HTTP::Post.new(uri)
  request["Authorization"] = "Bearer #{@config.access_token}"
  request["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
  request.body = body

  result = instrument(Events::MEDIA_UPLOAD, {
    filename: filename,
    mime_type: mime_type,
    size: file_size,
    platform: :whatsapp
  }) do
    response = http.request(request)

    if response.is_a?(Net::HTTPSuccess)
      data = JSON.parse(response.body)
      media_id = data["id"]
      if media_id
        FlowChat.logger.info { "WhatsApp::Client: Media upload successful - media_id: #{media_id}" }
        {success: true, media_id: media_id}
      else
        FlowChat.logger.error { "WhatsApp::Client: Media upload failed - no media_id in response: #{data}" }
        raise StandardError, "Failed to upload media: #{data}"
      end
    else
      FlowChat.logger.error { "WhatsApp::Client: Media upload error - #{response.code}: #{response.body}" }
      raise StandardError, "Media upload failed: #{response.body}"
    end
  end

  result[:media_id]
rescue => error
  FlowChat.logger.error { "WhatsApp::Client: Media upload exception: #{error.class.name}: #{error.message}" }

  # Instrument the error
  instrument(Events::MEDIA_UPLOAD, {
    filename: filename,
    mime_type: mime_type,
    size: file_size,
    success: false,
    error: error.message,
    platform: :whatsapp
  })

  raise
ensure
  file&.close if file_path_or_io.is_a?(String)
end