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