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