Skip to content

Commit

Permalink
Now the bot revive when RTM client has disconnected.
Browse files Browse the repository at this point in the history
  • Loading branch information
ikasam committed Mar 3, 2018
1 parent 73bcb9c commit ac81f51
Showing 1 changed file with 33 additions and 28 deletions.
61 changes: 33 additions & 28 deletions slack-bot.rb
Expand Up @@ -12,36 +12,41 @@
end

# Get IDs via Web API
client = Slack::Web::Client.new
CHANNEL_ID = client.channels_info(channel: CHANNEL).channel.id
CHANNEL_OPS_ID = client.channels_info(channel: CHANNEL_OPS).channel.id unless CHANNEL_OPS.nil?

# RTM Connection
client = Slack::RealTime::Client.new

client.on :hello do
BOT_USER_ID = client.self.id
puts "Successfully connected, welcome '#{client.self.name}' to the '#{client.team.name}' team at https://#{client.team.domain}.slack.com."
client.message channel: CHANNEL_OPS_ID, text: "RTM Connected: keyword=#{KEYWORD} in <##{CHANNEL_ID}>" unless CHANNEL_OPS_ID.nil? or KEYWORD.nil?
end

client.on :message do |data|
if (not KEYWORD.empty?) and data.channel == CHANNEL_ID
case data.text
when /#{KEYWORD}/ then
client.message channel: data.channel, text: "<!channel> yo!"
when /#{BOT_USER_ID}/ then
client.message channel: data.channel, text: "<@#{data.user}> Hi."
WEB_CLIENT = Slack::Web::Client.new
CHANNEL_ID = WEB_CLIENT.channels_info(channel: CHANNEL).channel.id
CHANNEL_OPS_ID = WEB_CLIENT.channels_info(channel: CHANNEL_OPS).channel.id unless CHANNEL_OPS.nil?

def start!
# RTM Connection
client = Slack::RealTime::Client.new

client.on :hello do
@bot_user_id = client.self.id
puts "Successfully connected, welcome '#{client.self.name}' to the '#{client.team.name}' team at https://#{client.team.domain}.slack.com."
WEB_CLIENT.chat_postMessage channel: CHANNEL_OPS_ID, text: "RTM Connected: keyword=#{KEYWORD} in <##{CHANNEL_ID}>", as_user: false unless CHANNEL_OPS_ID.nil? or KEYWORD.nil?
end

client.on :message do |data|
if (not KEYWORD.empty?) and data.channel == CHANNEL_ID
case data.text
when /#{KEYWORD}/ then
WEB_CLIENT.chat_postMessage channel: data.channel, text: "<!channel> yo!", as_user: false
when /#{@bot_user_id}/ then
WEB_CLIENT.chat_postMessage channel: data.channel, text: "<@#{data.user}> Hi.", as_user: false
end
end
end
end

client.on :close do |_data|
puts "Client is about to disconnect"
end

client.on :close do |_data|
puts "Client is about to disconnect"
end

client.on :closed do |_data|
puts "Client has disconnected successfully!"
start!
end

client.on :closed do |_data|
puts "Client has disconnected successfully!"
client.start!
end

client.start!
start!

0 comments on commit ac81f51

Please sign in to comment.