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