Class: FlowChat::Whatsapp::Client
- Inherits:
-
Object
- Object
- FlowChat::Whatsapp::Client
- Includes:
- Instrumentation
- Defined in:
- lib/flow_chat/whatsapp/client.rb
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
#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 (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
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.}" } nil end |
#get_media_url(media_id) ⇒ String
Get media URL from media ID
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.
192 193 194 |
# File 'lib/flow_chat/whatsapp/client.rb', line 192 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.
171 172 173 174 175 176 177 178 179 180 |
# File 'lib/flow_chat/whatsapp/client.rb', line 171 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
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}" } (to, :audio, audio_url_or_id, mime_type: mime_type) end |
#send_buttons(to, text, buttons) ⇒ Hash
Send interactive buttons
64 65 66 67 68 |
# File 'lib/flow_chat/whatsapp/client.rb', line 64 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
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}" } (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
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 (to, caption, media: media) end |
#send_list(to, text, sections, button_text = "Choose") ⇒ Hash
Send interactive list
76 77 78 79 80 81 82 |
# File 'lib/flow_chat/whatsapp/client.rb', line 76 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 |
# 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 type, content, = response result = instrument(Events::MESSAGE_SENT, { to: to, message_type: type.to_s, content_length: content.to_s.length, platform: :whatsapp }) do = (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
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}" } (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
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 } (to, "", media: media) end |
#send_text(to, text) ⇒ Hash
Send a text message
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}" } (to, text) end |
#send_video(to, video_url_or_id, caption = nil, mime_type = nil) ⇒ Hash
Send video message
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}" } (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
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.}" } # 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 |