Created
October 21, 2015 18:14
-
-
Save asterite/c42fcbe14ac711f6e79a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "json" | |
require "http/web_socket" | |
macro every(time_span) | |
spawn do | |
loop do | |
sleep({{time_span}}) | |
{{yield}} | |
end | |
end | |
end | |
token = "..." | |
ws_url = HTTP::Client.get("https://slack.com/api/rtm.start?token=#{token}") do |response| | |
pull = JSON::PullParser.new(response.body_io) | |
url = nil | |
pull.on_key!("url") do | |
url = pull.read_string | |
end | |
url || raise("websocket url not found") | |
end | |
ws = HTTP::WebSocket.open(ws_url) | |
session = HTTP::WebSocketHandler::WebSocketSession.new(ws) | |
incoming_messages = Channel(String).new(20) | |
outgoing_messages = Channel(String).new(20) | |
session.on_message do |message| | |
incoming_messages.send message | |
end | |
every s3.second do | |
outgoing_messages.send(%({ | |
"id": 1234, | |
"type": "ping", | |
"time": 1403299273342 | |
})) | |
end | |
spawn do | |
incoming_messages.each do |msg| | |
pp JSON.parse(msg) | |
end | |
end | |
spawn do | |
outgoing_messages.each do |msg| | |
ws.send msg, masked: true | |
end | |
end | |
puts "Running!" | |
session.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment