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