Current section

Files

Jump to
messenger_bot lib messenger_bot services message.ex
Raw

lib/messenger_bot/services/message.ex

defmodule MessengerBot.Service.Message do
@moduledoc """
Facebook Messenger 'Message' API
"""
use EventBus.EventSource
alias MessengerBot.Client
alias MessengerBot.Config
alias MessengerBot.Payload.MessageRequest
@path "/messages"
@doc """
Deliver request to facebook api
"""
@spec deliver(String.t(), MessageRequest.t()) ::
{:ok, Map.t()} | {:error, Map.t()}
def deliver(page_id, %MessageRequest{} = request, transaction_id \\ nil) do
transaction_id = if transaction_id, do: transaction_id, else: UUID.uuid4()
app_id = Config.app_id()
page_token = Config.page_token(page_id)
url = Client.url(@path, page_token)
case Client.post(url, request) do
%HTTPoison.Response{} = response ->
body = :jiffy.decode(response.body, [:return_maps])
report(:succeeded, {app_id, page_id, request, body}, transaction_id)
body
{:error, %HTTPoison.Response{} = response} ->
body = :jiffy.decode(response.body, [:return_maps])
report(:failed, {app_id, page_id, request, body}, transaction_id)
{:error, body}
{:error, error} ->
report(
:request_failed,
{app_id, page_id, request, error},
transaction_id
)
{:error, %{"request_error" => error}}
end
end
defp report(status, {app_id, page_id, request, response_body}, transaction_id) do
EventSource.notify %{
id: UUID.uuid4(),
topic: :"mb_message_sent_#{status}",
transaction_id: transaction_id
} do
{app_id, page_id, request, response_body}
end
end
end