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