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