-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathrtm.ex
More file actions
47 lines (38 loc) · 1.27 KB
/
rtm.ex
File metadata and controls
47 lines (38 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
defmodule Slack.JsonDecodeError do
@moduledoc false
defexception [:reason, :string]
def message(%Slack.JsonDecodeError{reason: reason, string: string}) do
"Poison could not decode string for reason: `:#{reason}`, string given:\n#{string}"
end
end
defmodule Slack.Rtm do
@moduledoc false
def start(token) do
with url <- slack_url(token),
headers <- [],
options <- Application.get_env(:slack, :web_http_client_opts, []) do
url
|> HTTPoison.get(headers, options)
|> handle_response()
end
end
defp handle_response({:ok, %HTTPoison.Response{body: body}}) do
case Jason.decode!(body, keys: :atoms) do
%{ok: true} = json ->
{:ok, json}
%{error: reason} ->
{:error, "Slack API returned an error `#{reason}.\n Response: #{body}"}
_ ->
{:error, "Invalid RTM response"}
end
rescue
error in Jason.DecodeError ->
%Jason.DecodeError{data: reason, position: _, token: _} = error
{:error, %Slack.JsonDecodeError{reason: reason, string: body}}
end
defp handle_response(error), do: error
defp slack_url(token) do
Application.get_env(:slack, :url, "https://slack.com") <>
"/api/rtm.start?token=#{token}&batch_presence_aware=true&presence_sub=true"
end
end