|
| 1 | +defmodule Exbot do |
| 2 | + |
| 3 | + defp start!(token) do |
| 4 | + {:ok, response} = HTTPoison.get "https://slack.com/api/rtm.start?token=" <> token, [], timeout: 10000 |
| 5 | + response |
| 6 | + end |
| 7 | + |
| 8 | + defp parse(response) do |
| 9 | + {:ok, json} = response.body |
| 10 | + |> Poison.Parser.parse |
| 11 | + json |
| 12 | + end |
| 13 | + |
| 14 | + defp get_config(json) do |
| 15 | + <<bot_id::size(72)>> = json["self"]["id"] |
| 16 | + %{url: json["url"], bot_id: bot_id} |
| 17 | + end |
| 18 | + |
| 19 | + defp connect(%{url: url} = state) do |
| 20 | + uri = URI.parse url |
| 21 | + {:ok, socket} = Socket.Web.connect uri.host, path: uri.path, secure: true |
| 22 | + state |
| 23 | + |> Map.put(:socket, socket) |
| 24 | + |> Map.put(:msg_id, 1) |
| 25 | + end |
| 26 | + |
| 27 | + defp send_text(socket, id, channel, text) do |
| 28 | + socket |
| 29 | + |> Socket.Web.send! {:text, """ |
| 30 | + { |
| 31 | + "id": #{id}, |
| 32 | + "type": "message", |
| 33 | + "channel": "#{channel}", |
| 34 | + "text": "#{text}" |
| 35 | + } |
| 36 | + """ |
| 37 | + } |
| 38 | + end |
| 39 | + |
| 40 | + defp handle(state) do |
| 41 | + state.socket |
| 42 | + |> Socket.Web.recv! |
| 43 | + |> process(state) |
| 44 | + end |
| 45 | + |
| 46 | + defp process({:text, raw_json}, state) do |
| 47 | + raw_json |
| 48 | + |> Poison.Parser.parse! |
| 49 | + |> log |
| 50 | + |> do_process(state) |
| 51 | + |> handle |
| 52 | + end |
| 53 | + |
| 54 | + defp log(msg) do |
| 55 | + IO.inspect(msg) |
| 56 | + msg |
| 57 | + end |
| 58 | + |
| 59 | + defp process(_msg, state) do |
| 60 | + handle(state) |
| 61 | + end |
| 62 | + |
| 63 | + defp do_process(%{ |
| 64 | + "type" => "message", |
| 65 | + "channel" => channel, |
| 66 | + "user" => user, |
| 67 | + "text" => << ?<, ?@, bot_id::size(72), ?>, ?: >> <> text}, |
| 68 | + %{socket: socket, bot_id: bot_id, msg_id: msg_id} = state) do |
| 69 | + send_text(socket, msg_id, channel, "<@#{user}>:#{text}") |
| 70 | + %{state | msg_id: msg_id+1} |
| 71 | + end |
| 72 | + |
| 73 | + defp do_process(_json, state) do |
| 74 | + state |
| 75 | + end |
| 76 | + |
| 77 | + def run(token) do |
| 78 | + token |
| 79 | + |> start! |
| 80 | + |> parse |
| 81 | + |> get_config |
| 82 | + |> connect |
| 83 | + |> handle |
| 84 | + end |
| 85 | + |
| 86 | +end |
0 commit comments