4 # :title: Reaction plugin
6 # Author:: Giuseppe Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2007 Giuseppe Bilotta
10 # Build one-liner replies/reactions to expressions/actions in channel
12 # Very alpha stage, so beware of sudden reaction syntax changes
15 attr_reader :trigger, :replies
16 attr_reader :raw_trigger, :raw_replies
19 attr_reader :act, :reply, :pct
21 attr_reader :author, :date, :channel
37 def initialize(reaction, act, expr, pct, author, date, channel)
44 self.channel = channel
49 "#{act} #{reply} (#{pct} chance)",
50 @range ? "(#{@range})" : "",
51 "(#{author}, #{channel}, #{date})"
61 @raw_trigger = expr.dup
64 if rex.sub!(/^act:/,'')
68 if rex.sub!(%r@^([/!])(.*)\1$@, '\2')
69 @trigger << Regexp.new(rex, true)
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)
78 def add_reply(expr, *args)
79 @raw_replies << expr.dup
82 if rex.sub!(/^act:/,'')
84 elsif rex.sub!(/^(?:cmd|command):/,'')
87 @replies << Reply.new(self, act, rex, *args)
93 @replies.delete_at(num-1)
95 return @raw_replies.delete_at(num-1)
99 @replies[@raw_replies.index(expr)] rescue nil
104 pcts = @replies.map { |rep|
111 debug "percentages: #{pcts.inspect}"
114 @replies.each_with_index { |r, i|
116 r.range = last..(last+p)
119 debug "ranges: #{@replies.map { |r| r.range}.inspect}"
124 debug "#{pick} in #{@replies.map { |r| r.range}.inspect}"
126 return r if r.range and r.range === pick
132 return nil if @trigger.first and not message.action
133 return message.message.match(@trigger.last)
148 class ReactionPlugin < Plugin
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()
155 TRIGGER_SYNTAX = /^(?:act:)?(?:!.*?!|\/.*?\/|".*?"|'.*?'|\S+)/
166 return TRIGGER_SYNTAX
173 if @registry.has_key?(:reactions)
174 @reactions = @registry[:reactions]
175 raise LoadError, "corrupted reaction database" unless @reactions
182 :underline => Underline,
185 :normal => NormalText,
193 @registry[:reactions] = @reactions
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"
202 case (topic.to_sym rescue nil)
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"
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)"
226 "reaction list [n]: lists the n-the page of programmed reactions (30 reactions are listed per page)"
228 "reaction show <trigger>: list the programmed replies to trigger <trigger>"
230 "reaction topics: add, remove, delete, rm, del, move, triggers, replies, chance, list, show"
235 return unless PrivMessage === m
236 debug "testing #{m} for reactions"
237 return if @reactions.empty?
238 candidates = @reactions.map { |react|
240 blob ? [blob, react] : nil
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
250 before = match.pre_match.strip
251 after = match.post_match.strip
252 target, what = after.split(/\s+/, 2)
254 :who => m.sourcenick,
261 match.to_a.each_with_index { |d, i|
262 extra[:"match#{i}"] = d
264 subs = @subs.dup.merge extra
265 reply = wanted.pick_reply
266 debug "picked #{reply}"
268 act, arg = reply.apply(subs)
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
286 def find_reaction(trigger)
287 @reactions.find { |react|
288 react.raw_trigger.downcase == trigger.downcase
292 def handle_add(m, params)
293 trigger = params[:trigger].to_s
294 reply = params[:reply].to_s
296 pct = params[:chance] || "1"
298 pct = (pct.to_f/100).clip(0,1)
300 pct = pct.to_f.clip(0,1)
303 reaction = find_reaction(trigger)
305 reaction = Reaction.new(trigger)
306 @reactions << reaction
307 m.reply "Ok, I'll start reacting to #{reaction.raw_trigger}"
309 found = reaction.find_reply(reply)
312 found.author = m.sourcenick
313 found.date = Time.now
314 found.channel = m.channel
316 found = reaction.add_reply(reply, pct, m.sourcenick, Time.now, m.channel)
318 m.reply "I'll react to #{reaction.raw_trigger} with #{reaction.raw_replies.last} (#{(reaction.replies.last.pct * 100).to_i}%)"
321 def handle_move(m, params)
322 source = params[:source].to_s
323 dest = params[:dest].to_s
324 found = find_reaction(source)
326 m.reply "I don't react to #{source}"
329 if find_reaction(dest)
330 m.reply "I already react to #{dest}, so I won't move #{source} to #{dest}"
334 m.reply "Ok, I'll react to #{found.raw_trigger} now"
337 def handle_rm(m, params)
338 trigger = params[:trigger].to_s
341 debug trigger.inspect
342 found = find_reaction(trigger)
346 if n < 1 or n > found.replies.length
347 m.reply "Please specify an index between 1 and #{found.replies.length}"
350 purged = found.rm_reply(n)
351 if found.replies.length == 0
352 @reactions.delete(found)
355 purged = " with #{purged}"
358 @reactions.delete(found)
360 m.reply "I won't react to #{found.raw_trigger}#{purged} anymore"
362 m.reply "no reaction programmed for #{trigger}"
366 def handle_list(m, params)
368 m.reply "no reactions programmed"
373 pages = @reactions.length / per_page + 1
374 page = params[:page].to_i.clip(1, pages)
376 str = @reactions[(page-1)*per_page, per_page].join(", ")
378 m.reply "Programmed reactions (page #{page}/#{pages}): #{str}"
381 def handle_show(m, params)
383 m.reply "no reactions programmed"
387 trigger = params[:trigger].to_s
389 found = find_reaction(trigger)
392 m.reply "I'm not reacting to #{trigger}"
396 m.reply found.replies.join(", ")
401 plugin = ReactionPlugin.new
403 plugin.map plugin.add_syntax, :action => 'handle_add',
404 :requirements => { :trigger => plugin.trigger_syntax }
406 plugin.map 'reaction list [:page]', :action => 'handle_list',
407 :requirements => { :page => /^\d+$/ }
409 plugin.map 'reaction show *trigger', :action => 'handle_show'
411 plugin.map plugin.move_syntax, :action => 'handle_move',
413 :source => plugin.trigger_syntax,
414 :dest => plugin.trigger_syntax
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+$/ }