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