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):/,'')
86 elsif rex.sub!(/^ruby:/,'')
89 @replies << Reply.new(self, act, rex, *args)
95 @replies.delete_at(num-1)
97 return @raw_replies.delete_at(num-1)
101 @replies[@raw_replies.index(expr)] rescue nil
106 pcts = @replies.map { |rep|
113 debug "percentages: #{pcts.inspect}"
116 @replies.each_with_index { |r, i|
118 r.range = last..(last+p)
121 debug "ranges: #{@replies.map { |r| r.range}.inspect}"
126 debug "#{pick} in #{@replies.map { |r| r.range}.inspect}"
128 return r if r.range and r.range === pick
134 return nil if @trigger.first and not message.action
135 return message.message.match(@trigger.last)
150 class ReactionPlugin < Plugin
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()
157 TRIGGER_SYNTAX = /^(?:act:)?(?:!.*?!|\/.*?\/|".*?"|'.*?'|\S+)/
168 return TRIGGER_SYNTAX
175 if @registry.has_key?(:reactions)
176 @reactions = @registry[:reactions]
177 raise LoadError, "corrupted reaction database" unless @reactions
184 :underline => Underline,
187 :normal => NormalText,
195 @registry[:reactions] = @reactions
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"
204 case (topic.to_sym rescue nil)
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"
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."
231 "reaction list [n]: lists the n-the page of programmed reactions (30 reactions are listed per page)"
233 "reaction show <trigger>: list the programmed replies to trigger <trigger>"
235 "reaction topics: add, remove, delete, rm, del, move, triggers, replies, chance, list, show"
240 return unless PrivMessage === m
241 debug "testing #{m} for reactions"
242 return if @reactions.empty?
243 candidates = @reactions.map { |react|
245 blob ? [blob, react] : nil
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
255 before = match.pre_match.strip
256 after = match.post_match.strip
257 target, what = after.split(/\s+/, 2)
259 :who => m.sourcenick,
266 match.to_a.each_with_index { |d, i|
267 extra[:"match#{i}"] = d
269 subs = @subs.dup.merge extra
270 reply = wanted.pick_reply
271 debug "picked #{reply}"
273 act, arg = reply.apply(subs)
277 # no substitutions for ruby code
279 rescue Exception => e
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
298 def find_reaction(trigger)
299 @reactions.find { |react|
300 react.raw_trigger.downcase == trigger.downcase
304 def can_add?(m, reaction)
305 return true if reaction.act == :reply
306 return true if reaction.act == :ruby and @bot.auth.permit?(m.source, "reaction::react::ruby", m.channel)
307 return true if reaction.act == :cmd and @bot.auth.permit?(m.source, "reaction::react::cmd", m.channel)
311 def handle_add(m, params)
312 trigger = params[:trigger].to_s
313 reply = params[:reply].to_s
315 pct = params[:chance] || "1"
317 pct = (pct.to_f/100).clip(0,1)
319 pct = pct.to_f.clip(0,1)
324 reaction = find_reaction(trigger)
326 reaction = Reaction.new(trigger)
327 @reactions << reaction
331 found = reaction.find_reply(reply)
333 # ruby replies need special permission
334 if can_add?(m, found)
336 found.author = m.sourcenick
337 found.date = Time.now
338 found.channel = m.channel
340 m.reply _("Sorry, you're not allowed to change %{act} replies here") % {
346 found = reaction.add_reply(reply, pct, m.sourcenick, Time.now, m.channel)
347 unless can_add?(m, found)
348 m.reply _("Sorry, you're not allowed to add %{act} replies here") % {
351 reaction.rm_reply(reaction.replies.length)
353 @reactions.delete(reaction)
360 m.reply "Ok, I'll start reacting to #{reaction.raw_trigger}"
362 m.reply "I'll react to #{reaction.raw_trigger} with #{reaction.raw_replies.last} (#{(reaction.replies.last.pct * 100).to_i}%)"
365 def handle_move(m, params)
366 source = params[:source].to_s
367 dest = params[:dest].to_s
368 found = find_reaction(source)
370 m.reply "I don't react to #{source}"
373 if find_reaction(dest)
374 m.reply "I already react to #{dest}, so I won't move #{source} to #{dest}"
378 m.reply "Ok, I'll react to #{found.raw_trigger} now"
381 def handle_rm(m, params)
382 trigger = params[:trigger].to_s
385 debug trigger.inspect
386 found = find_reaction(trigger)
390 if n < 1 or n > found.replies.length
391 m.reply "Please specify an index between 1 and #{found.replies.length}"
394 purged = found.rm_reply(n)
395 if found.replies.length == 0
396 @reactions.delete(found)
399 purged = " with #{purged}"
402 @reactions.delete(found)
404 m.reply "I won't react to #{found.raw_trigger}#{purged} anymore"
406 m.reply "no reaction programmed for #{trigger}"
410 def handle_list(m, params)
412 m.reply "no reactions programmed"
417 pages = @reactions.length / per_page + 1
418 page = params[:page].to_i.clip(1, pages)
420 str = @reactions[(page-1)*per_page, per_page].join(", ")
422 m.reply "Programmed reactions (page #{page}/#{pages}): #{str}"
425 def handle_show(m, params)
427 m.reply "no reactions programmed"
431 trigger = params[:trigger].to_s
433 found = find_reaction(trigger)
436 m.reply "I'm not reacting to #{trigger}"
440 m.reply found.replies.join(", ")
445 plugin = ReactionPlugin.new
447 plugin.map plugin.add_syntax, :action => 'handle_add',
448 :requirements => { :trigger => plugin.trigger_syntax }
450 # ruby reactions are security holes, so give stricter permission
451 plugin.default_auth('react::ruby', false)
452 # cmd reactions can be security holes too
453 plugin.default_auth('react::cmd', false)
455 plugin.map 'reaction list [:page]', :action => 'handle_list',
456 :requirements => { :page => /^\d+$/ }
458 plugin.map 'reaction show *trigger', :action => 'handle_show'
460 plugin.map plugin.move_syntax, :action => 'handle_move',
462 :source => plugin.trigger_syntax,
463 :dest => plugin.trigger_syntax
466 plugin.map 'reaction del[ete] *trigger [:n]', :action => 'handle_rm', :auth_path => 'del!',
467 :requirements => { :trigger => plugin.trigger_syntax, :n => /^\d+$/ }
468 plugin.map 'reaction remove *trigger [:n]', :action => 'handle_rm', :auth_path => 'del!',
469 :requirements => { :trigger => plugin.trigger_syntax, :n => /^\d+$/ }
470 plugin.map 'reaction rm *trigger [:n]', :action => 'handle_rm', :auth_path => 'del!',
471 :requirements => { :trigger => plugin.trigger_syntax, :n => /^\d+$/ }