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::FloatValue.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.")
38 Config.register Config::IntegerValue.new('markov.answer_addressed',
40 :validate => Proc.new { |v| (0..100).include? v },
41 :desc => "Probability of answer when addressed by nick")
45 # upgrade a registry entry from 0.9.14 and earlier, converting the Arrays
46 # into Hashes of weights
47 def upgrade_entry(k, logfile)
48 logfile.puts "\t#{k.inspect}"
54 # wipe the current key
59 logfile.puts "\tEMPTY"
64 logfile.puts "\t#{ar.inspect}"
66 # re-encode key to UTF-8 and cleanup as needed
67 words = k.split.map do |w|
68 BasicUserMessage.strip_formatting(
69 @bot.socket.filter.in(w)
73 # old import that failed to split properly?
74 if words.length == 1 and words.first.include? '/'
77 at = unsplit.rindex('/')
78 words = [unsplit[0,at], unsplit[at+1..-1]]
81 # if any of the re-split/re-encoded words have spaces,
82 # or are empty, we would get a chain we can't convert,
84 if words.first.empty? or words.first.include?(' ') or
85 words.last.empty? or words.last.include?(' ')
86 logfile.puts "\tSKIPPED"
90 # former unclean CTCP, we can't convert this
91 if words.first[0] == 1
92 logfile.puts "\tSKIPPED"
96 # nonword CTCP => SKIP
97 # someword CTCP => nonword someword
99 if words.first == "nonword"
100 logfile.puts "\tSKIPPED"
107 # intern the old keys
109 ['nonword', MARKER].include?(w) ? MARKER : w.chomp("\001")
112 newkey = words.join(' ')
113 logfile.puts "\t#{newkey.inspect}"
115 # the new key exists already, so we want to merge
116 if k != newkey and @registry.key? newkey
117 ar2 = @registry[newkey]
118 logfile.puts "\tMERGE"
119 logfile.puts "\t\t#{ar2.inspect}"
121 # and get rid of the key
122 @registry.delete(newkey)
128 @chains_mutex.synchronize do
129 if @chains.key? newkey
130 ar2 = @chains[newkey]
141 # we convert old words into UTF-8, cleanup, resplit if needed,
142 # and only get the first word. we may lose some data for old
143 # missplits, but this is the best we can do
144 w = BasicUserMessage.strip_formatting(
145 @bot.socket.filter.in(word).split.first
148 when /^\001\S+$/, "\001", ""
149 # former unclean CTCP or end of CTCP
152 # intern after clearing leftover end-of-actions if present
153 sym = w.chomp("\001").intern
160 logfile.puts "\tSKIPPED"
163 logfile.puts "\t#{[total, hash].inspect}"
164 @chains[newkey] = [total, hash]
169 # we load all the keys and then iterate over this array because
170 # running each() on the registry and updating it at the same time
172 keys = @registry.keys
173 # no registry, nothing to do
174 return if keys.empty?
177 log "starting markov database conversion thread (v1 to v2, #{keys.length} keys)"
179 keys.each { |k| @upgrade_queue.push k }
180 @upgrade_queue.push nil
182 @upgrade_thread = Thread.new do
183 logfile = File.open(@bot.path('markov-conversion.log'), 'a')
184 logfile.puts "=== conversion thread started #{Time.now} ==="
185 while k = @upgrade_queue.pop
187 logfile.puts "Key #{ki} (#{@upgrade_queue.length} in queue):"
189 upgrade_entry(k, logfile)
190 rescue Exception => e
191 logfile.puts "=== ERROR ==="
192 logfile.puts e.pretty_inspect
193 logfile.puts "=== EREND ==="
195 sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
197 logfile.puts "=== conversion thread stopped #{Time.now} ==="
200 @upgrade_thread.priority = -1
203 attr_accessor :chains
207 @registry.set_default([])
208 if @registry.has_key?('enabled')
209 @bot.config['markov.enabled'] = @registry['enabled']
210 @registry.delete('enabled')
212 if @registry.has_key?('probability')
213 @bot.config['markov.probability'] = @registry['probability']
214 @registry.delete('probability')
216 if @bot.config['markov.ignore_users']
217 debug "moving markov.ignore_users to markov.ignore"
218 @bot.config['markov.ignore'] = @bot.config['markov.ignore_users'].dup
219 @bot.config.delete('markov.ignore_users'.to_sym)
222 @chains = @registry.sub_registry('v2')
223 @chains.set_default([])
224 @chains_mutex = Mutex.new
226 @upgrade_queue = Queue.new
227 @upgrade_thread = nil
230 @learning_queue = Queue.new
231 @learning_thread = Thread.new do
232 while s = @learning_queue.pop
234 sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
237 @learning_thread.priority = -1
241 if @upgrade_thread and @upgrade_thread.alive?
242 debug 'closing conversion thread'
244 @upgrade_queue.push nil
246 debug 'conversion thread closed'
249 debug 'closing learning thread'
250 @learning_queue.push nil
251 @learning_thread.join
252 debug 'learning thread closed'
255 # if passed a pair, pick a word from the registry using the pair as key.
256 # otherwise, pick a word from an given list
257 def pick_word(word1, word2=MARKER)
258 if word1.kind_of? Array
261 k = "#{word1} #{word2}"
262 return MARKER unless @chains.key? k
263 wordlist = @chains[k]
265 total = wordlist.first
267 return MARKER if total == 0
268 return hash.keys.first if hash.length == 1
281 def generate_string(word1, word2)
282 # limit to max of markov.max_words words
284 output = "#{word1} #{word2}"
289 if @chains.key? output
290 wordlist = @chains[output]
291 wordlist.last.delete(MARKER)
295 @chains.each_key(output) do |key|
296 if key.downcase.include? output
303 keys = @chains.keys.select { |k| k.downcase.include? output }
305 return nil if keys.empty?
306 while key = keys.delete_one
307 wordlist = @chains[key]
308 wordlist.last.delete(MARKER)
309 unless wordlist.empty?
311 # split using / / so that we can properly catch the marker
312 word1, word2 = output.split(/ /).map {|w| w.intern}
318 word3 = pick_word(wordlist)
319 return nil if word3 == MARKER
321 output << " #{word3}"
322 word1, word2 = word2, word3
324 (@bot.config['markov.max_words'] - 1).times do
325 word3 = pick_word(word1, word2)
326 break if word3 == MARKER
327 output << " #{word3}"
328 word1, word2 = word2, word3
333 def help(plugin, topic="")
334 topic, subtopic = topic.split
338 "markov delay <value> => Set message delay"
342 "markov ignore add <hostmask|channel> => ignore a hostmask or a channel"
344 "markov ignore list => show ignored hostmasks and channels"
346 "markov ignore remove <hostmask|channel> => unignore a hostmask or channel"
348 "ignore hostmasks or channels -- topics: add, remove, list"
353 "markov readonly add <hostmask|channel> => read-only a hostmask or a channel"
355 "markov readonly list => show read-only hostmasks and channels"
357 "markov readonly remove <hostmask|channel> => unreadonly a hostmask or channel"
359 "restrict hostmasks or channels to read only -- topics: add, remove, list"
362 "markov status => show if markov is enabled, probability and amount of messages in queue for learning"
364 "markov probability [<percent>] => set the % chance of rbot responding to input, or display the current probability"
368 "markov chat about <word> [<another word>] => talk about <word> or riff on a word pair (if possible)"
370 "markov chat => try to say something intelligent"
373 "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"
379 str.gsub!(/^\S+[:,;]/, "")
380 str.gsub!(/\s{2,}/, ' ') # fix for two or more spaces
385 return @bot.config['markov.probability']
389 if @bot.config['markov.enabled']
390 reply = _("markov is currently enabled, %{p}% chance of chipping in") % { :p => probability? }
391 l = @learning_queue.length
392 reply << (_(", %{l} messages in queue") % {:l => l}) if l > 0
393 l = @upgrade_queue.length
394 reply << (_(", %{l} chains to upgrade") % {:l => l}) if l > 0
396 reply = _("markov is currently disabled")
402 return false unless m
403 return true if m.private?
404 return true if m.prefixed?
405 @bot.config['markov.ignore'].each do |mask|
406 return true if m.channel.downcase == mask.downcase
407 return true if m.source.matches?(mask)
413 return false unless m
414 @bot.config['markov.readonly'].each do |mask|
415 return true if m.channel.downcase == mask.downcase
416 return true if m.source.matches?(mask)
421 def ignore(m, params)
422 action = params[:action]
423 user = params[:option]
426 if @bot.config['markov.ignore'].include? user
427 s = @bot.config['markov.ignore']
429 @bot.config['ignore'] = s
430 m.reply _("%{u} removed") % { :u => user }
432 m.reply _("not found in list")
436 if @bot.config['markov.ignore'].include?(user)
437 m.reply _("%{u} already in list") % { :u => user }
439 @bot.config['markov.ignore'] = @bot.config['markov.ignore'].push user
440 m.reply _("%{u} added to markov ignore list") % { :u => user }
443 m.reply _("give the name of a person or channel to ignore")
446 m.reply _("I'm ignoring %{ignored}") % { :ignored => @bot.config['markov.ignore'].join(", ") }
448 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")
452 def readonly(m, params)
453 action = params[:action]
454 user = params[:option]
457 if @bot.config['markov.readonly'].include? user
458 s = @bot.config['markov.readonly']
460 @bot.config['markov.readonly'] = s
461 m.reply _("%{u} removed") % { :u => user }
463 m.reply _("not found in list")
467 if @bot.config['markov.readonly'].include?(user)
468 m.reply _("%{u} already in list") % { :u => user }
470 @bot.config['markov.readonly'] = @bot.config['markov.readonly'].push user
471 m.reply _("%{u} added to markov readonly list") % { :u => user }
474 m.reply _("give the name of a person or channel to read only")
477 m.reply _("I'm only reading %{readonly}") % { :readonly => @bot.config['markov.readonly'].join(", ") }
479 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")
483 def enable(m, params)
484 @bot.config['markov.enabled'] = true
488 def probability(m, params)
489 if params[:probability]
490 @bot.config['markov.probability'] = params[:probability].to_i
493 m.reply _("markov has a %{prob}% chance of chipping in") % { :prob => probability? }
497 def disable(m, params)
498 @bot.config['markov.enabled'] = false
503 return false unless @bot.config['markov.enabled']
505 return true if prob > rand(100)
509 # Generates all sequence pairs from array
510 # seq_pairs [1,2,3,4] == [ [1,2], [2,3], [3,4]]
513 0.upto(arr.size-2) do |i|
514 res << [arr[i], arr[i+1]]
519 def set_delay(m, params)
520 if params[:delay] == "off"
521 @bot.config["markov.delay"] = 0
523 elsif !params[:delay]
524 m.reply _("Message delay is %{delay}" % { :delay => @bot.config["markov.delay"]})
526 @bot.config["markov.delay"] = params[:delay].to_i
531 def reply_delay(m, line)
533 if @bot.config['markov.delay'] > 0
534 @bot.timer.add_once(@bot.config['markov.delay']) {
535 m.reply line, :nick => false, :to => :public
538 m.reply line, :nick => false, :to => :public
542 def random_markov(m, message)
543 return unless (should_talk or (m.address? and @bot.config['markov.answer_addressed'] > rand(100)))
545 words = clean_str(message).split(/\s+/)
547 line = generate_string words.first, nil
550 return if message.index(line) == 0
555 pairs = seq_pairs(words).sort_by { rand }
556 pairs.each do |word1, word2|
557 line = generate_string(word1.intern, word2.intern)
558 if line and message.index(line) != 0
563 words.sort_by { rand }.each do |word|
564 line = generate_string word.first, nil
565 if line and message.index(line) != 0
574 line = generate_string(params[:seed1], params[:seed2])
575 if line and line != [params[:seed1], params[:seed2]].compact.join(" ")
578 m.reply _("I can't :(")
582 def rand_chat(m, params)
583 # pick a random pair from the db and go from there
584 word1, word2 = MARKER, MARKER
586 @bot.config['markov.max_words'].times do
587 word3 = pick_word(word1, word2)
588 break if word3 == MARKER
590 word1, word2 = word2, word3
593 m.reply output.join(" ")
595 m.reply _("I can't :(")
600 lines.each { |l| @learning_queue.push l }
606 # in channel message, the kind we are interested in
607 message = m.plainmessage
610 message = "#{m.sourcenick} #{message}"
614 random_markov(m, message) unless readonly? m or m.replied?
618 def learn_triplet(word1, word2, word3)
619 k = "#{word1} #{word2}"
620 @chains_mutex.synchronize do
630 @chains[k] = [total, hash]
634 def learn_line(message)
635 # debug "learning #{message.inspect}"
636 wordlist = clean_str(message).split(/\s+/).map { |w| w.intern }
637 return unless wordlist.length >= 2
638 word1, word2 = MARKER, MARKER
640 wordlist.each do |word3|
641 learn_triplet(word1, word2, word3)
642 word1, word2 = word2, word3
646 # TODO allow learning from URLs
647 def learn_from(m, params)
650 file = File.open(path, "r")
651 pattern = params[:pattern].empty? ? nil : Regexp.new(params[:pattern].to_s)
653 m.reply _("no such file")
658 m.reply _("the file is empty!")
664 range = case params[:lines]
666 Range.new(*params[:lines].split("..").map { |e| e.to_i })
668 Range.new(1, params[:lines].to_i)
670 Range.new(1, [@bot.config['send.max_lines'], 3].max)
674 next unless file.lineno >= range.begin
676 break if file.lineno == range.end
679 lines = lines.map do |l|
680 pattern ? l.scan(pattern).to_s : l
681 end.reject { |e| e.empty? }
685 m.reply _("example matches for that pattern at lines %{range} include: %{lines}") % {
686 :lines => lines.map { |e| Underline+e+Underline }.join(", "),
690 m.reply _("the pattern doesn't match anything at lines %{range}") % {
695 m.reply _("learning from the file without a pattern would learn, for example: ")
696 lines.each { |l| m.reply l }
703 file.each { |l| learn(l.scan(pattern).to_s) }
705 file.each { |l| learn(l.chomp) }
712 plugin = MarkovPlugin.new
713 plugin.map 'markov delay :delay', :action => "set_delay"
714 plugin.map 'markov delay', :action => "set_delay"
715 plugin.map 'markov ignore :action :option', :action => "ignore"
716 plugin.map 'markov ignore :action', :action => "ignore"
717 plugin.map 'markov ignore', :action => "ignore"
718 plugin.map 'markov readonly :action :option', :action => "readonly"
719 plugin.map 'markov readonly :action', :action => "readonly"
720 plugin.map 'markov readonly', :action => "readonly"
721 plugin.map 'markov enable', :action => "enable"
722 plugin.map 'markov disable', :action => "disable"
723 plugin.map 'markov status', :action => "status"
724 plugin.map 'chat about :seed1 [:seed2]', :action => "chat"
725 plugin.map 'chat', :action => "rand_chat"
726 plugin.map 'markov probability [:probability]', :action => "probability",
727 :requirements => {:probability => /^\d+%?$/}
728 plugin.map 'markov learn from :file [:testing [:lines lines]] [using pattern *pattern]', :action => "learn_from", :thread => true,
730 :testing => /^testing$/,
731 :lines => /^(?:\d+\.\.\d+|\d+)$/ }
733 plugin.default_auth('ignore', false)
734 plugin.default_auth('probability', false)
735 plugin.default_auth('learn', false)