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