]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/markov.rb
markov plugin: use plain message
[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       end
40     end
41   end
42
43   def cleanup
44     debug 'closing learning thread'
45     @learning_queue.push nil
46     @learning_thread.join
47     debug 'learning thread closed'
48   end
49
50   def generate_string(word1, word2)
51     # limit to max of 50 words
52     output = word1 + " " + word2
53
54     # try to avoid :nonword in the first iteration
55     wordlist = @registry["#{word1} #{word2}"]
56     wordlist.delete(:nonword)
57     if not wordlist.empty?
58       word3 = wordlist[rand(wordlist.length)]
59       output = output + " " + word3
60       word1, word2 = word2, word3
61     end
62
63     49.times do
64       wordlist = @registry["#{word1} #{word2}"]
65       break if wordlist.empty?
66       word3 = wordlist[rand(wordlist.length)]
67       break if word3 == :nonword
68       output = output + " " + word3
69       word1, word2 = word2, word3
70     end
71     return output
72   end
73
74   def help(plugin, topic="")
75     "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)"
76   end
77
78   def clean_str(s)
79     str = s.dup
80     str.gsub!(/^\S+[:,;]/, "")
81     str.gsub!(/\s{2,}/, ' ') # fix for two or more spaces
82     return str.strip
83   end
84
85   def probability?
86     return @bot.config['markov.probability']
87   end
88
89   def status(m,params)
90     if @bot.config['markov.enabled']
91       m.reply "markov is currently enabled, #{probability?}% chance of chipping in"
92     else
93       m.reply "markov is currently disabled"
94     end
95   end
96
97   def ignore?(user=nil)
98     return false unless user
99     @bot.config['markov.ignore_users'].each do |mask|
100       return true if user.matches?(mask)
101     end
102     return false
103   end
104
105   def ignore(m, params)
106     action = params[:action]
107     user = params[:option]
108     case action
109     when 'remove':
110       if @bot.config['markov.ignore_users'].include? user
111         s = @bot.config['markov.ignore_users']
112         s.delete user
113         @bot.config['ignore_users'] = s
114         m.reply "#{user} removed"
115       else
116         m.reply "not found in list"
117       end
118     when 'add':
119       if user
120         if @bot.config['markov.ignore_users'].include?(user)
121           m.reply "#{user} already in list"
122         else
123           @bot.config['markov.ignore_users'] = @bot.config['markov.ignore_users'].push user
124           m.reply "#{user} added to markov ignore list"
125         end
126       else
127         m.reply "give the name of a person to ignore"
128       end
129     when 'list':
130       m.reply "I'm ignoring #{@bot.config['markov.ignore_users'].join(", ")}"
131     else
132       m.reply "have markov ignore the input from a hostmask.  usage: markov ignore add <mask>; markov ignore remove <mask>; markov ignore list"
133     end
134   end
135
136   def enable(m, params)
137     @bot.config['markov.enabled'] = true
138     m.okay
139   end
140
141   def probability(m, params)
142     if params[:probability]
143       @bot.config['markov.probability'] = params[:probability].to_i
144       m.okay
145     else
146       m.reply _("markov has a %{prob}% chance of chipping in") % { :prob => probability? }
147     end
148   end
149
150   def disable(m, params)
151     @bot.config['markov.enabled'] = false
152     m.okay
153   end
154
155   def should_talk
156     return false unless @bot.config['markov.enabled']
157     prob = probability?
158     return true if prob > rand(100)
159     return false
160   end
161
162   def delay
163     1 + rand(5)
164   end
165
166   def random_markov(m, message)
167     return unless should_talk
168
169     word1, word2 = message.split(/\s+/)
170     line = generate_string(word1, word2)
171     return unless line
172     return if line == message
173     @bot.timer.add_once(delay) {
174       m.reply line
175     }
176   end
177
178   def chat(m, params)
179     line = generate_string(params[:seed1], params[:seed2])
180     if line != "#{params[:seed1]} #{params[:seed2]}"
181       m.reply line 
182     else
183       m.reply "I can't :("
184     end
185   end
186
187   def rand_chat(m, params)
188     # pick a random pair from the db and go from there
189     word1, word2 = :nonword, :nonword
190     output = Array.new
191     50.times do
192       wordlist = @registry["#{word1} #{word2}"]
193       break if wordlist.empty?
194       word3 = wordlist[rand(wordlist.length)]
195       break if word3 == :nonword
196       output << word3
197       word1, word2 = word2, word3
198     end
199     if output.length > 1
200       m.reply output.join(" ")
201     else
202       m.reply "I can't :("
203     end
204   end
205   
206   def message(m)
207     return unless m.public?
208     return if m.address?
209     return if ignore? m.source
210
211     # in channel message, the kind we are interested in
212     message = clean_str m.plainmessage
213
214     if m.action?
215       message = "#{m.sourcenick} #{message}"
216     end
217     
218     @learning_queue.push message
219     random_markov(m, message) unless m.replied?
220   end
221
222   def learn(message)
223     # debug "learning #{message}"
224     wordlist = message.split(/\s+/)
225     return unless wordlist.length >= 2
226     word1, word2 = :nonword, :nonword
227     wordlist.each do |word3|
228       k = "#{word1} #{word2}"
229       @registry[k] = @registry[k].push(word3)
230       word1, word2 = word2, word3
231     end
232     k = "#{word1} #{word2}"
233     @registry[k] = @registry[k].push(:nonword)
234   end
235 end
236
237 plugin = MarkovPlugin.new
238 plugin.map 'markov ignore :action :option', :action => "ignore"
239 plugin.map 'markov ignore :action', :action => "ignore"
240 plugin.map 'markov ignore', :action => "ignore"
241 plugin.map 'markov enable', :action => "enable"
242 plugin.map 'markov disable', :action => "disable"
243 plugin.map 'markov status', :action => "status"
244 plugin.map 'chat about :seed1 :seed2', :action => "chat"
245 plugin.map 'chat', :action => "rand_chat"
246 plugin.map 'markov probability [:probability]', :action => "probability",
247            :requirements => {:probability => /^\d+%?$/}