Packages

an Elixir client library for IFTTT's Webhooks

Current section

Files

Jump to
ifttt_webhook lib ifttt_webhook api.ex
Raw

lib/ifttt_webhook/api.ex

defmodule IftttWebhook.API do
@moduledoc """
Handles the sending of webhooks to IFTTT
"""
@httpotion_module Application.get_env(:ifttt_webhook, :httpotion_module, HTTPotion)
@doc """
sends a webhook to IFTTT using `HTTPotion`, values must be a list of up to 3 values.
More values will be ommitted when sending the request.
## Examples
iex> IftttWebhook.API.send("my-secret-key", "my-event", [])
{:ok, "Congratulations! You've fired the my-event event"}
iex> IftttWebhook.API.send("my-secret-key", "my-event-with-body", [13.0])
{:ok, "Congratulations! You've fired the my-event-with-body event"}
iex> IftttWebhook.API.send("wrong-key", "my-event", [])
{:error, :invalid_key}
iex> IftttWebhook.API.send("unknown-error-key", "my-event", [])
{:error, :unknown}
"""
@spec send(binary, binary, list) ::
{:ok, binary} |
{:error, :invalid_key} |
{:error, :unknown}
def send(key, event, values) when is_list(values) do
response = @httpotion_module.post(
build_url(key, event),
[body: build_body(values), headers: ['Content-type': "application/json"]]
)
case response do
%HTTPotion.Response{status_code: 200, body: body} ->
{:ok, body}
%HTTPotion.Response{status_code: 401} ->
{:error, :invalid_key}
_ ->
{:error, :unknown}
end
end
@doc """
Builds the URL to access IFTTT
## Examples
iex> IftttWebhook.API.build_url("foo", "bar")
"https://maker.ifttt.com/trigger/bar/with/key/foo"
"""
def build_url(key, event) do
"https://maker.ifttt.com/trigger/#{event}/with/key/#{key}"
end
defp build_body(values) do
["value1", "value2", "value3"]
|> Enum.zip(Enum.take(values, 3))
|> Enum.into(%{})
|> Poison.encode!()
end
end