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