Skip to content

Instantly share code, notes, and snippets.

@rutan
Created Feb 7, 2017
Embed
What would you like to do?
Reacolle - Reaction Collection for Slack
# coding: utf-8
=begin
# Reacolle
"Reacolle" is the simple slack bot application written by Ruby.
When happen event `add_reaction` in any public channel, Reacolle post message to your channel.
## Required gems
gem 'slack-api'
gem 'dotenv' # optional
## Required ENV
ENV['SLACK_TOKEN'] = 'Your Slack bot application token'
ENV['TEAM_DOMAIN'] = 'Your Slack team domain ( example.slack.com )'
## Usage
$ gem install slack-api
$ SLACK_TOKEN='xxxxx' TEAM_DOMAIN='example.slack.com' ruby reacolle.rb
## License
MIT
=end
require 'slack'
begin
require 'dotenv'
Dotenv.load
rescue
end
# ------------------------------------------------------------------------------
Slack.configure do |config|
config.token = ENV['SLACK_TOKEN']
end
# ------------------------------------------------------------------------------
class Reacolle
def initialize(settings = {})
@client = Slack::Web::Client.new
@rtm_client = Slack::RealTime::Client.new
@settings = settings.map do |emoji, channels|
[emoji.to_s, channels.map { |c| resolve_channel(c) }.uniq]
end.to_h
@uid_caches = []
end
attr_reader :client, :rtm_client
def start!
rtm_client.on :reaction_added do |m|
if can_notify?(m['item'])
uid = uid_from_item(m['item'])
emoji = m['reaction']
channels = @settings[emoji]
if channels && !@uid_caches.include?(uid)
@uid_caches.push(uid)
channels.each do |channel|
client.chat_postMessage(
channel: channel,
text: ":#{emoji}: https://#{ENV['TEAM_DOMAIN']}/archives/#{channel_name(m['item']['channel'])}/p#{m['item']['ts'].gsub('.', '')}",
parse: 'full',
unfurl_links: true,
unfurl_media: true,
as_user: true
)
end
end
end
end
rtm_client.start!
end
private
def can_notify?(item)
case item['type']
when 'message'
item['channel'].index('C') == 0
end
end
def uid_from_item(item)
"#{item['channel']}-#{item['ts']}"
end
def resolve_channel(name)
list = client.channels_list.channels
channel = list.find { |n| n.name == name }
channel ? channel.id : nil
end
def channel_name(uid)
list = client.channels_list.channels
channel = list.find { |n| n.id == uid }
channel ? channel.name : nil
end
end
# ------------------------------------------------------------------------------
Reacolle.new({
# ex) post to #random when receive `:ok_woman:` reaction
ok_woman: ['random'],
}).start!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment