]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/markov.rb
8abf0e584902f32dec8711ceeaf27c9975458bca
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / markov.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Markov plugin
5 #
6 # Author:: Tom Gilbert <tom@linuxbrit.co.uk>
7 # Copyright:: (C) 2005 Tom Gilbert
8 #
9 # Contribute to chat with random phrases built from word sequences learned
10 # by listening to chat
11
12 class MarkovPlugin < Plugin
13   Config.register Config::BooleanValue.new('markov.enabled',
14     :default => false,
15     :desc => "Enable and disable the plugin")
16   Config.register Config::IntegerValue.new('markov.probability',
17     :default => 25,
18     :validate => Proc.new { |v| (0..100).include? v },
19     :desc => "Percentage chance of markov plugin chipping in")
20   Config.register Config::ArrayValue.new('markov.ignore_users',
21     :default => [],
22     :desc => "Hostmasks of users to be ignored")
23
24   def initialize
25     super
26     @registry.set_default([])
27     if @registry.has_key?('enabled')
28       @bot.config['markov.enabled'] = @registry['enabled']
29       @registry.delete('enabled')
30     end
31     if @registry.has_key?('probability')
32       @bot.config['markov.probability'] = @registry['probability']
33       @registry.delete('probability')
34     end
35     @learning_queue = Queue.new
36     @learning_thread = Thread.new do
37       while s = @learning_queue.pop
38         learn s
39         sleep 0.5
40       end
41     end
42   end
43
44   def cleanup
45     debug 'closing learning thread'
46     @learning_queue.push nil
47     @learning_thread.join
48     debug 'learning thread closed'
49   end
50
51   def generate_string(word1, word2)
52     # limit to max of 50 words
53     output = word1 + " " + word2
54
55     # try to avoid :nonword in the first iteration
56     wordlist = @registry["#{word1} #{word2}"]
57     wordlist.delete(:nonword)
58     if not wordlist.empty?
59       word3 = wordlist[rand(wordlist.length)]
60       output = output + " " + word3
61       word1, word2 = word2, word3
62     end
63
64     49.times do
65       wordlist = @registry["#{word1} #{word2}"]
66       break if wordlist.empty?
67       word3 = wordlist[rand(wordlist.length)]
68       break if word3 == :nonword
69       output = output + " " + word3
70       word1, word2 = word2, word3
71     end
72     return output
73   end
74
75   def help(plugin, topic="")
76     "markov plugin: listens to chat to build a markov chain, with which it can (perhaps) attempt to (inanely) contribute to 'discussion'. Sort of.. Will get a *lot* better after listening to a lot of chat. usage: 'markov' to attempt to say something relevant to the last line of chat, if it can.  other options to markov: 'ignore' => ignore a hostmask (accept no input), 'status' => show current status, 'probability [<chance>]' => set the % chance of rbot responding to input, or display the current probability, 'chat' => try and say something intelligent, 'chat about <foo> <bar>' => riff on a word pair (if possible)"
77   end
78
79   def clean_str(s)
80     str = s.dup
81     str.gsub!(/^\S+[:,;]/, "")
82     str.gsub!(/\s{2,}/, ' ') # fix for two or more spaces
83     return str.strip
84   end
85
86   def probability?
87     return @bot.config['markov.probability']
88   end
89
90   def status(m,params)
91     if @bot.config['markov.enabled']
92       m.reply "markov is currently enabled, #{probability?}% chance of chipping in"
93     else
94       m.reply "markov is currently disabled"
95     end
96   end
97
98   def ignore?(user=nil)
99     return false unless user
100     @bot.config['markov.ignore_users'].each do |mask|
101       return true if user.matches?(mask)
102     end
103     return false
104   end
105
106   def ignore(m, params)
107     action = params[:action]
108     user = params[:option]
109     case action
110     when 'remove':
111       if @bot.config['markov.ignore_users'].include? user
112         s = @bot.config['markov.ignore_users']
113         s.delete user
114         @bot.config['ignore_users'] = s
115         m.reply "#{user} removed"
116       else
117         m.reply "not found in list"
118       end
119     when 'add':
120       if user
121         if @bot.config['markov.ignore_users'].include?(user)
122           m.reply "#{user} already in list"
123         else
124           @bot.config['markov.ignore_users'] = @bot.config['markov.ignore_users'].push user
125           m.reply "#{user} added to markov ignore list"
126         end
127       else
128         m.reply "give the name of a person to ignore"
129       end
130     when 'list':
131       m.reply "I'm ignoring #{@bot.config['markov.ignore_users'].join(", ")}"
132     else
133       m.reply "have markov ignore the input from a hostmask.  usage: markov ignore add <mask>; markov ignore remove <mask>; markov ignore list"
134     end
135   end
136
137   def enable(m, params)
138     @bot.config['markov.enabled'] = true
139     m.okay
140   end
141
142   def probability(m, params)
143     if params[:probability]
144       @bot.config['markov.probability'] = params[:probability].to_i
145       m.okay
146     else
147       m.reply _("markov has a %{prob}% chance of chipping in") % { :prob => probability? }
148     end
149   end
150
151   def disable(m, params)
152     @bot.config['markov.enabled'] = false
153     m.okay
154   end
155
156   def should_talk
157     return false unless @bot.config['markov.enabled']
158     prob = probability?
159     return true if prob > rand(100)
160     return false
161   end
162
163   def delay
164     1 + rand(5)
165   end
166
167   def random_markov(m, message)
168     return unless should_talk
169
170     word1, word2 = message.split(/\s+/)
171     line = generate_string(word1, word2)
172     return unless line
173     return if line == message
174     @bot.timer.add_once(delay) {
175       m.reply line
176     }
177   end
178
179   def chat(m, params)
180     line = generate_string(params[:seed1], params[:seed2])
181     if line != "#{params[:seed1]} #{params[:seed2]}"
182       m.reply line 
183     else
184       m.reply "I can't :("
185     end
186   end
187
188   def rand_chat(m, params)
189     # pick a random pair from the db and go from there
190     word1, word2 = :nonword, :nonword
191     output = Array.new
192     50.times do
193       wordlist = @registry["#{word1} #{word2}"]
194       break if wordlist.empty?
195       word3 = wordlist[rand(wordlist.length)]
196       break if word3 == :nonword
197       output << word3
198       word1, word2 = word2, word3
199     end
200     if output.length > 1
201       m.reply output.join(" ")
202     else
203       m.reply "I can't :("
204     end
205   end
206   
207   def message(m)
208     return unless m.public?
209     return if m.address?
210     return if ignore? m.source
211
212     # in channel message, the kind we are interested in
213     message = clean_str m.plainmessage
214
215     if m.action?
216       message = "#{m.sourcenick} #{message}"
217     end
218     
219     @learning_queue.push message
220     random_markov(m, message) unless m.replied?
221   end
222
223   def learn(message)
224     # debug "learning #{message}"
225     wordlist = message.split(/\s+/)
226     return unless wordlist.length >= 2
227     word1, word2 = :nonword, :nonword
228     wordlist.each do |word3|
229       k = "#{word1} #{word2}"
230       @registry[k] = @registry[k].push(word3)
231       word1, word2 = word2, word3
232     end
233     k = "#{word1} #{word2}"
234     @registry[k] = @registry[k].push(:nonword)
235   end
236 end
237
238 plugin = MarkovPlugin.new
239 plugin.map 'markov ignore :action :option', :action => "ignore"
240 plugin.map 'markov ignore :action', :action => "ignore"
241 plugin.map 'markov ignore', :action => "ignore"
242 plugin.map 'markov enable', :action => "enable"
243 plugin.map 'markov disable', :action => "disable"
244 plugin.map 'markov status', :action => "status"
245 plugin.map 'chat about :seed1 :seed2', :action => "chat"
246 plugin.map 'chat', :action => "rand_chat"
247 plugin.map 'markov probability [:probability]', :action => "probability",
248            :requirements => {:probability => /^\d+%?$/}