Skip to content

Instantly share code, notes, and snippets.

@drewr
Created January 14, 2018 05:46
Show Gist options
  • Select an option

  • Save drewr/6a7f02edef26bf0e2ddb715608acafd5 to your computer and use it in GitHub Desktop.

Select an option

Save drewr/6a7f02edef26bf0e2ddb715608acafd5 to your computer and use it in GitHub Desktop.
Slack websocket experiment
(ns shia.core
(:require [cheshire.core :as json]
[clj-http.client :as http]
[clojure.spec.alpha :as s])
(:import (org.java_websocket.client WebSocketClient)
(java.net URI)))
(s/def :rtm/connect (s/keys :req-un [::ok ::self ::team ::url]))
(def ord (atom 0))
(defn make-message [chan text]
(json/encode
{:id (swap! ord inc)
:channel chan
:type "message"
:text text}))
(defn send-message [conn chan text]
(.send conn (make-message chan text)))
(defn make-periodic [conn ms]
(fn []
(while [true]
(try
(when (.isOpen conn)
(send-message
conn "D8TE6HMBR" "yo"))
(catch Exception e
(println e)))
(Thread/sleep ms))))
(defn on-message [conn json]
(let [msg (json/decode json true)]
(println "------------------")
(clojure.pprint/pprint msg)
(case (:text msg)
"speak" (send-message conn (:channel msg) "I spoke!")
:default)
))
(defn rtm-connect
[tok]
(let [resp (->
(http/get "https://slack.com/api/rtm.connect"
{:query-params {"token" tok}
:as :json})
:body)]
(if (= ::s/invalid (s/conform :rtm/connect resp))
(throw (ex-info "bad response" (s/explain-data :rtm/connect resp)))
(:url resp))))
(defn set-topic
[tok chan topic]
(->
(http/get "https://slack.com/api/channels.setTopic"
{:query-params {"token" tok
"channel" chan
"topic" topic}
:as :json})
:body))
(defn make-client
[tok]
(let [wss (URI. (rtm-connect tok))]
(proxy [WebSocketClient] [wss]
(onOpen [_]
(println "opened"))
(onClose [code reason remote]
(println "closed:" code reason remote))
(onError [ex]
(println ex))
(onMessage [msg]
(#'on-message this msg))
)))
(defn start
[tok]
(let [client (make-client tok)]
#_(.start
(Thread. (make-periodic client 10000) "timer"))
(doto client
.connect)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment