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")
42 Config.register Config::ArrayValue.new('markov.ignore_patterns',
44 :desc => "Ignore these word patterns")
48 # upgrade a registry entry from 0.9.14 and earlier, converting the Arrays
49 # into Hashes of weights
50 def upgrade_entry(k, logfile)
51 logfile.puts "\t#{k.inspect}"
57 # wipe the current key
62 logfile.puts "\tEMPTY"
67 logfile.puts "\t#{ar.inspect}"
69 # re-encode key to UTF-8 and cleanup as needed
70 words = k.split.map do |w|
71 BasicUserMessage.strip_formatting(
72 @bot.socket.filter.in(w)
76 # old import that failed to split properly?
77 if words.length == 1 and words.first.include? '/'
80 at = unsplit.rindex('/')
81 words = [unsplit[0,at], unsplit[at+1..-1]]
84 # if any of the re-split/re-encoded words have spaces,
85 # or are empty, we would get a chain we can't convert,
87 if words.first.empty? or words.first.include?(' ') or
88 words.last.empty? or words.last.include?(' ')
89 logfile.puts "\tSKIPPED"
93 # former unclean CTCP, we can't convert this
94 if words.first[0] == 1
95 logfile.puts "\tSKIPPED"
99 # nonword CTCP => SKIP
100 # someword CTCP => nonword someword
101 if words.last[0] == 1
102 if words.first == "nonword"
103 logfile.puts "\tSKIPPED"
110 # intern the old keys
112 ['nonword', MARKER].include?(w) ? MARKER : w.chomp("\001")
115 newkey = words.join(' ')
116 logfile.puts "\t#{newkey.inspect}"
118 # the new key exists already, so we want to merge
119 if k != newkey and @registry.key? newkey
120 ar2 = @registry[newkey]
121 logfile.puts "\tMERGE"
122 logfile.puts "\t\t#{ar2.inspect}"
124 # and get rid of the key
125 @registry.delete(newkey)
131 @chains_mutex.synchronize do
132 if @chains.key? newkey
133 ar2 = @chains[newkey]
144 # we convert old words into UTF-8, cleanup, resplit if needed,
145 # and only get the first word. we may lose some data for old
146 # missplits, but this is the best we can do
147 w = BasicUserMessage.strip_formatting(
148 @bot.socket.filter.in(word).split.first
151 when /^\001\S+$/, "\001", ""
152 # former unclean CTCP or end of CTCP
155 # intern after clearing leftover end-of-actions if present
156 sym = w.chomp("\001")
163 logfile.puts "\tSKIPPED"
166 logfile.puts "\t#{[total, hash].inspect}"
167 @chains[newkey] = [total, hash]
172 # we load all the keys and then iterate over this array because
173 # running each() on the registry and updating it at the same time
175 keys = @registry.keys
176 # no registry, nothing to do
177 return if keys.empty?
180 log "starting markov database conversion thread (v1 to v2, #{keys.length} keys)"
182 keys.each { |k| @upgrade_queue.push k }
183 @upgrade_queue.push nil
185 @upgrade_thread = Thread.new do
186 logfile = File.open(@bot.path('markov-conversion.log'), 'a')
187 logfile.puts "=== conversion thread started #{Time.now} ==="
188 while k = @upgrade_queue.pop
190 logfile.puts "Key #{ki} (#{@upgrade_queue.length} in queue):"
192 upgrade_entry(k, logfile)
193 rescue Exception => e
194 logfile.puts "=== ERROR ==="
195 logfile.puts e.pretty_inspect
196 logfile.puts "=== EREND ==="
198 sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
200 logfile.puts "=== conversion thread stopped #{Time.now} ==="
203 @upgrade_thread.priority = -1
206 attr_accessor :chains
210 @registry.set_default([])
211 if @registry.has_key?('enabled')
212 @bot.config['markov.enabled'] = @registry['enabled']
213 @registry.delete('enabled')
215 if @registry.has_key?('probability')
216 @bot.config['markov.probability'] = @registry['probability']
217 @registry.delete('probability')
219 if @bot.config['markov.ignore_users']
220 debug "moving markov.ignore_users to markov.ignore"
221 @bot.config['markov.ignore'] = @bot.config['markov.ignore_users'].dup
222 @bot.config.delete('markov.ignore_users'.to_sym)
225 @chains = @registry.sub_registry('v2')
226 @chains.set_default([])
227 @rchains = @registry.sub_registry('v2r')
228 @rchains.set_default([])
230 @upgrade_queue = Queue.new
231 @upgrade_thread = nil
234 @learning_queue = Queue.new
235 @learning_thread = Thread.new do
236 while s = @learning_queue.pop
238 sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
241 @learning_thread.priority = -1
245 if @upgrade_thread and @upgrade_thread.alive?
246 debug 'closing conversion thread'
248 @upgrade_queue.push nil
250 debug 'conversion thread closed'
253 debug 'closing learning thread'
254 @learning_queue.clear
255 @learning_queue.push nil
256 @learning_thread.join
257 debug 'learning thread closed'
263 # pick a word from the registry using the pair as key.
264 def pick_word(word1, word2=MARKER, chainz=@chains)
265 k = "#{word1} #{word2}"
266 return MARKER unless chainz.key? k
268 pick_word_from_list wordlist
271 # pick a word from weighted hash
272 def pick_word_from_list(wordlist)
273 total = wordlist.first
275 return MARKER if total == 0
276 return hash.keys.first if hash.length == 1
289 def generate_string(word1, word2)
290 # limit to max of markov.max_words words
292 output = [word1, word2]
296 @chains.each_key(output) do |key|
297 if key.downcase.include? output
303 return nil if keys.empty?
304 output = keys[rand(keys.size)].split(/ /)
306 output = output.split(/ /) unless output.is_a? Array
307 input = [word1, word2]
308 while output.length < @bot.config['markov.max_words'] and (output.first != MARKER or output.last != MARKER) do
309 if output.last != MARKER
310 output << pick_word(output[-2], output[-1])
312 if output.first != MARKER
313 output.insert 0, pick_word(output[0], output[1], @rchains)
324 def help(plugin, topic="")
325 topic, subtopic = topic.split
329 "markov delay <value> => Set message delay"
333 "markov ignore add <hostmask|channel> => ignore a hostmask or a channel"
335 "markov ignore list => show ignored hostmasks and channels"
337 "markov ignore remove <hostmask|channel> => unignore a hostmask or channel"
339 "ignore hostmasks or channels -- topics: add, remove, list"
344 "markov readonly add <hostmask|channel> => read-only a hostmask or a channel"
346 "markov readonly list => show read-only hostmasks and channels"
348 "markov readonly remove <hostmask|channel> => unreadonly a hostmask or channel"
350 "restrict hostmasks or channels to read only -- topics: add, remove, list"
353 "markov status => show if markov is enabled, probability and amount of messages in queue for learning"
355 "markov probability [<percent>] => set the % chance of rbot responding to input, or display the current probability"
359 "markov chat about <word> [<another word>] => talk about <word> or riff on a word pair (if possible)"
361 "markov chat => try to say something intelligent"
364 "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"
369 str = m.plainmessage.dup
370 str =~ /^(\S+)([:,;])/
371 if $1 and m.target.is_a? Irc::Channel and m.target.user_nicks.include? $1.downcase
372 str.gsub!(/^(\S+)([:,;])\s+/, "")
374 str.gsub!(/\s{2,}/, ' ') # fix for two or more spaces
379 return @bot.config['markov.probability']
383 if @bot.config['markov.enabled']
384 reply = _("markov is currently enabled, %{p}% chance of chipping in") % { :p => probability? }
385 l = @learning_queue.length
386 reply << (_(", %{l} messages in queue") % {:l => l}) if l > 0
387 l = @upgrade_queue.length
388 reply << (_(", %{l} chains to upgrade") % {:l => l}) if l > 0
390 reply = _("markov is currently disabled")
396 return false unless m
397 return true if m.private?
398 return true if m.prefixed?
399 @bot.config['markov.ignore'].each do |mask|
400 return true if m.channel.downcase == mask.downcase
401 return true if m.source.matches?(mask)
407 return false unless m
408 @bot.config['markov.readonly'].each do |mask|
409 return true if m.channel.downcase == mask.downcase
410 return true if m.source.matches?(mask)
415 def ignore(m, params)
416 action = params[:action]
417 user = params[:option]
420 if @bot.config['markov.ignore'].include? user
421 s = @bot.config['markov.ignore']
423 @bot.config['ignore'] = s
424 m.reply _("%{u} removed") % { :u => user }
426 m.reply _("not found in list")
430 if @bot.config['markov.ignore'].include?(user)
431 m.reply _("%{u} already in list") % { :u => user }
433 @bot.config['markov.ignore'] = @bot.config['markov.ignore'].push user
434 m.reply _("%{u} added to markov ignore list") % { :u => user }
437 m.reply _("give the name of a person or channel to ignore")
440 m.reply _("I'm ignoring %{ignored}") % { :ignored => @bot.config['markov.ignore'].join(", ") }
442 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")
446 def readonly(m, params)
447 action = params[:action]
448 user = params[:option]
451 if @bot.config['markov.readonly'].include? user
452 s = @bot.config['markov.readonly']
454 @bot.config['markov.readonly'] = s
455 m.reply _("%{u} removed") % { :u => user }
457 m.reply _("not found in list")
461 if @bot.config['markov.readonly'].include?(user)
462 m.reply _("%{u} already in list") % { :u => user }
464 @bot.config['markov.readonly'] = @bot.config['markov.readonly'].push user
465 m.reply _("%{u} added to markov readonly list") % { :u => user }
468 m.reply _("give the name of a person or channel to read only")
471 m.reply _("I'm only reading %{readonly}") % { :readonly => @bot.config['markov.readonly'].join(", ") }
473 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")
477 def enable(m, params)
478 @bot.config['markov.enabled'] = true
482 def probability(m, params)
483 if params[:probability]
484 @bot.config['markov.probability'] = params[:probability].to_i
487 m.reply _("markov has a %{prob}% chance of chipping in") % { :prob => probability? }
491 def disable(m, params)
492 @bot.config['markov.enabled'] = false
497 return false unless @bot.config['markov.enabled']
498 prob = m.address? ? @bot.config['markov.answer_addressed'] : probability?
499 return true if prob > rand(100)
503 # Generates all sequence pairs from array
504 # seq_pairs [1,2,3,4] == [ [1,2], [2,3], [3,4]]
507 0.upto(arr.size-2) do |i|
508 res << [arr[i], arr[i+1]]
513 def set_delay(m, params)
514 if params[:delay] == "off"
515 @bot.config["markov.delay"] = 0
517 elsif !params[:delay]
518 m.reply _("Message delay is %{delay}" % { :delay => @bot.config["markov.delay"]})
520 @bot.config["markov.delay"] = params[:delay].to_i
525 def reply_delay(m, line)
527 if @bot.config['markov.delay'] > 0
528 @bot.timer.add_once(1 + rand(@bot.config['markov.delay'])) {
529 m.reply line, :nick => false, :to => :public
532 m.reply line, :nick => false, :to => :public
536 def random_markov(m, message)
537 return unless should_talk(m)
539 words = clean_message(m).split(/\s+/)
541 line = generate_string words.first, nil
543 if line and message.index(line) != 0
548 pairs = seq_pairs(words).sort_by { rand }
549 pairs.each do |word1, word2|
550 line = generate_string(word1, word2)
551 if line and message.index(line) != 0
556 words.sort_by { rand }.each do |word|
557 line = generate_string word.first, nil
558 if line and message.index(line) != 0
567 line = generate_string(params[:seed1], params[:seed2])
568 if line and line != [params[:seed1], params[:seed2]].compact.join(" ")
571 m.reply _("I can't :(")
575 def rand_chat(m, params)
576 # pick a random pair from the db and go from there
577 word1, word2 = MARKER, MARKER
579 @bot.config['markov.max_words'].times do
580 word3 = pick_word(word1, word2)
581 break if word3 == MARKER
583 word1, word2 = word2, word3
586 m.reply output.join(" ")
588 m.reply _("I can't :(")
593 lines.each { |l| @learning_queue.push l }
599 # in channel message, the kind we are interested in
600 message = m.plainmessage
603 message = "#{m.sourcenick} #{message}"
606 random_markov(m, message) unless readonly? m or m.replied?
607 learn clean_message(m)
611 def learn_triplet(word1, word2, word3)
612 k = "#{word1} #{word2}"
613 rk = "#{word2} #{word3}"
623 @chains[k] = [total, hash]
628 t2, h2 = @rchains[rk]
634 @rchains[rk] = [total, hash]
638 def learn_line(message)
639 # debug "learning #{message.inspect}"
640 wordlist = message.strip.split(/\s+/).reject do |w|
641 @bot.config['markov.ignore_patterns'].map do |pat|
642 w =~ Regexp.new(pat.to_s)
643 end.select{|v| v}.size != 0
645 return unless wordlist.length >= 2
646 word1, word2 = MARKER, MARKER
648 wordlist.each do |word3|
649 learn_triplet(word1, word2, word3.to_sym)
650 word1, word2 = word2, word3
654 # TODO allow learning from URLs
655 def learn_from(m, params)
658 file = File.open(path, "r")
659 pattern = params[:pattern].empty? ? nil : Regexp.new(params[:pattern].to_s)
661 m.reply _("no such file")
666 m.reply _("the file is empty!")
672 range = case params[:lines]
674 Range.new(*params[:lines].split("..").map { |e| e.to_i })
676 Range.new(1, params[:lines].to_i)
678 Range.new(1, [@bot.config['send.max_lines'], 3].max)
682 next unless file.lineno >= range.begin
684 break if file.lineno == range.end
687 lines = lines.map do |l|
688 pattern ? l.scan(pattern).to_s : l
689 end.reject { |e| e.empty? }
693 m.reply _("example matches for that pattern at lines %{range} include: %{lines}") % {
694 :lines => lines.map { |e| Underline+e+Underline }.join(", "),
698 m.reply _("the pattern doesn't match anything at lines %{range}") % {
703 m.reply _("learning from the file without a pattern would learn, for example: ")
704 lines.each { |l| m.reply l }
711 file.each { |l| learn(l.scan(pattern).to_s) }
713 file.each { |l| learn(l.chomp) }
720 m.reply "Markov status: chains: #{@chains.length} forward, #{@rchains.length} reverse, queued phrases: #{@learning_queue.size}"
725 plugin = MarkovPlugin.new
726 plugin.map 'markov delay :delay', :action => "set_delay"
727 plugin.map 'markov delay', :action => "set_delay"
728 plugin.map 'markov ignore :action :option', :action => "ignore"
729 plugin.map 'markov ignore :action', :action => "ignore"
730 plugin.map 'markov ignore', :action => "ignore"
731 plugin.map 'markov readonly :action :option', :action => "readonly"
732 plugin.map 'markov readonly :action', :action => "readonly"
733 plugin.map 'markov readonly', :action => "readonly"
734 plugin.map 'markov enable', :action => "enable"
735 plugin.map 'markov disable', :action => "disable"
736 plugin.map 'markov status', :action => "status"
737 plugin.map 'markov stats', :action => "stats"
738 plugin.map 'chat about :seed1 [:seed2]', :action => "chat"
739 plugin.map 'chat', :action => "rand_chat"
740 plugin.map 'markov probability [:probability]', :action => "probability",
741 :requirements => {:probability => /^\d+%?$/}
742 plugin.map 'markov learn from :file [:testing [:lines lines]] [using pattern *pattern]', :action => "learn_from", :thread => true,
744 :testing => /^testing$/,
745 :lines => /^(?:\d+\.\.\d+|\d+)$/ }
747 plugin.default_auth('ignore', false)
748 plugin.default_auth('probability', false)
749 plugin.default_auth('learn', false)