Skip to content

Instantly share code, notes, and snippets.

@FerPerales
Forked from chischaschos/slack-bot.rb
Last active August 29, 2015 14:19
Show Gist options
  • Save FerPerales/754f20f3344909bb643b to your computer and use it in GitHub Desktop.
Save FerPerales/754f20f3344909bb643b to your computer and use it in GitHub Desktop.
require 'securerandom'
require 'em-http-request'
require 'pry-nav'
require 'json'
require 'faye/websocket'
require 'eventmachine'
require 'rest_client'
class WTV
def initialize(my_id, my_token)
@channels = []
@users = []
@channels_to_listen = []
@me = my_id
@token = my_token
end
def start
url = "https://slack.com/api/rtm.start"
response = RestClient.post url, token: @token
exit(0) unless response.code == 200
response_json = JSON.parse(response.body)
puts response_json['error'] && exit(0) unless response_json['ok']
loadChannels(response_json)
response_json['url']
end
def loadChannels(rtm_response)
@channels = rtm_response['channels']
@users = rtm_response['users']
setup_channels_to_listen
end
def setup_channels_to_listen
@channels_to_listen = @channels.find_all {|c| ['dota'].include? c['name']}
end
def listeningChannel?(channel_id)
@channels_to_listen.find_all {|c| c['id'] == channel_id}
end
def answer?(json_data)
return false unless listeningChannel?(json_data['channel'])
return false if is_it_me?(json_data['user'])
am_i_metioned?(json_data['text'])
end
def is_it_me?(id)
id == @me
end
def am_i_metioned?(text)
!text.match(/#{@me}/).nil?
end
def answer(json_data)
{
id: SecureRandom.uuid,
type: "message",
channel: json_data['channel'],
text: ['ah va cuentame mas', 'nah', 'sale pues', 'aguantame la mi', 'sabes, que dame 5 min', 'estoy TRABAJANDO como eres molesto', 'le entro si si si si si papa'].sample
}
end
end
EventMachine.error_handler { |e|
puts "Error raised during event loop: #{e.message}"
puts e.backtrace
}
EM.run {
wtv = WTV.new('XXXX', 'xoxasdasdasdas')
ws = Faye::WebSocket::Client.new(wtv.start)
ws.on :open do |event|
p [:open]
end
ws.on :message do |event|
json_data = JSON.parse(event.data)
puts "getting #{json_data}"
if json_data['type'] == 'message' && wtv.answer?(json_data)
puts "answering to #{json_data}"
ws.send wtv.answer(json_data).to_json
end
end
ws.on :close do |event|
p [:close, event.code, event.reason]
ws = nil
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment