Skip to content

Latest commit

 

History

History
79 lines (53 loc) · 1.36 KB

File metadata and controls

79 lines (53 loc) · 1.36 KB

RTM API Basics

RealTime Messaging API reference is here.

Make a Team

Sign up at slack.com, my team is dblockdotorg.slack.com.

Create a New Bot Integration

This is something done in Slack, under integrations. Create a new bot, and note its API token.

Gemfile

source 'http://rubygems.org'

gem 'http'
gem 'faye-websocket'
gem 'eventmachine'

Start

require 'http'
require 'json'

rc = JSON.parse HTTP.post("https://slack.com/api/rtm.start", params: {
  token: ENV['SLACK_API_TOKEN'],
})

puts rc['url']
wss://ms364.slack-msgs.com/websocket/...

See Events

require 'faye/websocket'
require 'eventmachine'

EM.run {
  ws = Faye::WebSocket::Client.new(url)

  ws.on :open do |event|
    p [:open]
  end

  ws.on :message do |event|
    p [:message, JSON.parse(event.data)]
  end

  ws.on :close do |event|
    p [:close, event.code, event.reason]
    ws = nil
  end
}

Say Hi Back

ws.on :message do |event|
  data = JSON.parse(event.data) if event && event.data

  if data && data['type'] == 'message' && data['text'] == 'hi'
    ws.send({ type: 'message', text: "hi <@#{data['user']}>", channel: data['channel'] }.to_json)
  end
end