-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rb
executable file
·103 lines (86 loc) · 2.29 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#!/usr/bin/env ruby
require 'wits'
require 'dotenv'
require 'mailgun'
Dotenv.load
THRESHOLD_FOR_ALERT = 125
THRESHOLD_CHANGE = 25
SLEEP_TIME = 30
class PriceAlert
attr_accessor :last_alert
def initialize(output = nil)
@last_alert = nil
@mailgun = Mailgun::Client.new(ENV['MG_KEY'])
@output = !(output == "--no-output")
end
def get_last
prices = Wits.five_minute_prices(ENV['GIP_GXP'])
prices = prices[:prices]
prices.last
end
def alert(latest:, below: false, previous: nil)
if below
send_mail(title: '[FLKOF] Price recovered',
text: "Price has recovered from previously alerted <b>#{previous[:price]}</b>\n down to <b>#{latest[:price]}</b>")
@last_alert = nil
else
if previous
send_mail(title: "[FLKOF] [#{severity(latest[:price])}] Price has increased",
text: "Price has increased from <b>#{previous[:price]}</b>\nto <b>#{latest[:price]}</b>")
else
send_mail(title: "[FLKOF] [#{severity(latest[:price])}] Price has increased",
text: "Price alert for price at <b>#{latest[:price]}</b>")
end
@last_alert = latest
end
end
def severity(price)
case
when price > 300
"EXTREME"
when price > 200
"VERY HIGH"
when price > 150
"HIGH"
else
"CAUTION"
end
end
def send_mail(title:,text:)
log "\nSending email: #{title}\n\n#{text}\n"
@mailgun.send_message(ENV['MG_DOMAIN'],
{ from: ENV['FROM_EMAIL'],
to: ENV['TO_EMAIL'],
subject: title,
html: text })
end
def loop
Kernel.loop do
main
end
end
def log(text)
puts text if @output
end
def main
latest = get_last
if latest[:price] > THRESHOLD_FOR_ALERT
if last_alert.nil?
alert(latest: latest)
elsif (latest[:price] - last_alert[:price]) > THRESHOLD_CHANGE
alert(previous: last_alert, latest: latest)
end
else
if !last_alert.nil?
alert(below: true, previous: last_alert, latest: latest)
end
end
log latest
rescue Wits::Error::ClientError => e
log "Wits error: #{e.message}"
ensure
sleep SLEEP_TIME
end
end
pa = PriceAlert.new(ARGV[0])
pa.loop