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
"""
alias MessengerBot.Client
alias MessengerBot.Config
alias MessengerBot.Payload.MessageRequest
alias EventBus.Model.Event
@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.uuid1()
page_token = Config.page_token(page_id)
url = Client.url(@path, page_token)
case Client.post(url, request) do
%HTTPoison.Response{} = response ->
process_response(transaction_id, page_id, request, response)
{:error, err} ->
report(:failed, transaction_id, page_id, request, %{"error" => err})
{:error, err}
end
end
defp process_response(transaction_id, page_id, request, response) do
body = Poison.decode!(response.body)
case body do
%{"error" => _} ->
report(:failed, transaction_id, page_id, request, body)
_ ->
report(:succeeded, transaction_id, page_id, request, body)
end
end
defp report(status, transaction_id, page_id, request, response_body) do
event = %Event{id: UUID.uuid1(), topic: :"mb_message_sent_#{status}",
data: {page_id, request, response_body}, transaction_id: transaction_id}
EventBus.notify(event)
end
end