-
Notifications
You must be signed in to change notification settings - Fork 2
/
jester.rb
executable file
·92 lines (88 loc) · 2.49 KB
/
jester.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
require 'rubygems'
require 'net/http'
require 'open-uri'
require 'json'
require 'cgi'
require 'digest'
require 'action_view'
require 'similar_text'
include ActionView::Helpers::DateHelper
class Jester
ENDPOINT = "jester"
VALID_WORDS = %w{jester}
RATE_LIMIT = 32 # seconds
CACHE_DURATION = 60 #seconds
APP_ROOT = File.expand_path(File.dirname(__FILE__))
CACHE_FILE = APP_ROOT+"/cache/"
attr_accessor :regex, :last_message, :chatter
def initialize
@regex = /^!(#{VALID_WORDS.join('|')})/i
@last_message = ""
end
def check(query)
m = trycheck(query)
if @last_message.similar(m) >= 97
# it's too similar. so it will get the bot banned
m = "Jester hasn\'t saved any more lives yet. "
m << ["SoDoge", "DaFeels", "NoTears", "SoSad"].sample
end
@last_message = m
return m
rescue Exception => e
puts e.message
puts e.backtrace.join("\n")
m = e.message
" OverRustle Tell hephaestus something broke. Exception: #{m.to_s}"
end
def trycheck(query)
output = "jester? he\'s a pretty cool guy. "
cached = getcached(ENDPOINT)
if cached.nil? or cached.has_key?("lives") == false
cached = {}
cached["lives"] = 0
setcached(ENDPOINT, cached)
end
# if jester is setting the number
parts = query.split(' ')
if @chatter == ENDPOINT and parts.length > 1
m_num = parts[1]
puts "jester is changing the count to: #{m_num}"
unless m_num.nil? or m_num.length == 0
# check if it's a number
if m_num =~ /\A\d+\z/
# set the new value
cached["lives"] = m_num.to_i
setcached(ENDPOINT, cached)
end
end
else
puts "someone else is calling this: #{@chatter}"
end
lives = cached["lives"]
output << "jester saved #{lives} lives. Klappa"
return output
end
# safe cache! won't die if the bot dies
def getcached(url)
_cached = instance_variable_get "@cached_#{hashed(url)}"
return _cached unless _cached.nil?
path = CACHE_FILE + "#{hashed(url)}.json"
if File.exists?(path)
f = File.open(path)
_cached = JSON.parse(f.read)
instance_variable_set("@cached_#{hashed(url)}", _cached)
return _cached
end
return nil
end
def setcached(url, jsn)
instance_variable_set("@cached_#{hashed(url)}", jsn)
path = CACHE_FILE + "#{hashed(url)}.json"
File.open(path, 'w') do |f2|
f2.puts JSON.unparse(jsn)
end
end
def hashed(url)
return Digest::MD5.hexdigest(url).to_s
end
end