]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/message.rb
registry.rb: suppress warning when @recovery is not defined
[user/henk/code/ruby/rbot.git] / lib / rbot / message.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: IRC message datastructures
5
6 module Irc
7   BotConfig.register BotConfigArrayValue.new('core.address_prefix',
8     :default => [], :wizard => true,
9     :desc => "what non nick-matching prefixes should the bot respond to as if addressed (e.g !, so that '!foo' is treated like 'rbot: foo')"
10   )
11
12   BotConfig.register BotConfigBooleanValue.new('core.reply_with_nick',
13     :default => false, :wizard => true,
14     :desc => "if true, the bot will prepend the nick to what he has to say when replying (e.g. 'markey: you can't do that!')"
15   )
16
17   BotConfig.register BotConfigStringValue.new('core.nick_postfix',
18     :default => ':', :wizard => true,
19     :desc => "when replying with nick put this character after the nick of the user the bot is replying to"
20   )
21
22   # Define standard IRC attriubtes (not so standard actually,
23   # but the closest thing we have ...)
24   Bold = "\002"
25   Underline = "\037"
26   Reverse = "\026"
27   Italic = "\011"
28   NormalText = "\017"
29
30   # Color is prefixed by \003 and followed by optional
31   # foreground and background specifications, two-digits-max
32   # numbers separated by a comma. One of the two parts
33   # must be present.
34   Color = "\003"
35   ColorRx = /#{Color}\d?\d?(?:,\d\d?)?/
36
37   # Standard color codes
38   ColorCode = {
39     :black      => 1,
40     :blue       => 2,
41     :navyblue   => 2,
42     :navy_blue  => 2,
43     :green      => 3,
44     :red        => 4,
45     :brown      => 5,
46     :purple     => 6,
47     :olive      => 7,
48     :yellow     => 8,
49     :limegreen  => 9,
50     :lime_green => 9,
51     :teal       => 10,
52     :aqualight  => 11,
53     :aqua_light => 11,
54     :royal_blue => 12,
55     :hotpink    => 13,
56     :hot_pink   => 13,
57     :darkgray   => 14,
58     :dark_gray  => 14,
59     :lightgray  => 15,
60     :light_gray => 15,
61     :white      => 16
62   }
63
64   # Convert a String or Symbol into a color number
65   def Irc.find_color(data)
66     if Integer === data
67       data
68     else
69       f = if String === data
70             data.intern
71           else
72             data
73           end
74       if ColorCode.key?(f)
75         ColorCode[f] 
76       else
77         0
78       end
79     end
80   end
81
82   # Insert the full color code for a given
83   # foreground/background combination.
84   def Irc.color(fg=nil,bg=nil)
85     str = Color.dup
86     if fg
87      str << Irc.find_color(fg).to_s
88     end
89     if bg
90       str << "," << Irc.find_color(bg).to_s
91     end
92     return str
93   end
94
95   # base user message class, all user messages derive from this
96   # (a user message is defined as having a source hostmask, a target
97   # nick/channel and a message part)
98   class BasicUserMessage
99
100     # associated bot
101     attr_reader :bot
102
103     # associated server
104     attr_reader :server
105
106     # when the message was received
107     attr_reader :time
108
109     # User that originated the message
110     attr_reader :source
111
112     # User/Channel message was sent to
113     attr_reader :target
114
115     # contents of the message
116     attr_accessor :message
117
118     # has the message been replied to/handled by a plugin?
119     attr_accessor :replied
120
121     # instantiate a new Message
122     # bot::      associated bot class
123     # server::   Server where the message took place
124     # source::   User that sent the message
125     # target::   User/Channel is destined for
126     # message::  actual message
127     def initialize(bot, server, source, target, message)
128       @msg_wants_id = false unless defined? @msg_wants_id
129
130       @time = Time.now
131       @bot = bot
132       @source = source
133       @address = false
134       @target = target
135       @message = BasicUserMessage.stripcolour message
136       @replied = false
137       @server = server
138
139       @identified = false
140       if @msg_wants_id && @server.capabilities[:"identify-msg"]
141         if @message =~ /^([-+])(.*)/
142           @identified = ($1=="+")
143           @message = $2
144         else
145           warning "Message does not have identification"
146         end
147       end
148
149       if target && target == @bot.myself
150         @address = true
151       end
152
153     end
154
155     # Access the nick of the source
156     #
157     def sourcenick
158       @source.nick rescue @source.to_s
159     end
160
161     # Access the user@host of the source
162     #
163     def sourceaddress
164       "#{@source.user}@#{@source.host}" rescue @source.to_s
165     end
166
167     # Was the message from an identified user?
168     def identified?
169       return @identified
170     end
171
172     # returns true if the message was addressed to the bot.
173     # This includes any private message to the bot, or any public message
174     # which looks like it's addressed to the bot, e.g. "bot: foo", "bot, foo",
175     # a kick message when bot was kicked etc.
176     def address?
177       return @address
178     end
179
180     # has this message been replied to by a plugin?
181     def replied?
182       return @replied
183     end
184
185     # strip mIRC colour escapes from a string
186     def BasicUserMessage.stripcolour(string)
187       return "" unless string
188       ret = string.gsub(ColorRx, "")
189       #ret.tr!("\x00-\x1f", "")
190       ret
191     end
192
193   end
194
195   # class for handling IRC user messages. Includes some utilities for handling
196   # the message, for example in plugins.
197   # The +message+ member will have any bot addressing "^bot: " removed
198   # (address? will return true in this case)
199   class UserMessage < BasicUserMessage
200
201     # for plugin messages, the name of the plugin invoked by the message
202     attr_reader :plugin
203
204     # for plugin messages, the rest of the message, with the plugin name
205     # removed
206     attr_reader :params
207
208     # convenience member. Who to reply to (i.e. would be sourcenick for a
209     # privately addressed message, or target (the channel) for a publicly
210     # addressed message
211     attr_reader :replyto
212
213     # channel the message was in, nil for privately addressed messages
214     attr_reader :channel
215
216     # for PRIVMSGs, false unless the message was a CTCP command,
217     # in which case it evaluates to the CTCP command itself
218     # (TIME, PING, VERSION, etc). The CTCP command parameters
219     # are then stored in the message.
220     attr_reader :ctcp
221
222     # for PRIVMSGs, true if the message was a CTCP ACTION (CTCP stuff
223     # will be stripped from the message)
224     attr_reader :action
225
226     # instantiate a new UserMessage
227     # bot::      associated bot class
228     # source::   hostmask of the message source
229     # target::   nick/channel message is destined for
230     # message::  message part
231     def initialize(bot, server, source, target, message)
232       super(bot, server, source, target, message)
233       @target = target
234       @private = false
235       @plugin = nil
236       @ctcp = false
237       @action = false
238
239       if target == @bot.myself
240         @private = true
241         @address = true
242         @channel = nil
243         @replyto = source
244       else
245         @replyto = @target
246         @channel = @target
247       end
248
249       # check for option extra addressing prefixes, e.g "|search foo", or
250       # "!version" - first match wins
251       bot.config['core.address_prefix'].each {|mprefix|
252         if @message.gsub!(/^#{Regexp.escape(mprefix)}\s*/, "")
253           @address = true
254           break
255         end
256       }
257
258       # even if they used above prefixes, we allow for silly people who
259       # combine all possible types, e.g. "|rbot: hello", or
260       # "/msg rbot rbot: hello", etc
261       if @message.gsub!(/^\s*#{Regexp.escape(bot.nick)}\s*([:;,>]|\s)\s*/i, "")
262         @address = true
263       end
264
265       if(@message =~ /^\001(\S+)(\s(.+))?\001/)
266         @ctcp = $1
267         # FIXME need to support quoting of NULL and CR/LF, see
268         # http://www.irchelp.org/irchelp/rfc/ctcpspec.html
269         @message = $3 || String.new
270         @action = @ctcp == 'ACTION'
271         debug "Received CTCP command #{@ctcp} with options #{@message} (action? #{@action})"
272       end
273
274       # free splitting for plugins
275       @params = @message.dup
276       if @params.gsub!(/^\s*(\S+)[\s$]*/, "")
277         @plugin = $1.downcase
278         @params = nil unless @params.length > 0
279       end
280     end
281
282     # returns true for private messages, e.g. "/msg bot hello"
283     def private?
284       return @private
285     end
286
287     # returns true if the message was in a channel
288     def public?
289       return !@private
290     end
291
292     def action?
293       return @action
294     end
295
296     # convenience method to reply to a message, useful in plugins. It's the
297     # same as doing:
298     # <tt>@bot.say m.replyto, string</tt>
299     # So if the message is private, it will reply to the user. If it was
300     # in a channel, it will reply in the channel.
301     def plainreply(string, options={})
302       @bot.say @replyto, string, options
303       @replied = true
304     end
305
306     # Same as reply, but when replying in public it adds the nick of the user
307     # the bot is replying to
308     def nickreply(string, options={})
309       extra = self.public? ? "#{@source}#{@bot.config['core.nick_postfix']} " : ""
310       @bot.say @replyto, extra + string, options
311       @replied = true
312     end
313
314     # the default reply style is to nickreply unless the reply already contains
315     # the nick or core.reply_with_nick is set to false
316     #
317     def reply(string, options={})
318       if @bot.config['core.reply_with_nick'] and not string =~ /\b#{@source}\b/
319         return nickreply(string, options)
320       end
321       plainreply(string, options)
322     end
323
324     # convenience method to reply to a message with an action. It's the
325     # same as doing:
326     # <tt>@bot.action m.replyto, string</tt>
327     # So if the message is private, it will reply to the user. If it was
328     # in a channel, it will reply in the channel.
329     def act(string, options={})
330       @bot.action @replyto, string, options
331       @replied = true
332     end
333
334     # send a CTCP response, i.e. a private NOTICE to the sender
335     # with the same CTCP command and the reply as a parameter
336     def ctcp_reply(string, options={})
337       @bot.ctcp_notice @source, @ctcp, string, options
338     end
339
340     # convenience method to reply "okay" in the current language to the
341     # message
342     def plainokay
343       self.plainreply @bot.lang.get("okay")
344     end
345
346     # Like the above, but append the username
347     def nickokay
348       str = @bot.lang.get("okay").dup
349       if self.public?
350         # remove final punctuation
351         str.gsub!(/[!,.]$/,"")
352         str += ", #{@source}"
353       end
354       self.plainreply str
355     end
356
357     # the default okay style is the same as the default reply style
358     #
359     def okay
360       if @bot.config['core.reply_with_nick']
361         return nickokay
362       end
363       plainokay
364     end
365
366   end
367
368   # class to manage IRC PRIVMSGs
369   class PrivMessage < UserMessage
370     def initialize(bot, server, source, target, message)
371       @msg_wants_id = true
372       super
373     end
374   end
375
376   # class to manage IRC NOTICEs
377   class NoticeMessage < UserMessage
378     def initialize(bot, server, source, target, message)
379       @msg_wants_id = true
380       super
381     end
382   end
383
384   # class to manage IRC KICKs
385   # +address?+ can be used as a shortcut to see if the bot was kicked,
386   # basically, +target+ was kicked from +channel+ by +source+ with +message+
387   class KickMessage < BasicUserMessage
388     # channel user was kicked from
389     attr_reader :channel
390
391     def initialize(bot, server, source, target, channel, message="")
392       super(bot, server, source, target, message)
393       @channel = channel
394     end
395   end
396
397   # class to pass IRC Nick changes in. @message contains the old nickame,
398   # @sourcenick contains the new one.
399   class NickMessage < BasicUserMessage
400     def initialize(bot, server, source, oldnick, newnick)
401       super(bot, server, source, oldnick, newnick)
402     end
403
404     def oldnick
405       return @target
406     end
407
408     def newnick
409       return @message
410     end
411   end
412
413   class QuitMessage < BasicUserMessage
414     def initialize(bot, server, source, target, message="")
415       super(bot, server, source, target, message)
416     end
417   end
418
419   class TopicMessage < BasicUserMessage
420     # channel topic
421     attr_reader :topic
422     # topic set at (unixtime)
423     attr_reader :timestamp
424     # topic set on channel
425     attr_reader :channel
426
427     def initialize(bot, server, source, channel, topic=ChannelTopic.new)
428       super(bot, server, source, channel, topic.text)
429       @topic = topic
430       @timestamp = topic.set_on
431       @channel = channel
432     end
433   end
434
435   # class to manage channel joins
436   class JoinMessage < BasicUserMessage
437     # channel joined
438     attr_reader :channel
439     def initialize(bot, server, source, channel, message="")
440       super(bot, server, source, channel, message)
441       @channel = channel
442       # in this case sourcenick is the nick that could be the bot
443       @address = (source == @bot.myself)
444     end
445   end
446
447   # class to manage channel parts
448   # same as a join, but can have a message too
449   class PartMessage < JoinMessage
450   end
451 end