Last active
April 16, 2022 22:28
-
-
Save ioquatix/c24f107e2cc7f48e571a37e8e93b0cda to your computer and use it in GitHub Desktop.
Make slack-api great again
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
# This is used in production, but I've extracted everything here, so this particular code is untested, but should work. | |
gem 'async-http-faraday' | |
gem 'async-websocket' | |
gem 'slack-api' | |
require 'slack' | |
require 'async/http/url_endpoint' | |
require 'async/websocket/client' | |
require 'async/http/faraday' | |
Faraday.default_adapter = :async_http | |
module Slack | |
class API | |
def realtime | |
response = post("rtm.start") | |
url = response["url"] | |
endpoint = Async::HTTP::URLEndpoint.parse(url) | |
peer = endpoint.connect | |
client = Async::WebSocket::Client.new(peer, url) | |
return client unless block_given? | |
begin | |
yield client | |
ensure | |
client.close | |
end | |
end | |
end | |
end | |
class Bot | |
def initialize(token: nil, channel: nil) | |
@token = token or raise ArgumentError, "No token specified" | |
@channel = channel or raise ArgumentError, "No channel specified" | |
@client = ::Slack::Client.new(token: @token, logger: LOGGER) | |
end | |
attr :client | |
def send_message(text, channel: @channel) | |
@client.chat_postMessage(channel: "#{@channel}", text: text, as_user: true) | |
end | |
end | |
class Fortune | |
def initialize | |
@bot = Bot.new(**options) | |
end | |
def call | |
@bot.client.realtime do |websocket| | |
while data = websocket.next_message | |
next unless text = data['text'] and text =~ /fortune/ | |
@bot.send_message `fortune` | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment