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