~pixelinc/Slack-RTM

13686dad7b6a7402664f4637b07f3a2162e9f4d5 — PixeL 4 years ago a28825a
Add more rest methods

- Added `get_channel`, `get_user`
- Auto add token to request params
3 files changed, 44 insertions(+), 9 deletions(-)

M src/slack_rtm/mappings/rest.cr
M src/slack_rtm/mappings/user.cr
M src/slack_rtm/rest.cr
M src/slack_rtm/mappings/rest.cr => src/slack_rtm/mappings/rest.cr +2 -0
@@ 6,6 6,8 @@ module Slack
      getter ok : Bool
      getter error : String?
      getter url : String?
      getter channels : Array(Channel)?
      getter users : Array(User)?
    end
  end
end

M src/slack_rtm/mappings/user.cr => src/slack_rtm/mappings/user.cr +5 -5
@@ 4,11 4,11 @@ module Slack

    getter id : String
    getter name : String
    getter real_name : String
    getter is_admin : Bool
    getter is_owner : Bool
    getter real_name : String?
    getter is_admin : Bool?
    getter is_owner : Bool?
    getter is_bot : Bool
    getter is_app_user : Bool
    getter has_2fa : Bool
    getter is_app_user : Bool?
    getter has_2fa : Bool?
  end
end

M src/slack_rtm/rest.cr => src/slack_rtm/rest.cr +37 -4
@@ 7,23 7,56 @@ module Slack
    SSL_CONTEXT = OpenSSL::SSL::Context::Client.new
    API_BASE    = "https://slack.com/api"

    def request(method, path, headers, body)
      response = HTTP::Client.exec(method: method, url: API_BASE + path, headers: headers, body: body, tls: SSL_CONTEXT)
    def request(method, path, headers, params, body)
      unless params.has_key?("token")
        params["token"] = @token
      end

      response = HTTP::Client.exec(method: method, url: "#{API_BASE}#{path}?#{params}", headers: headers, body: body, tls: SSL_CONTEXT)
      Log.info { "[HTTP IN] #{response.status_code} #{response.status_message} (#{response.body.size} bytes)" }
      Log.debug { "[HTTP IN] BODY: #{response.body}" }

      response.not_nil!
      response
    end

    def get_websocket_url
      response = request(
        "GET",
        "/rtm.start?token=#{@token}",
        "/rtm.start",
        HTTP::Headers.new,
        HTTP::Params.new,
        nil
      )

      RTMURLResponse.from_json(response.body)
    end

    def get_channel(id : String)
      response = request(
        "GET",
        "/conversations.info",
        HTTP::Headers.new,
        HTTP::Params{
          "channel" => id,
        },
        nil
      )

      Channel.from_json(response.body)
    end

    def get_user(id : String)
      response = request(
        "GET",
        "/users.info",
        HTTP::Headers.new,
        HTTP::Params{
          "user" => id,
        },
        nil
      )

      User.from_json(response.body)
    end
  end
end