Skip to content

Instantly share code, notes, and snippets.

@paralleltree
Created March 21, 2019 06:26
Show Gist options
  • Save paralleltree/609f62f954469202e6fc99d74d664913 to your computer and use it in GitHub Desktop.
Save paralleltree/609f62f954469202e6fc99d74d664913 to your computer and use it in GitHub Desktop.
require 'json'
require 'open-uri'
require 'net/http'
require 'slack-ruby-client'
API_BASE = ENV['API_BASE']
SLACK_TOKEN = ENV['SLACK_TOKEN']
Slack.configure { |config| config.token = SLACK_TOKEN }
client = Slack::RealTime::Client.new
def aircon(work: false, mode: :auto, temp: 0)
url = URI.parse(File.join(API_BASE, 'aircon'))
req = Net::HTTP::Put.new(url.path)
data = { mode: mode, temp: temp }
data[:work] = '1' if work
req.set_form_data(data)
res = Net::HTTP.new(url.host, url.port).start { |http| http.request(req) }
return res.code.to_i
end
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|
puts data
next unless data.type == 'message'
next if data.subtype == 'bot_message' # skip messages from bots
next if data.user == client.self.id # skip self messages
next unless data.reply_to.nil? || data.text =~ /<@#{client.self.id}>/ # skip replies
if data.channel.start_with?('D')
# DM
case data.text
when /気温|温度|何度/
temp = open(File.join(API_BASE, '/env')) { |f| JSON.parse(f.read)['temp'].to_f }
msg = [
'寒い……寒いです……。', # -7
'ちょっと寒いです。', # 7-16
'ちょうどいい感じです。', # 17-26
'暑いですよ……。', # 27-
]
index = [[((temp + 3) / 10).to_i, 0].max, msg.count - 1].min
client.message(channel: data.channel, text: "#{'%.1f' % temp}度だそうです。#{msg[index]}")
when /エアコン|[冷暖]房|除湿|ドライ/
mdic = { auto: '自動', cool: '冷房', heat: '暖房', dry: 'ドライ' }
mode = case data.text
when /冷房/ then :cool
when /暖房/ then :heat
when /除湿|ドライ/ then :dry
else :auto
end
temp = data.text.match(/-?\d+(?=度)/) || { auto: 0, cool: 28, heat: 21, dry: 0 }[mode]
res = case data.text
when /つけ|オン|入れ|on/i
comments = %w(しょうがないですね。)# 仕方ないですね……。 あまりこき使わないでください。)
client.message(channel: data.channel, text: "#{comments.sample}#{temp}度の#{mdic[mode]}でエアコンつけておきますよ。")
aircon(work: true, mode: mode, temp: temp)
when /消し|切っ|オフ|止め|off/i
client.message(channel: data.channel, text: 'わかりました。切っておきますね。')
aircon(work: false, mode: mode, temp: temp)
else nil
end
next if res.nil?
client.message(channel: data.channel, text: 'あれ?リモコンが動かないみたいです。') unless res == 200
end
end
end
client.on :close do
puts "Client is about to disconnect"
end
client.on :closed do
puts "Client has disconnected successfully!"
end
client.start!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment