Class: FlowChat::Whatsapp::Client
- Inherits:
-
Object
- Object
- FlowChat::Whatsapp::Client
- Includes:
- Instrumentation
- Defined in:
- lib/flow_chat/whatsapp/client.rb
Constant Summary
Constants included from Instrumentation
Instrumentation::DELIVERED_MESSAGE_ID_KEY, Instrumentation::DELIVERY_DURATION_KEY
Instance Method Summary collapse
-
#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.
-
#download_media(media_id) ⇒ String
Download media content.
-
#get_media_mime_type(url) ⇒ Object
Get MIME type from URL without downloading (HEAD request).
-
#get_media_url(media_id) ⇒ String
Get media URL from media ID.
-
#indicate_typing(message_id) ⇒ Hash?
Show a typing indicator in response to an inbound message.
-
#initialize(config) ⇒ Client
constructor
A new instance of Client.
-
#mark_as_read(message_id, typing: false) ⇒ Hash?
Mark an inbound message as read, optionally showing a typing indicator.
-
#send_audio(to, audio_url_or_id, mime_type = nil) ⇒ Hash
Send audio message.
-
#send_buttons(to, text, buttons) ⇒ Hash
Send interactive buttons.
-
#send_document(to, document_url_or_id, caption = nil, filename = nil, mime_type = nil) ⇒ Hash
Send document message.
-
#send_image(to, image_url_or_id, caption = nil, mime_type = nil) ⇒ Hash
Send image message.
-
#send_list(to, text, sections, button_text = "Choose") ⇒ Hash
Send interactive list.
-
#send_message(to, prompt, choices: nil, media: nil) ⇒ Hash
Send a message to a WhatsApp number.
-
#send_sticker(to, sticker_url_or_id, mime_type = nil) ⇒ Hash
Send sticker message.
-
#send_template(to, template_name, components = [], language = "en_US") ⇒ Hash
Send a template message.
-
#send_text(to, text) ⇒ Hash
Send a text message.
-
#send_video(to, video_url_or_id, caption = nil, mime_type = nil) ⇒ Hash
Send video message.
-
#upload_media(file_path_or_io, mime_type, filename = nil) ⇒ String
Upload media file and return media ID.
Methods included from Instrumentation
#elapsed_ms_since, #inbound_message?, #instrument, instrument, #platform_message_id_from, report_api_error, #report_delivery_failure, #report_delivery_success, #report_to_app, #report_to_subscribers
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
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 412 413 414 415 416 417 418 |
# File 'lib/flow_chat/whatsapp/client.rb', line 310 def (response, to) type, content, = 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: [:buttons].map.with_index do |, index| { type: "reply", reply: { id: [:id] || index.to_s, title: [:title] } } end } } # Add header if provided (for media support) if [:header] interactive_payload[:header] = [: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: [:button_text] || "Choose", sections: [:sections] } } } when :template { messaging_product: "whatsapp", to: to, type: "template", template: { name: [:template_name], language: {code: [:language] || "en_US"}, components: [:components] || [] } } when :media_image { messaging_product: "whatsapp", to: to, type: "image", image: build_media_object() } when :media_document { messaging_product: "whatsapp", to: to, type: "document", document: build_media_object() } when :media_audio { messaging_product: "whatsapp", to: to, type: "audio", audio: build_media_object() } when :media_video { messaging_product: "whatsapp", to: to, type: "video", video: build_media_object() } when :media_sticker { messaging_product: "whatsapp", to: to, type: "sticker", sticker: build_media_object() } 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
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
# File 'lib/flow_chat/whatsapp/client.rb', line 445 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)
467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
# File 'lib/flow_chat/whatsapp/client.rb', line 467 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.}" } nil end |
#get_media_url(media_id) ⇒ String
Get media URL from media ID
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 |
# File 'lib/flow_chat/whatsapp/client.rb', line 423 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.
199 200 201 |
# File 'lib/flow_chat/whatsapp/client.rb', line 199 def indicate_typing() mark_as_read(, 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.
178 179 180 181 182 183 184 185 186 187 |
# File 'lib/flow_chat/whatsapp/client.rb', line 178 def mark_as_read(, typing: false) payload = { messaging_product: "whatsapp", status: "read", message_id: } payload[:typing_indicator] = {type: "text"} if typing send_read_receipt_payload(payload, ) end |
#send_audio(to, audio_url_or_id, mime_type = nil) ⇒ Hash
Send audio message
153 154 155 156 |
# File 'lib/flow_chat/whatsapp/client.rb', line 153 def send_audio(to, audio_url_or_id, mime_type = nil) FlowChat.logger.debug { "WhatsApp::Client: Sending audio to #{to}" } (to, :audio, audio_url_or_id, mime_type: mime_type) end |
#send_buttons(to, text, buttons) ⇒ Hash
Send interactive buttons
71 72 73 74 75 |
# File 'lib/flow_chat/whatsapp/client.rb', line 71 def (to, text, ) FlowChat.logger.debug { "WhatsApp::Client: Sending interactive buttons to #{to} with #{.size} buttons" } choices = .each_with_object({}) { |, hash| hash[[:id]] = [:title] } (to, text, choices: choices) end |
#send_document(to, document_url_or_id, caption = nil, filename = nil, mime_type = nil) ⇒ Hash
Send document message
131 132 133 134 135 |
# File 'lib/flow_chat/whatsapp/client.rb', line 131 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}" } (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
114 115 116 117 118 119 120 121 122 |
# File 'lib/flow_chat/whatsapp/client.rb', line 114 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 (to, caption, media: media) end |
#send_list(to, text, sections, button_text = "Choose") ⇒ Hash
Send interactive list
83 84 85 86 87 88 89 |
# File 'lib/flow_chat/whatsapp/client.rb', line 83 def send_list(to, text, sections, = "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] } } (to, text, choices: choices) end |
#send_message(to, prompt, choices: nil, media: nil) ⇒ Hash
Send a message to a WhatsApp number
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 49 50 51 52 53 54 55 |
# File 'lib/flow_chat/whatsapp/client.rb', line 22 def (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 _, _, = response # MESSAGE_SENT is instrumented by the gateway, not here. This wrapped # the send in its own instrument block, and ActiveSupport::Notifications # publishes a block event once the block returns whatever it returned - # so the event fired even when the send had failed and this method was # about to answer nil, and fired a second time when the gateway # instrumented the same send. Every subscriber counted a successful # send twice and a failed one once. result = begin # Above the button cap there is no interactive surface that can # carry media (see the renderer), so it rides in options[:media] # and goes out as its own message ahead of the choice message. (([:media], to)) if [:media] = (response, to) () end if result = result.dig("messages", 0, "id") FlowChat.logger.debug { "WhatsApp::Client: Message sent successfully to #{to}, 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
163 164 165 166 |
# File 'lib/flow_chat/whatsapp/client.rb', line 163 def send_sticker(to, sticker_url_or_id, mime_type = nil) FlowChat.logger.debug { "WhatsApp::Client: Sending sticker to #{to}" } (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
97 98 99 100 101 102 103 104 105 106 |
# File 'lib/flow_chat/whatsapp/client.rb', line 97 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 } (to, "", media: media) end |
#send_text(to, text) ⇒ Hash
Send a text message
61 62 63 64 |
# File 'lib/flow_chat/whatsapp/client.rb', line 61 def send_text(to, text) FlowChat.logger.debug { "WhatsApp::Client: Sending text message to #{to}" } (to, text) end |
#send_video(to, video_url_or_id, caption = nil, mime_type = nil) ⇒ Hash
Send video message
143 144 145 146 |
# File 'lib/flow_chat/whatsapp/client.rb', line 143 def send_video(to, video_url_or_id, caption = nil, mime_type = nil) FlowChat.logger.debug { "WhatsApp::Client: Sending video to #{to}" } (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
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 300 301 302 303 304 305 306 |
# File 'lib/flow_chat/whatsapp/client.rb', line 209 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.}" } # Instrument the error instrument(Events::MEDIA_UPLOAD, { filename: filename, mime_type: mime_type, size: file_size, success: false, error: error., platform: :whatsapp }) raise ensure file&.close if file_path_or_io.is_a?(String) end |