]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/reaction.rb
* (reaction plugin) make rm recalculate chances of replies
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / reaction.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Reaction plugin
5 #
6 # Author:: Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2007 Giuseppe Bilotta
8 # License:: GPLv2
9 #
10 # Build one-liner replies/reactions to expressions/actions in channel
11 #
12 # Very alpha stage, so beware of sudden reaction syntax changes
13
14 class ::Reaction
15   attr_reader :trigger, :replies
16   attr_reader :raw_trigger, :raw_replies
17
18   class ::Reply
19     attr_reader :act, :reply, :pct
20     attr_accessor :range
21     attr_reader :author, :date, :channel
22     attr_writer :date
23
24     def pct=(val)
25       @pct = val
26       @reaction.make_ranges
27     end
28
29     def author=(name)
30       @author = name.to_s
31     end
32
33     def channel=(name)
34       @channel = name.to_s
35     end
36
37     def initialize(reaction, act, expr, pct, author, date, channel)
38       @reaction = reaction
39       @act = act
40       @reply = expr
41       self.pct = pct
42       self.author = author
43       @date = date
44       self.channel = channel
45     end
46
47     def to_s
48       [
49         "#{act} #{reply} (#{pct} chance)",
50         @range ? "(#{@range})" : "",
51         "(#{author}, #{channel}, #{date})"
52       ].join(" ")
53     end
54
55     def apply(subs={})
56       [act, reply % subs]
57     end
58   end
59
60   def trigger=(expr)
61     @raw_trigger = expr.dup
62     act = false
63     rex = expr.dup
64     if rex.sub!(/^act:/,'')
65       act = true
66     end
67     @trigger = [act]
68     if rex.sub!(%r@^([/!])(.*)\1$@, '\2')
69       @trigger << Regexp.new(rex, true)
70     else
71       rex.sub!(/^(["'])(.*)\1$/, '\2')
72       @trigger << Regexp.new(/\b#{Regexp.escape(rex)}(?:\b|$)/ui)
73     end
74   end
75
76   def add_reply(expr, *args)
77     @raw_replies << expr.dup
78     act = :reply
79     rex = expr.dup
80     if rex.sub!(/^act:/,'')
81       act = :act
82     elsif rex.sub!(/^(?:cmd|command):/,'')
83       act = :cmd
84     end
85     @replies << Reply.new(self, act, rex, *args)
86     make_ranges
87     return @replies.last
88   end
89
90   def rm_reply(num)
91     @replies.delete_at(num-1)
92     make_ranges
93     return @raw_replies.delete_at(num-1)
94   end
95
96   def find_reply(expr)
97     @replies[@raw_replies.index(expr)] rescue nil
98   end
99
100   def make_ranges
101     totals = 0
102     pcts = @replies.map { |rep|
103       totals += rep.pct
104       rep.pct
105     }
106     pcts.map! { |p|
107       p/totals
108     } if totals > 1
109     debug "percentages: #{pcts.inspect}"
110
111     last = 0
112     @replies.each_with_index { |r, i|
113       p = pcts[i]
114       r.range = last..(last+p)
115       last+=p
116     }
117     debug "ranges: #{@replies.map { |r| r.range}.inspect}"
118   end
119
120   def pick_reply
121     pick = rand()
122     debug "#{pick} in #{@replies.map { |r| r.range}.inspect}"
123     @replies.each { |r|
124       return r if r.range and r.range === pick
125     }
126     return nil
127   end
128
129   def ===(message)
130     return nil if @trigger.first and not message.action
131     return message.message.match(@trigger.last)
132   end
133
134   def initialize(trig)
135     self.trigger=trig
136     @raw_replies = []
137     @replies = []
138   end
139
140   def to_s
141     raw_trigger
142   end
143
144 end
145
146 class ReactionPlugin < Plugin
147
148   ADD_SYNTAX = 'react to *trigger with *reply [at :chance chance]'
149   MOVE_SYNTAX = 'reaction move *source to *dest'
150   # We'd like to use backreferences for the trigger syntax
151   # but we can't because it will be merged with the Plugin#map()
152   # regexp
153   TRIGGER_SYNTAX = /^(?:act:)?(?:!.*?!|\/.*?\/|".*?"|'.*?'|\S+)/
154
155   def add_syntax
156     return ADD_SYNTAX
157   end
158
159   def move_syntax
160     return MOVE_SYNTAX
161   end
162
163   def trigger_syntax
164     return TRIGGER_SYNTAX
165   end
166
167   attr :reactions
168
169   def initialize
170     super
171     if @registry.has_key?(:reactions)
172       @reactions = @registry[:reactions]
173       raise unless @reactions
174     else
175       @reactions = []
176     end
177
178     @subs = {
179       :bold => Bold,
180       :underline => Underline,
181       :reverse => Reverse,
182       :italic => Italic,
183       :normal => NormalText,
184       :color => Color,
185       :colour => Color,
186       :bot => @bot.myself,
187     }.merge ColorCode
188   end
189
190   def save
191     @registry[:reactions] = @reactions
192   end
193
194   def help(plugin, topic="")
195     if plugin.to_sym == :react
196       return "react to <trigger> with <reply> [at <chance> chance] => " +
197       "create a new reaction to expression <trigger> to which the bot will reply <reply>, optionally at chance <chance>, " +
198       "seek help for reaction trigger, reaction reply and reaction chance for more details"
199     end
200     case (topic.to_sym rescue nil)
201     when :add
202       help(:react)
203     when :remove, :delete, :rm, :del
204       "reaction #{topic} <trigger> [<n>] => removes reactions to expression <trigger>. If <n> (a positive integer) is specified, only remove the n-th reaction, otherwise remove the trigger completely"
205     when :chance, :chances
206       "reaction chances are expressed either in terms of percentage (like 30%) or in terms of floating point numbers (like 0.3), and are clipped to be " +
207       "between 0 and 1 (i.e. 0% and 100%). A reaction can have multiple replies, each with a different chance; if the total of the chances is less than one, " +
208       "there is a chance that the trigger will not actually cause a reply. Otherwise, the chances express the relative frequency of the replies."
209     when :trigger, :triggers
210       "reaction triggers can have one of the format: single_word 'multiple words' \"multiple words \" /regular_expression/ !regular_expression!. " + 
211       "If prefixed by 'act:' (e.g. act:/(order|command)s/) the bot will only respond if a CTCP ACTION matches the trigger"
212     when :reply, :replies
213       "reaction replies are simply messages that the bot will reply when a trigger is matched. " +
214       "Replies can be prefixed by 'act:' (e.g. act:goes shopping) to signify that the bot should act instead of saying the message. " +
215       "Replies can be prefixed by 'cmd:' or 'command:' (e.g. cmd:lart %{who}) to issue a command to the bot. " +
216       "Replies can use the %{key} syntax to access one of the following keys: " +
217       "who (the user that said the trigger), bot (the bot's own nick), " +
218       "target (the first word following the trigger), what (whatever follows target), " +
219       "before (everything that precedes the trigger), after, (everything that follows the trigger), " +
220       "match (the actual matched text), match1, match2, ... (the i-th capture)"
221     when :list
222       "reaction list [n]: lists the n-the page of programmed reactions (30 reactions are listed per page)"
223     when :show
224       "reaction show <trigger>: list the programmed replies to trigger <trigger>"
225     else
226       "reaction topics: add, remove, delete, rm, del, triggers, replies, chance, list, show"
227     end
228   end
229
230   def unreplied(m)
231     return unless PrivMessage === m
232     debug "testing #{m} for reactions"
233     return if @reactions.empty?
234     candidates = @reactions.map { |react|
235       blob = react === m
236       blob ? [blob, react] : nil
237     }.compact
238     return if candidates.empty?
239     match, wanted = candidates.sort { |m1, m2|
240       # Order by longest matching text first,
241       # and by number of captures second
242       longer = m1.first[0].length <=> m2.first[0].length
243       longer == 0 ? m1.first.length <=> m2.first.length : longer
244     }.last
245     matched = match[0]
246     before = match.pre_match.strip
247     after = match.post_match.strip
248     target, what = after.split(/\s+/, 2)
249     extra = {
250       :who => m.sourcenick,
251       :match => matched,
252       :target => target,
253       :what => what,
254       :before => before,
255       :after => after
256     }
257     match.to_a.each_with_index { |d, i|
258       extra[:"match#{i}"] = d
259     }
260     subs = @subs.dup.merge extra
261     reply = wanted.pick_reply
262     debug "picked #{reply}"
263     return unless reply
264     args = reply.apply(subs)
265     if args[0] == :cmd
266       new_m = PrivMessage.new(@bot, m.server, m.source, m.target, @bot.nick+": "+args[1])
267       @bot.plugins.delegate "listen", new_m
268       @bot.plugins.privmsg(new_m) if new_m.address?
269     else
270       m.__send__(*args)
271     end
272   end
273
274   def find_reaction(trigger)
275     @reactions.find { |react|
276       react.raw_trigger.downcase == trigger.downcase
277     }
278   end
279
280   def handle_add(m, params)
281     trigger = params[:trigger].to_s
282     reply = params[:reply].to_s
283
284     pct = params[:chance] || "1"
285     if pct.sub!(/%$/,'')
286       pct = (pct.to_f/100).clip(0,1)
287     else
288       pct = pct.to_f.clip(0,1)
289     end
290
291     reaction = find_reaction(trigger)
292     if not reaction
293       reaction = Reaction.new(trigger)
294       @reactions << reaction
295       m.reply "Ok, I'll start reacting to #{reaction.raw_trigger}"
296     end
297     found = reaction.find_reply(reply)
298     if found
299       found.pct = pct
300       found.author = m.sourcenick
301       found.date = Time.now
302       found.channel = m.channel
303     else
304       found = reaction.add_reply(reply, pct, m.sourcenick, Time.now, m.channel)
305     end
306     m.reply "I'll react to #{reaction.raw_trigger} with #{reaction.raw_replies.last} (#{(reaction.replies.last.pct * 100).to_i}%)"
307   end
308
309   def handle_move(m, params)
310     source = params[:source].to_s
311     dest = params[:dest].to_s
312     found = find_reaction(source)
313     if not found
314       m.reply "I don't react to #{source}"
315       return
316     end
317     if find_reaction(dest)
318       m.reply "I already react to #{dest}, so I won't move #{source} to #{dest}"
319       return
320     end
321     found.trigger=dest
322     m.reply "Ok, I'll react to #{found.raw_trigger} now"
323   end
324
325   def handle_rm(m, params)
326     trigger = params[:trigger].to_s
327     n = params[:n]
328     n = n.to_i if n
329     debug trigger.inspect
330     found = find_reaction(trigger)
331     purged = nil
332     if found
333       if n
334         if n < 1 or n > found.replies.length
335           m.reply "Please specify an index between 1 and #{found.replies.length}"
336           return
337         end
338         purged = found.rm_reply(n)
339         if found.replies.length == 0
340           @reactions.delete(found)
341           purged = nil
342         else
343           purged = " with #{purged}"
344         end
345       else
346         @reactions.delete(found)
347       end
348       m.reply "I won't react to #{found.raw_trigger}#{purged} anymore"
349     else
350       m.reply "no reaction programmed for #{trigger}"
351     end
352   end
353
354   def handle_list(m, params)
355     if @reactions.empty?
356       m.reply "no reactions programmed"
357       return
358     end
359
360     per_page = 30
361     pages = @reactions.length / per_page + 1
362     page = params[:page].to_i.clip(1, pages)
363
364     str = @reactions[(page-1)*per_page, per_page].join(", ")
365
366     m.reply "Programmed reactions (page #{page}/#{pages}): #{str}"
367   end
368
369   def handle_show(m, params)
370     if @reactions.empty?
371       m.reply "no reactions programmed"
372       return
373     end
374
375     trigger = params[:trigger].to_s
376
377     found = find_reaction(trigger)
378
379     unless found
380       m.reply "I'm not reacting to #{trigger}"
381       return
382     end
383
384     m.reply found.replies.join(", ")
385   end
386
387 end
388
389 plugin = ReactionPlugin.new
390
391 plugin.map plugin.add_syntax, :action => 'handle_add',
392   :requirements => { :trigger => plugin.trigger_syntax }
393
394 plugin.map 'reaction list [:page]', :action => 'handle_list',
395   :requirements => { :page => /^\d+$/ }
396
397 plugin.map 'reaction show *trigger', :action => 'handle_show'
398
399 plugin.map plugin.move_syntax, :action => 'handle_move',
400   :requirements => {
401     :source => plugin.trigger_syntax,
402     :dest => plugin.trigger_syntax
403   }
404
405 plugin.map 'reaction del[ete] *trigger [:n]', :action => 'handle_rm', :auth_path => 'del!',
406   :requirements => { :trigger => plugin.trigger_syntax, :n => /^\d+$/ }
407 plugin.map 'reaction remove *trigger [:n]', :action => 'handle_rm', :auth_path => 'del!',
408   :requirements => { :trigger => plugin.trigger_syntax, :n => /^\d+$/ }
409 plugin.map 'reaction rm *trigger [:n]', :action => 'handle_rm', :auth_path => 'del!',
410   :requirements => { :trigger => plugin.trigger_syntax, :n => /^\d+$/ }