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::IntegerValue.new('markov.max_words',
25 :validate => Proc.new { |v| (0..100).include? v },
26 :desc => "Maximum number of words the bot should put in a sentence")
27 Config.register Config::IntegerValue.new('markov.learn_delay',
29 :validate => Proc.new { |v| v >= 0 },
30 :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.")
31 Config.register Config::IntegerValue.new('markov.delay',
33 :validate => Proc.new { |v| v >= 0 },
34 :desc => "Wait short time before contributing to conversation.")
38 # upgrade a registry entry from 0.9.14 and earlier, converting the Arrays
39 # into Hashes of weights
40 def upgrade_entry(k, logfile)
41 logfile.puts "\t#{k.inspect}"
47 # wipe the current key
52 logfile.puts "\tEMPTY"
57 logfile.puts "\t#{ar.inspect}"
59 # re-encode key to UTF-8 and cleanup as needed
60 words = k.split.map do |w|
61 BasicUserMessage.strip_formatting(
62 @bot.socket.filter.in(w)
66 # old import that failed to split properly?
67 if words.length == 1 and words.first.include? '/'
70 at = unsplit.rindex('/')
71 words = [unsplit[0,at], unsplit[at+1..-1]]
74 # if any of the re-split/re-encoded words have spaces,
75 # or are empty, we would get a chain we can't convert,
77 if words.first.empty? or words.first.include?(' ') or
78 words.last.empty? or words.last.include?(' ')
79 logfile.puts "\tSKIPPED"
83 # former unclean CTCP, we can't convert this
84 if words.first[0] == 1
85 logfile.puts "\tSKIPPED"
89 # nonword CTCP => SKIP
90 # someword CTCP => nonword someword
92 if words.first == "nonword"
93 logfile.puts "\tSKIPPED"
100 # intern the old keys
102 ['nonword', MARKER].include?(w) ? MARKER : w.chomp("\001")
105 newkey = words.join(' ')
106 logfile.puts "\t#{newkey.inspect}"
108 # the new key exists already, so we want to merge
109 if k != newkey and @registry.key? newkey
110 ar2 = @registry[newkey]
111 logfile.puts "\tMERGE"
112 logfile.puts "\t\t#{ar2.inspect}"
114 # and get rid of the key
115 @registry.delete(newkey)
121 @chains_mutex.synchronize do
122 if @chains.key? newkey
123 ar2 = @chains[newkey]
134 # we convert old words into UTF-8, cleanup, resplit if needed,
135 # and only get the first word. we may lose some data for old
136 # missplits, but this is the best we can do
137 w = BasicUserMessage.strip_formatting(
138 @bot.socket.filter.in(word).split.first
141 when /^\001\S+$/, "\001", ""
142 # former unclean CTCP or end of CTCP
145 # intern after clearing leftover end-of-actions if present
146 sym = w.chomp("\001").intern
153 logfile.puts "\tSKIPPED"
156 logfile.puts "\t#{[total, hash].inspect}"
157 @chains[newkey] = [total, hash]
162 # we load all the keys and then iterate over this array because
163 # running each() on the registry and updating it at the same time
165 keys = @registry.keys
166 # no registry, nothing to do
167 return if keys.empty?
170 log "starting markov database conversion thread (v1 to v2, #{keys.length} keys)"
172 keys.each { |k| @upgrade_queue.push k }
173 @upgrade_queue.push nil
175 @upgrade_thread = Thread.new do
176 logfile = File.open(@bot.path('markov-conversion.log'), 'a')
177 logfile.puts "=== conversion thread started #{Time.now} ==="
178 while k = @upgrade_queue.pop
180 logfile.puts "Key #{ki} (#{@upgrade_queue.length} in queue):"
182 upgrade_entry(k, logfile)
183 rescue Exception => e
184 logfile.puts "=== ERROR ==="
185 logfile.puts e.pretty_inspect
186 logfile.puts "=== EREND ==="
188 sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
190 logfile.puts "=== conversion thread stopped #{Time.now} ==="
193 @upgrade_thread.priority = -1
196 attr_accessor :chains
200 @registry.set_default([])
201 if @registry.has_key?('enabled')
202 @bot.config['markov.enabled'] = @registry['enabled']
203 @registry.delete('enabled')
205 if @registry.has_key?('probability')
206 @bot.config['markov.probability'] = @registry['probability']
207 @registry.delete('probability')
209 if @bot.config['markov.ignore_users']
210 debug "moving markov.ignore_users to markov.ignore"
211 @bot.config['markov.ignore'] = @bot.config['markov.ignore_users'].dup
212 @bot.config.delete('markov.ignore_users'.to_sym)
215 @chains = @registry.sub_registry('v2')
216 @chains.set_default([])
217 @chains_mutex = Mutex.new
219 @upgrade_queue = Queue.new
220 @upgrade_thread = nil
223 @learning_queue = Queue.new
224 @learning_thread = Thread.new do
225 while s = @learning_queue.pop
227 sleep @bot.config['markov.learn_delay'] unless @bot.config['markov.learn_delay'].zero?
230 @learning_thread.priority = -1
234 if @upgrade_thread and @upgrade_thread.alive?
235 debug 'closing conversion thread'
237 @upgrade_queue.push nil
239 debug 'conversion thread closed'
242 debug 'closing learning thread'
243 @learning_queue.push nil
244 @learning_thread.join
245 debug 'learning thread closed'
248 # if passed a pair, pick a word from the registry using the pair as key.
249 # otherwise, pick a word from an given list
250 def pick_word(word1, word2=MARKER)
251 if word1.kind_of? Array
254 k = "#{word1} #{word2}"
255 return MARKER unless @chains.key? k
256 wordlist = @chains[k]
258 total = wordlist.first
260 return MARKER if total == 0
261 return hash.keys.first if hash.length == 1
274 def generate_string(word1, word2)
275 # limit to max of markov.max_words words
277 output = "#{word1} #{word2}"
282 if @chains.key? output
283 wordlist = @chains[output]
284 wordlist.last.delete(MARKER)
288 @chains.each_key(output) do |key|
289 if key.downcase.include? output
296 keys = @chains.keys.select { |k| k.downcase.include? output }
298 return nil if keys.empty?
299 while key = keys.delete_one
300 wordlist = @chains[key]
301 wordlist.last.delete(MARKER)
302 unless wordlist.empty?
304 # split using / / so that we can properly catch the marker
305 word1, word2 = output.split(/ /).map {|w| w.intern}
311 word3 = pick_word(wordlist)
312 return nil if word3 == MARKER
314 output << " #{word3}"
315 word1, word2 = word2, word3
317 (@bot.config['markov.max_words'] - 1).times do
318 word3 = pick_word(word1, word2)
319 break if word3 == MARKER
320 output << " #{word3}"
321 word1, word2 = word2, word3
326 def help(plugin, topic="")
327 topic, subtopic = topic.split
331 "markov delay <value> => Set message delay"
335 "markov ignore add <hostmask|channel> => ignore a hostmask or a channel"
337 "markov ignore list => show ignored hostmasks and channels"
339 "markov ignore remove <hostmask|channel> => unignore a hostmask or channel"
341 "ignore hostmasks or channels -- topics: add, remove, list"
344 "markov status => show if markov is enabled, probability and amount of messages in queue for learning"
346 "markov probability [<percent>] => set the % chance of rbot responding to input, or display the current probability"
350 "markov chat about <word> [<another word>] => talk about <word> or riff on a word pair (if possible)"
352 "markov chat => try to say something intelligent"
355 "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"
361 str.gsub!(/^\S+[:,;]/, "")
362 str.gsub!(/\s{2,}/, ' ') # fix for two or more spaces
367 return @bot.config['markov.probability']
371 if @bot.config['markov.enabled']
372 reply = _("markov is currently enabled, %{p}% chance of chipping in") % { :p => probability? }
373 l = @learning_queue.length
374 reply << (_(", %{l} messages in queue") % {:l => l}) if l > 0
375 l = @upgrade_queue.length
376 reply << (_(", %{l} chains to upgrade") % {:l => l}) if l > 0
378 reply = _("markov is currently disabled")
384 return false unless m
385 return true if m.address? or m.private?
386 @bot.config['markov.ignore'].each do |mask|
387 return true if m.channel.downcase == mask.downcase
388 return true if m.source.matches?(mask)
393 def ignore(m, params)
394 action = params[:action]
395 user = params[:option]
398 if @bot.config['markov.ignore'].include? user
399 s = @bot.config['markov.ignore']
401 @bot.config['ignore'] = s
402 m.reply _("%{u} removed") % { :u => user }
404 m.reply _("not found in list")
408 if @bot.config['markov.ignore'].include?(user)
409 m.reply _("%{u} already in list") % { :u => user }
411 @bot.config['markov.ignore'] = @bot.config['markov.ignore'].push user
412 m.reply _("%{u} added to markov ignore list") % { :u => user }
415 m.reply _("give the name of a person or channel to ignore")
418 m.reply _("I'm ignoring %{ignored}") % { :ignored => @bot.config['markov.ignore'].join(", ") }
420 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")
424 def enable(m, params)
425 @bot.config['markov.enabled'] = true
429 def probability(m, params)
430 if params[:probability]
431 @bot.config['markov.probability'] = params[:probability].to_i
434 m.reply _("markov has a %{prob}% chance of chipping in") % { :prob => probability? }
438 def disable(m, params)
439 @bot.config['markov.enabled'] = false
444 return false unless @bot.config['markov.enabled']
446 return true if prob > rand(100)
450 def set_delay(m, params)
451 if params[:delay] == "off"
452 @bot.config["markov.delay"] = 0
454 elsif !params[:delay]
455 m.reply _("Message delay is %{delay}" % { :delay => @bot.config["markov.delay"]})
457 @bot.config["markov.delay"] = params[:delay].to_i
462 def reply_delay(m, line)
464 if @bot.config['markov.delay'] > 0
465 @bot.timer.add_once(@bot.config['markov.delay']) {
466 m.reply line, :nick => false, :to => :public
469 m.reply line, :nick => false, :to => :public
473 def random_markov(m, message)
474 return unless should_talk
476 word1, word2 = clean_str(message).split(/\s+/)
477 return unless word1 and word2
478 line = generate_string(word1.intern, word2.intern)
480 # we do nothing if the line we return is just an initial substring
481 # of the line we received
482 return if message.index(line) == 0
487 line = generate_string(params[:seed1], params[:seed2])
488 if line and line != [params[:seed1], params[:seed2]].compact.join(" ")
491 m.reply _("I can't :(")
495 def rand_chat(m, params)
496 # pick a random pair from the db and go from there
497 word1, word2 = MARKER, MARKER
499 @bot.config['markov.max_words'].times do
500 word3 = pick_word(word1, word2)
501 break if word3 == MARKER
503 word1, word2 = word2, word3
506 m.reply output.join(" ")
508 m.reply _("I can't :(")
513 lines.each { |l| @learning_queue.push l }
519 # in channel message, the kind we are interested in
520 message = m.plainmessage
523 message = "#{m.sourcenick} #{message}"
527 random_markov(m, message) unless m.replied?
530 def learn_triplet(word1, word2, word3)
531 k = "#{word1} #{word2}"
532 @chains_mutex.synchronize do
542 @chains[k] = [total, hash]
546 def learn_line(message)
547 # debug "learning #{message.inspect}"
548 wordlist = clean_str(message).split(/\s+/).map { |w| w.intern }
549 return unless wordlist.length >= 2
550 word1, word2 = MARKER, MARKER
552 wordlist.each do |word3|
553 learn_triplet(word1, word2, word3)
554 word1, word2 = word2, word3
558 # TODO allow learning from URLs
559 def learn_from(m, params)
562 file = File.open(path, "r")
563 pattern = params[:pattern].empty? ? nil : Regexp.new(params[:pattern].to_s)
565 m.reply _("no such file")
570 m.reply _("the file is empty!")
576 range = case params[:lines]
578 Range.new(*params[:lines].split("..").map { |e| e.to_i })
580 Range.new(1, params[:lines].to_i)
582 Range.new(1, [@bot.config['send.max_lines'], 3].max)
586 next unless file.lineno >= range.begin
588 break if file.lineno == range.end
591 lines = lines.map do |l|
592 pattern ? l.scan(pattern).to_s : l
593 end.reject { |e| e.empty? }
597 m.reply _("example matches for that pattern at lines %{range} include: %{lines}") % {
598 :lines => lines.map { |e| Underline+e+Underline }.join(", "),
602 m.reply _("the pattern doesn't match anything at lines %{range}") % {
607 m.reply _("learning from the file without a pattern would learn, for example: ")
608 lines.each { |l| m.reply l }
615 file.each { |l| learn(l.scan(pattern).to_s) }
617 file.each { |l| learn(l.chomp) }
624 plugin = MarkovPlugin.new
625 plugin.map 'markov delay :delay', :action => "set_delay"
626 plugin.map 'markov delay', :action => "set_delay"
627 plugin.map 'markov ignore :action :option', :action => "ignore"
628 plugin.map 'markov ignore :action', :action => "ignore"
629 plugin.map 'markov ignore', :action => "ignore"
630 plugin.map 'markov enable', :action => "enable"
631 plugin.map 'markov disable', :action => "disable"
632 plugin.map 'markov status', :action => "status"
633 plugin.map 'chat about :seed1 [:seed2]', :action => "chat"
634 plugin.map 'chat', :action => "rand_chat"
635 plugin.map 'markov probability [:probability]', :action => "probability",
636 :requirements => {:probability => /^\d+%?$/}
637 plugin.map 'markov learn from :file [:testing [:lines lines]] [using pattern *pattern]', :action => "learn_from", :thread => true,
639 :testing => /^testing$/,
640 :lines => /^(?:\d+\.\.\d+|\d+)$/ }
642 plugin.default_auth('ignore', false)
643 plugin.default_auth('probability', false)
644 plugin.default_auth('learn', false)