Skip to content

Instantly share code, notes, and snippets.

@chrisbloom7
Last active August 21, 2023 08:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbloom7/52bc954b4df09b9cb829a73cfd5466c0 to your computer and use it in GitHub Desktop.
Save chrisbloom7/52bc954b4df09b9cb829a73cfd5466c0 to your computer and use it in GitHub Desktop.
Basic implementation of a websocket connector for Slack using slack-ruby-client and async-websockets gems
# frozen_string_literal: true
# Basic implementation of a websocket connector for Slack using the slack-ruby-client gem
#
# Run this rake task in a virtual container that is set to automatically restart on failure; this
# will help deal with disconnects from Slack since socket URLs are temporary.
# https://api.slack.com/apis/connections/socket-implement#disconnect
#
# This rake task can be called in multiple virtual containers to help with resilliancy and rolling restarts
# https://api.slack.com/apis/connections/socket-implement#connections
require "async"
require "slack_ruby_client"
require "async/io/stream"
require "async/http/endpoint"
require "async/websocket/client"
namespace :slack do
namespace :socket_mode do
desc "Start the socket mode client"
task :start, [:debug] => [:environment] do |_task, args|
# Get a websocket URL
# https://api.slack.com/apis/connections/socket-implement#call
client = Slack::Web::Client.new
url = client.apps_connections_open.url
url += "&debug_reconnects=true" if args[:debug].present?
endpoint = Async::HTTP::Endpoint.parse(url)
# Start the async client and open a connection to the websocket URL
# https://api.slack.com/apis/connections/socket-implement#connect
Async do
Async::WebSocket::Client.connect(endpoint) do |connection|
while (message = connection.read)
if message[:envelope_id]
# Acknowledge receipt of message
# https://api.slack.com/apis/connections/socket-implement#acknowledge
connection.write({ envelope_id: message[:envelope_id] })
connection.flush
end
# Handle your events here
# https://api.slack.com/apis/connections/socket-implement#events
# ...
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment