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