4 # :title: Markov plugin
6 # Author:: Tom Gilbert <tom@linuxbrit.co.uk>
7 # Copyright:: (C) 2005 Tom Gilbert
9 # Contribute to chat with random phrases built from word sequences learned
10 # by listening to chat
12 class MarkovPlugin < Plugin
13 Config.register Config::BooleanValue.new('markov.enabled',
15 :desc => "Enable and disable the plugin")
16 Config.register Config::IntegerValue.new('markov.probability',
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',
22 :desc => "Hostmasks and channel names markov should NOT learn from (e.g. idiot*!*@*, #privchan).")
23 Config.register Config::ArrayValue.new('markov.readonly',
25 :desc => "Hostmasks and channel names markov should NOT talk to (e.g. idiot*!*@*, #privchan).")
26 Config.register Config::IntegerValue.new('markov.max_words',
28 :validate => Proc.new { |v| (0..100).include? v },
29 :desc => "Maximum number of words the bot should put in a sentence")
30 Config.register Config::IntegerValue.new('markov.learn_delay',
32 :validate => Proc.new { |v| v >= 0 },
33 :desc => "Time the learning thread spends sleeping after learning a line. If set to zero, learning from files can be very CPU intensive, but also faster.")
34 Config.register Config::IntegerValue.new('markov.delay',
36 :validate => Proc.new { |v| v >= 0 },
37 :desc => "Wait short time before contributing to conversation.")
41 # upgrade a registry entry from 0.9.14 and earlier, converting the Arrays
42 # into Hashes of weights
43 def upgrade_entry(k, logfile)
44 logfile.puts "\t#{k.inspect}"
50 # wipe the current key
55 logfile.puts "\tEMPTY"
60 logfile.puts "\t#{ar.inspect}"
62 # re-encode key to UTF-8 and cleanup as needed
63 words = k.split.map do |w|
64 BasicUserMessage.strip_formatting(
65 @bot.socket.filter.in(w)
69 # old import that failed to split properly?
70 if words.length == 1 and words.first.include? '/'
73 at = unsplit.rindex('/')
74 words = [unsplit[0,at], unsplit[at+1..-1]]
77 # if any of the re-split/re-encoded words have spaces,
78 # or are empty, we would get a chain we can't convert,
80 if words.first.empty? or words.first.include?(' ') or
81 words.last.empty? or words.last.include?(' ')
82 logfile.puts "\tSKIPPED"
86 # former unclean CTCP, we can't convert this
87 if words.first[0] == 1
88 logfile.puts "\tSKIPPED"
92 # nonword CTCP => SKIP
93 # someword CTCP => nonword someword
95 if words.first == "nonword"
96 logfile.puts "\tSKIPPED"
103 # intern the old keys
105 ['nonword', MARKER].include?(w) ? MARKER : w.chomp("\001")
108 newkey = words.join(' ')
109 logfile.puts "\t#{newkey.inspect}"
111 # the new key exists already, so we want to merge
112 if k != newkey and @registry.key? newkey
113 ar2 = @registry[newkey]
114 logfile.puts "\tMERGE"
115 logfile.puts "\t\t#{ar2.inspect}"
117 # and get rid of the key
118 @registry.delete(newkey)
124 @chains_mutex.synchronize do
125 if @chains.key? newkey
126 ar2 = @chains[newkey]
137 # we convert old words into UTF-8, cleanup, resplit if needed,
138 # and only get the first word. we may lose some data for old
139 # missplits, but this is the best we can do
140 w = BasicUserMessage.strip_formatting(
141 @bot.socket.filter.in(word).split.first
144 when /^\001\S+$/, "\001", ""
145 # former unclean CTCP or end of CTCP
148 # intern after clearing leftover end-of-actions if present
149 sym = w.chomp("\001").intern
156 logfile.puts "\tSKIPPED"
159 logfile.puts "\t#{[total, hash].inspect}"
160 @chains[newkey] = [total, hash]
165 # we load all the keys and then iterate over this array because
166 # running each() on the registry and updating it at the same time
168 keys = @registry.keys
169 # no registry, nothing to do
170 return if keys.empty?
173 log "starting markov database conversion thread (v1 to v2, #{keys.length} keys)"
175 keys.each { |k| @upgrade_queue.push k }
176 @upgrade_queue.push nil
178 @upgrade_thread = Thread.new do
179 logfile = File.open(@bot.path('markov-conversion.log'), 'a')
180 logfile.puts "=== conversion thread started #{Time.now} ==="
181 while k = @upgrade_queue.pop
183 logfile.puts "Key #{ki} (#{@upgrade_queue.length} in queue):"
185 upgrade_entry(k, logfile)
186 rescue Exception => e
187 logfile.puts "=== ERROR ==="
188 logfile.puts e.pretty_inspect
189 logfile.puts "=== EREND ==="
191 sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
193 logfile.puts "=== conversion thread stopped #{Time.now} ==="
196 @upgrade_thread.priority = -1
199 attr_accessor :chains
203 @registry.set_default([])
204 if @registry.has_key?('enabled')
205 @bot.config['markov.enabled'] = @registry['enabled']
206 @registry.delete('enabled')
208 if @registry.has_key?('probability')
209 @bot.config['markov.probability'] = @registry['probability']
210 @registry.delete('probability')
212 if @bot.config['markov.ignore_users']
213 debug "moving markov.ignore_users to markov.ignore"
214 @bot.config['markov.ignore'] = @bot.config['markov.ignore_users'].dup
215 @bot.config.delete('markov.ignore_users'.to_sym)
218 @chains = @registry.sub_registry('v2')
219 @chains.set_default([])
220 @chains_mutex = Mutex.new
222 @upgrade_queue = Queue.new
223 @upgrade_thread = nil
226 @learning_queue = Queue.new
227 @learning_thread = Thread.new do
228 while s = @learning_queue.pop
230 sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
233 @learning_thread.priority = -1
237 if @upgrade_thread and @upgrade_thread.alive?
238 debug 'closing conversion thread'
240 @upgrade_queue.push nil
242 debug 'conversion thread closed'
245 debug 'closing learning thread'
246 @learning_queue.push nil
247 @learning_thread.join
248 debug 'learning thread closed'
251 # if passed a pair, pick a word from the registry using the pair as key.
252 # otherwise, pick a word from an given list
253 def pick_word(word1, word2=MARKER)
254 if word1.kind_of? Array
257 k = "#{word1} #{word2}"
258 return MARKER unless @chains.key? k
259 wordlist = @chains[k]
261 total = wordlist.first
263 return MARKER if total == 0
264 return hash.keys.first if hash.length == 1
277 def generate_string(word1, word2)
278 # limit to max of markov.max_words words
280 output = "#{word1} #{word2}"
285 if @chains.key? output
286 wordlist = @chains[output]
287 wordlist.last.delete(MARKER)
291 @chains.each_key(output) do |key|
292 if key.downcase.include? output
299 keys = @chains.keys.select { |k| k.downcase.include? output }
301 return nil if keys.empty?
302 while key = keys.delete_one
303 wordlist = @chains[key]
304 wordlist.last.delete(MARKER)
305 unless wordlist.empty?
307 # split using / / so that we can properly catch the marker
308 word1, word2 = output.split(/ /).map {|w| w.intern}
314 word3 = pick_word(wordlist)
315 return nil if word3 == MARKER
317 output << " #{word3}"
318 word1, word2 = word2, word3
320 (@bot.config['markov.max_words'] - 1).times do
321 word3 = pick_word(word1, word2)
322 break if word3 == MARKER
323 output << " #{word3}"
324 word1, word2 = word2, word3
329 def help(plugin, topic="")
330 topic, subtopic = topic.split
334 "markov delay <value> => Set message delay"
338 "markov ignore add <hostmask|channel> => ignore a hostmask or a channel"
340 "markov ignore list => show ignored hostmasks and channels"
342 "markov ignore remove <hostmask|channel> => unignore a hostmask or channel"
344 "ignore hostmasks or channels -- topics: add, remove, list"
349 "markov readonly add <hostmask|channel> => read-only a hostmask or a channel"
351 "markov readonly list => show read-only hostmasks and channels"
353 "markov readonly remove <hostmask|channel> => unreadonly a hostmask or channel"
355 "restrict hostmasks or channels to read only -- topics: add, remove, list"
358 "markov status => show if markov is enabled, probability and amount of messages in queue for learning"
360 "markov probability [<percent>] => set the % chance of rbot responding to input, or display the current probability"
364 "markov chat about <word> [<another word>] => talk about <word> or riff on a word pair (if possible)"
366 "markov chat => try to say something intelligent"
369 "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: 'chat' to attempt to say something relevant to the last line of chat, if it can -- help topics: ignore, readonly, delay, status, probability, chat, chat about"
375 str.gsub!(/^\S+[:,;]/, "")
376 str.gsub!(/\s{2,}/, ' ') # fix for two or more spaces
381 return @bot.config['markov.probability']
385 if @bot.config['markov.enabled']
386 reply = _("markov is currently enabled, %{p}% chance of chipping in") % { :p => probability? }
387 l = @learning_queue.length
388 reply << (_(", %{l} messages in queue") % {:l => l}) if l > 0
389 l = @upgrade_queue.length
390 reply << (_(", %{l} chains to upgrade") % {:l => l}) if l > 0
392 reply = _("markov is currently disabled")
398 return false unless m
399 return true if m.address? or m.private?
400 @bot.config['markov.ignore'].each do |mask|
401 return true if m.channel.downcase == mask.downcase
402 return true if m.source.matches?(mask)
408 return false unless m
409 @bot.config['markov.readonly'].each do |mask|
410 return true if m.channel.downcase == mask.downcase
411 return true if m.source.matches?(mask)
416 def ignore(m, params)
417 action = params[:action]
418 user = params[:option]
421 if @bot.config['markov.ignore'].include? user
422 s = @bot.config['markov.ignore']
424 @bot.config['ignore'] = s
425 m.reply _("%{u} removed") % { :u => user }
427 m.reply _("not found in list")
431 if @bot.config['markov.ignore'].include?(user)
432 m.reply _("%{u} already in list") % { :u => user }
434 @bot.config['markov.ignore'] = @bot.config['markov.ignore'].push user
435 m.reply _("%{u} added to markov ignore list") % { :u => user }
438 m.reply _("give the name of a person or channel to ignore")
441 m.reply _("I'm ignoring %{ignored}") % { :ignored => @bot.config['markov.ignore'].join(", ") }
443 m.reply _("have markov ignore the input from a hostmask or a channel. usage: markov ignore add <mask or channel>; markov ignore remove <mask or channel>; markov ignore list")
447 def readonly(m, params)
448 action = params[:action]
449 user = params[:option]
452 if @bot.config['markov.readonly'].include? user
453 s = @bot.config['markov.readonly']
455 @bot.config['markov.readonly'] = s
456 m.reply _("%{u} removed") % { :u => user }
458 m.reply _("not found in list")
462 if @bot.config['markov.readonly'].include?(user)
463 m.reply _("%{u} already in list") % { :u => user }
465 @bot.config['markov.readonly'] = @bot.config['markov.readonly'].push user
466 m.reply _("%{u} added to markov readonly list") % { :u => user }
469 m.reply _("give the name of a person or channel to read only")
472 m.reply _("I'm only reading %{readonly}") % { :readonly => @bot.config['markov.readonly'].join(", ") }
474 m.reply _("have markov not answer to input from a hostmask or a channel. usage: markov readonly add <mask or channel>; markov readonly remove <mask or channel>; markov readonly list")
478 def enable(m, params)
479 @bot.config['markov.enabled'] = true
483 def probability(m, params)
484 if params[:probability]
485 @bot.config['markov.probability'] = params[:probability].to_i
488 m.reply _("markov has a %{prob}% chance of chipping in") % { :prob => probability? }
492 def disable(m, params)
493 @bot.config['markov.enabled'] = false
498 return false unless @bot.config['markov.enabled']
500 return true if prob > rand(100)
504 def set_delay(m, params)
505 if params[:delay] == "off"
506 @bot.config["markov.delay"] = 0
508 elsif !params[:delay]
509 m.reply _("Message delay is %{delay}" % { :delay => @bot.config["markov.delay"]})
511 @bot.config["markov.delay"] = params[:delay].to_i
516 def reply_delay(m, line)
518 if @bot.config['markov.delay'] > 0
519 @bot.timer.add_once(@bot.config['markov.delay']) {
520 m.reply line, :nick => false, :to => :public
523 m.reply line, :nick => false, :to => :public
527 def random_markov(m, message)
528 return unless should_talk
530 word1, word2 = clean_str(message).split(/\s+/)
531 return unless word1 and word2
532 line = generate_string(word1.intern, word2.intern)
534 # we do nothing if the line we return is just an initial substring
535 # of the line we received
536 return if message.index(line) == 0
541 line = generate_string(params[:seed1], params[:seed2])
542 if line and line != [params[:seed1], params[:seed2]].compact.join(" ")
545 m.reply _("I can't :(")
549 def rand_chat(m, params)
550 # pick a random pair from the db and go from there
551 word1, word2 = MARKER, MARKER
553 @bot.config['markov.max_words'].times do
554 word3 = pick_word(word1, word2)
555 break if word3 == MARKER
557 word1, word2 = word2, word3
560 m.reply output.join(" ")
562 m.reply _("I can't :(")
567 lines.each { |l| @learning_queue.push l }
573 # in channel message, the kind we are interested in
574 message = m.plainmessage
577 message = "#{m.sourcenick} #{message}"
581 random_markov(m, message) unless readonly? m or m.replied?
585 def learn_triplet(word1, word2, word3)
586 k = "#{word1} #{word2}"
587 @chains_mutex.synchronize do
597 @chains[k] = [total, hash]
601 def learn_line(message)
602 # debug "learning #{message.inspect}"
603 wordlist = clean_str(message).split(/\s+/).map { |w| w.intern }
604 return unless wordlist.length >= 2
605 word1, word2 = MARKER, MARKER
607 wordlist.each do |word3|
608 learn_triplet(word1, word2, word3)
609 word1, word2 = word2, word3
613 # TODO allow learning from URLs
614 def learn_from(m, params)
617 file = File.open(path, "r")
618 pattern = params[:pattern].empty? ? nil : Regexp.new(params[:pattern].to_s)
620 m.reply _("no such file")
625 m.reply _("the file is empty!")
631 range = case params[:lines]
633 Range.new(*params[:lines].split("..").map { |e| e.to_i })
635 Range.new(1, params[:lines].to_i)
637 Range.new(1, [@bot.config['send.max_lines'], 3].max)
641 next unless file.lineno >= range.begin
643 break if file.lineno == range.end
646 lines = lines.map do |l|
647 pattern ? l.scan(pattern).to_s : l
648 end.reject { |e| e.empty? }
652 m.reply _("example matches for that pattern at lines %{range} include: %{lines}") % {
653 :lines => lines.map { |e| Underline+e+Underline }.join(", "),
657 m.reply _("the pattern doesn't match anything at lines %{range}") % {
662 m.reply _("learning from the file without a pattern would learn, for example: ")
663 lines.each { |l| m.reply l }
670 file.each { |l| learn(l.scan(pattern).to_s) }
672 file.each { |l| learn(l.chomp) }
679 plugin = MarkovPlugin.new
680 plugin.map 'markov delay :delay', :action => "set_delay"
681 plugin.map 'markov delay', :action => "set_delay"
682 plugin.map 'markov ignore :action :option', :action => "ignore"
683 plugin.map 'markov ignore :action', :action => "ignore"
684 plugin.map 'markov ignore', :action => "ignore"
685 plugin.map 'markov readonly :action :option', :action => "readonly"
686 plugin.map 'markov readonly :action', :action => "readonly"
687 plugin.map 'markov readonly', :action => "readonly"
688 plugin.map 'markov enable', :action => "enable"
689 plugin.map 'markov disable', :action => "disable"
690 plugin.map 'markov status', :action => "status"
691 plugin.map 'chat about :seed1 [:seed2]', :action => "chat"
692 plugin.map 'chat', :action => "rand_chat"
693 plugin.map 'markov probability [:probability]', :action => "probability",
694 :requirements => {:probability => /^\d+%?$/}
695 plugin.map 'markov learn from :file [:testing [:lines lines]] [using pattern *pattern]', :action => "learn_from", :thread => true,
697 :testing => /^testing$/,
698 :lines => /^(?:\d+\.\.\d+|\d+)$/ }
700 plugin.default_auth('ignore', false)
701 plugin.default_auth('probability', false)
702 plugin.default_auth('learn', false)