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