-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack-portal.rb
executable file
·73 lines (60 loc) · 2.82 KB
/
slack-portal.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env ruby
# See LICENSE for the needlessly onerous conditions this file is
# licensed under.
require 'rubygems'
require 'bundler/setup'
require 'slack-ruby-client'
# require 'dotenv'
# Dotenv.load
class Slack::RealTime::Client
def url_of data
"https://#{team['domain']}.slack.com/archives/" + channels[data['channel']].name + "/p" + data['ts'].delete('.')
end
end
Slack.configure do |config|
config.token = ENV['SLACK_API_TOKEN']
end
client = Slack::RealTime::Client.new
client.on :hello do
puts "Successfully connected, welcome '#{client.self['name']}' to the '#{client.team['name']}' team at https://#{client.team['domain']}.slack.com."
end
client.on :message do |data|
unless client.self['id'] == data['user']
case data['text']
when /^portal (from|to) <#(C[^|>]*?)(?:\|[^>]*)?>/
match = /^portal (from|to) <#(C[^|>]*?)(?:\|[^>]*)?>/.match(data['text'])
target_channel = match[2]
source_channel = data['channel']
if match[1] == 'from'
target_channel, source_channel = source_channel, target_channel
end
base_message = {unfurl_links: 'false', unfurl_media: 'false', as_user: 'true'}
begin
source_message = base_message.merge(channel: source_channel, text: "opening portal to <##{target_channel}>...")
source_response = client.web_client.chat_postMessage(source_message)
rescue Slack::Web::Api::Error => e
client.web_client.chat_postMessage base_message.merge(channel: source_channel, text: "Encountered error: #{e}, in: immediate reply. Restarting...")
next
end
begin
target_message = base_message.merge(channel: target_channel, text: "portal from <##{source_channel}>:\n :blueportal: #{client.url_of(source_response)}")
target_response = client.web_client.chat_postMessage(target_message)
rescue Slack::Web::Api::Error => e
if e.message == 'not_in_channel'
client.web_client.chat_postMessage base_message.merge(channel: source_channel, text: "Encountered error: #{e}. I haven't been invited to <##{target_channel}> yet. Use the command `/invite @portal_bot` in that channel to invite me. Restarting...", mrkdown: 'true')
next
else
client.web_client.chat_postMessage base_message.merge(channel: source_channel, text: "Encountered error: #{e}, in: post to target channel. Restarting...")
next
end
end
begin
client.web_client.chat_update(ts: source_response['ts'], channel: source_channel, text: "portal to <##{target_channel}>:\n :orangeportal: #{client.url_of(target_response)}")
rescue Slack::Web::Api::Error => e
client.web_client.chat_postMessage base_message.merge(channel: source_channel, text: "Encountered error: #{e}, in: update message. Restarting...")
next
end
end
end
end
client.start!