]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/message.rb
* fix handling of IDENTIFY_MSG
[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
8
9   class Bot
10     module Config
11       Config.register ArrayValue.new('core.address_prefix',
12         :default => [], :wizard => true,
13         :desc => "what non nick-matching prefixes should the bot respond to as if addressed (e.g !, so that '!foo' is treated like 'rbot: foo')"
14       )
15
16       Config.register BooleanValue.new('core.reply_with_nick',
17         :default => false, :wizard => true,
18         :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!')"
19       )
20
21       Config.register StringValue.new('core.nick_postfix',
22         :default => ':', :wizard => true,
23         :desc => "when replying with nick put this character after the nick of the user the bot is replying to"
24       )
25     end
26   end
27
28
29   # Define standard IRC attriubtes (not so standard actually,
30   # but the closest thing we have ...)
31   Bold = "\002"
32   Underline = "\037"
33   Reverse = "\026"
34   Italic = "\011"
35   NormalText = "\017"
36   AttributeRx = /#{Bold}|#{Underline}|#{Reverse}|#{Italic}|#{NormalText}/
37
38   # Color is prefixed by \003 and followed by optional
39   # foreground and background specifications, two-digits-max
40   # numbers separated by a comma. One of the two parts
41   # must be present.
42   Color = "\003"
43   ColorRx = /#{Color}\d?\d?(?:,\d\d?)?/
44
45   FormattingRx = /#{AttributeRx}|#{ColorRx}/
46
47   # Standard color codes
48   ColorCode = {
49     :black      => 1,
50     :blue       => 2,
51     :navyblue   => 2,
52     :navy_blue  => 2,
53     :green      => 3,
54     :red        => 4,
55     :brown      => 5,
56     :purple     => 6,
57     :olive      => 7,
58     :yellow     => 8,
59     :limegreen  => 9,
60     :lime_green => 9,
61     :teal       => 10,
62     :aqualight  => 11,
63     :aqua_light => 11,
64     :royal_blue => 12,
65     :hotpink    => 13,
66     :hot_pink   => 13,
67     :darkgray   => 14,
68     :dark_gray  => 14,
69     :lightgray  => 15,
70     :light_gray => 15,
71     :white      => 16
72   }
73
74   # Convert a String or Symbol into a color number
75   def Irc.find_color(data)
76     "%02d" % if Integer === data
77       data
78     else
79       f = if String === data
80             data.intern
81           else
82             data
83           end
84       if ColorCode.key?(f)
85         ColorCode[f] 
86       else
87         0
88       end
89     end
90   end
91
92   # Insert the full color code for a given
93   # foreground/background combination.
94   def Irc.color(fg=nil,bg=nil)
95     str = Color.dup
96     if fg
97      str << Irc.find_color(fg)
98     end
99     if bg
100       str << "," << Irc.find_color(bg)
101     end
102     return str
103   end
104
105   # base user message class, all user messages derive from this
106   # (a user message is defined as having a source hostmask, a target
107   # nick/channel and a message part)
108   class BasicUserMessage
109
110     # associated bot
111     attr_reader :bot
112
113     # associated server
114     attr_reader :server
115
116     # when the message was received
117     attr_reader :time
118
119     # User that originated the message
120     attr_reader :source
121
122     # User/Channel message was sent to
123     attr_reader :target
124
125     # contents of the message (stripped of initial/final format codes)
126     attr_accessor :message
127
128     # contents of the message (for logging purposes)
129     attr_accessor :logmessage
130
131     # contents of the message (stripped of all formatting)
132     attr_accessor :plainmessage
133
134     # has the message been replied to/handled by a plugin?
135     attr_accessor :replied
136     alias :replied? :replied
137
138     # should the message be ignored?
139     attr_accessor :ignored
140     alias :ignored? :ignored
141
142     # set this to true if the method that delegates the message is run in a thread
143     attr_accessor :in_thread
144     alias :in_thread? :in_thread
145
146     def inspect(fields=nil)
147       ret = self.__to_s__[0..-2]
148       ret << ' bot=' << @bot.__to_s__
149       ret << ' server=' << server.to_s
150       ret << ' time=' << time.to_s
151       ret << ' source=' << source.to_s
152       ret << ' target=' << target.to_s
153       ret << ' message=' << message.inspect
154       ret << ' logmessage=' << logmessage.inspect
155       ret << ' plainmessage=' << plainmessage.inspect
156       ret << fields if fields
157       ret << ' (identified)' if identified?
158       ret << ' (addressed to me)' if identified?
159       ret << ' (replied)' if replied?
160       ret << ' (ignored)' if ignored?
161       ret << ' (in thread)' if in_thread?
162       ret << '>'
163     end
164
165     # instantiate a new Message
166     # bot::      associated bot class
167     # server::   Server where the message took place
168     # source::   User that sent the message
169     # target::   User/Channel is destined for
170     # message::  actual message
171     def initialize(bot, server, source, target, message)
172       @msg_wants_id = false unless defined? @msg_wants_id
173
174       @time = Time.now
175       @bot = bot
176       @source = source
177       @address = false
178       @target = target
179       @message = message || ""
180       @replied = false
181       @server = server
182       @ignored = false
183       @in_thread = false
184
185       @identified = false
186       if @msg_wants_id && @server.capabilities[:"identify-msg"]
187         if @message =~ /^([-+])(.*)/
188           @identified = ($1=="+")
189           @message = $2
190         else
191           warning "Message does not have identification"
192         end
193       end
194       @logmessage = @message.dup
195       @plainmessage = BasicUserMessage.strip_formatting(@message)
196       @message = BasicUserMessage.strip_initial_formatting(@message)
197
198       if target && target == @bot.myself
199         @address = true
200       end
201
202     end
203
204     # Access the nick of the source
205     #
206     def sourcenick
207       @source.nick rescue @source.to_s
208     end
209
210     # Access the user@host of the source
211     #
212     def sourceaddress
213       "#{@source.user}@#{@source.host}" rescue @source.to_s
214     end
215
216     # Access the botuser corresponding to the source, if any
217     #
218     def botuser
219       source.botuser rescue @bot.auth.everyone
220     end
221
222
223     # Was the message from an identified user?
224     def identified?
225       return @identified
226     end
227
228     # returns true if the message was addressed to the bot.
229     # This includes any private message to the bot, or any public message
230     # which looks like it's addressed to the bot, e.g. "bot: foo", "bot, foo",
231     # a kick message when bot was kicked etc.
232     def address?
233       return @address
234     end
235
236     # has this message been replied to by a plugin?
237     def replied?
238       return @replied
239     end
240
241     # strip mIRC colour escapes from a string
242     def BasicUserMessage.stripcolour(string)
243       return "" unless string
244       ret = string.gsub(ColorRx, "")
245       #ret.tr!("\x00-\x1f", "")
246       ret
247     end
248
249     def BasicUserMessage.strip_initial_formatting(string)
250       return "" unless string
251       ret = string.gsub(/^#{FormattingRx}|#{FormattingRx}$/,"")
252     end
253
254     def BasicUserMessage.strip_formatting(string)
255       string.gsub(FormattingRx,"")
256     end
257
258   end
259
260   # class for handling welcome messages from the server
261   class WelcomeMessage < BasicUserMessage
262   end
263
264   # class for handling MOTD from the server. Yes, MotdMessage
265   # is somewhat redundant, but it fits with the naming scheme
266   class MotdMessage < BasicUserMessage
267   end
268
269   # class for handling IRC user messages. Includes some utilities for handling
270   # the message, for example in plugins.
271   # The +message+ member will have any bot addressing "^bot: " removed
272   # (address? will return true in this case)
273   class UserMessage < BasicUserMessage
274
275     def inspect
276       fields = ' plugin=' << plugin.inspect
277       fields << ' params=' << params.inspect
278       fields << ' channel=' << channel.to_s if channel
279       fields << ' (reply to ' << replyto.to_s << ')'
280       if self.private?
281         fields << ' (private)'
282       else
283         fields << ' (public)'
284       end
285       if self.action?
286         fields << ' (action)'
287       elsif ctcp
288         fields << ' (CTCP ' << ctcp << ')'
289       end
290       super(fields)
291     end
292
293     # for plugin messages, the name of the plugin invoked by the message
294     attr_reader :plugin
295
296     # for plugin messages, the rest of the message, with the plugin name
297     # removed
298     attr_reader :params
299
300     # convenience member. Who to reply to (i.e. would be sourcenick for a
301     # privately addressed message, or target (the channel) for a publicly
302     # addressed message
303     attr_reader :replyto
304
305     # channel the message was in, nil for privately addressed messages
306     attr_reader :channel
307
308     # for PRIVMSGs, false unless the message was a CTCP command,
309     # in which case it evaluates to the CTCP command itself
310     # (TIME, PING, VERSION, etc). The CTCP command parameters
311     # are then stored in the message.
312     attr_reader :ctcp
313
314     # for PRIVMSGs, true if the message was a CTCP ACTION (CTCP stuff
315     # will be stripped from the message)
316     attr_reader :action
317
318     # instantiate a new UserMessage
319     # bot::      associated bot class
320     # source::   hostmask of the message source
321     # target::   nick/channel message is destined for
322     # message::  message part
323     def initialize(bot, server, source, target, message)
324       super(bot, server, source, target, message)
325       @target = target
326       @private = false
327       @plugin = nil
328       @ctcp = false
329       @action = false
330
331       if target == @bot.myself
332         @private = true
333         @address = true
334         @channel = nil
335         @replyto = source
336       else
337         @replyto = @target
338         @channel = @target
339       end
340
341       # check for option extra addressing prefixes, e.g "|search foo", or
342       # "!version" - first match wins
343       bot.config['core.address_prefix'].each {|mprefix|
344         if @message.gsub!(/^#{Regexp.escape(mprefix)}\s*/, "")
345           @address = true
346           break
347         end
348       }
349
350       # even if they used above prefixes, we allow for silly people who
351       # combine all possible types, e.g. "|rbot: hello", or
352       # "/msg rbot rbot: hello", etc
353       if @message.gsub!(/^\s*#{Regexp.escape(bot.nick)}\s*([:;,>]|\s)\s*/i, "")
354         @address = true
355       end
356
357       if(@message =~ /^\001(\S+)(\s(.+))?\001/)
358         @ctcp = $1
359         # FIXME need to support quoting of NULL and CR/LF, see
360         # http://www.irchelp.org/irchelp/rfc/ctcpspec.html
361         @message = $3 || String.new
362         @action = @ctcp == 'ACTION'
363         debug "Received CTCP command #{@ctcp} with options #{@message} (action? #{@action})"
364         @logmessage = @message.dup
365       end
366
367       # free splitting for plugins
368       @params = @message.dup
369       # Created messges (such as by fake_message) can contain multiple lines
370       if @params.gsub!(/\A\s*(\S+)[\s$]*/m, "")
371         @plugin = $1.downcase
372         @params = nil unless @params.length > 0
373       end
374     end
375
376     # returns true for private messages, e.g. "/msg bot hello"
377     def private?
378       return @private
379     end
380
381     # returns true if the message was in a channel
382     def public?
383       return !@private
384     end
385
386     def action?
387       return @action
388     end
389
390     # convenience method to reply to a message, useful in plugins. It's the
391     # same as doing:
392     # <tt>@bot.say m.replyto, string</tt>
393     # So if the message is private, it will reply to the user. If it was
394     # in a channel, it will reply in the channel.
395     def plainreply(string, options={})
396       @bot.say @replyto, string, options
397       @replied = true
398     end
399
400     # Same as reply, but when replying in public it adds the nick of the user
401     # the bot is replying to
402     def nickreply(string, options={})
403       extra = self.public? ? "#{@source}#{@bot.config['core.nick_postfix']} " : ""
404       @bot.say @replyto, extra + string, options
405       @replied = true
406     end
407
408     # the default reply style is to nickreply unless the reply already contains
409     # the nick or core.reply_with_nick is set to false
410     #
411     def reply(string, options={})
412       if @bot.config['core.reply_with_nick'] and not string =~ /(?:^|\W)#{Regexp.escape(@source.to_s)}(?:$|\W)/
413         return nickreply(string, options)
414       end
415       plainreply(string, options)
416     end
417
418     # convenience method to reply to a message with an action. It's the
419     # same as doing:
420     # <tt>@bot.action m.replyto, string</tt>
421     # So if the message is private, it will reply to the user. If it was
422     # in a channel, it will reply in the channel.
423     def act(string, options={})
424       @bot.action @replyto, string, options
425       @replied = true
426     end
427
428     # send a CTCP response, i.e. a private NOTICE to the sender
429     # with the same CTCP command and the reply as a parameter
430     def ctcp_reply(string, options={})
431       @bot.ctcp_notice @source, @ctcp, string, options
432     end
433
434     # convenience method to reply "okay" in the current language to the
435     # message
436     def plainokay
437       self.plainreply @bot.lang.get("okay")
438     end
439
440     # Like the above, but append the username
441     def nickokay
442       str = @bot.lang.get("okay").dup
443       if self.public?
444         # remove final punctuation
445         str.gsub!(/[!,.]$/,"")
446         str += ", #{@source}"
447       end
448       self.plainreply str
449     end
450
451     # the default okay style is the same as the default reply style
452     #
453     def okay
454       if @bot.config['core.reply_with_nick']
455         return nickokay
456       end
457       plainokay
458     end
459
460     # send a NOTICE to the message source
461     #
462     def notify(msg,opts={})
463       @bot.notice(sourcenick, msg, opts)
464     end
465
466   end
467
468   # class to manage IRC PRIVMSGs
469   class PrivMessage < UserMessage
470     def initialize(bot, server, source, target, message, opts={})
471       @msg_wants_id = opts[:handle_id]
472       super(bot, server, source, target, message)
473     end
474   end
475
476   # class to manage IRC NOTICEs
477   class NoticeMessage < UserMessage
478     def initialize(bot, server, source, target, message, opts={})
479       @msg_wants_id = opts[:handle_id]
480       super(bot, server, source, target, message)
481     end
482   end
483
484   # class to manage IRC KICKs
485   # +address?+ can be used as a shortcut to see if the bot was kicked,
486   # basically, +target+ was kicked from +channel+ by +source+ with +message+
487   class KickMessage < BasicUserMessage
488     # channel user was kicked from
489     attr_reader :channel
490
491     def inspect
492       fields = ' channel=' << channel.to_s
493       super(fields)
494     end
495
496     def initialize(bot, server, source, target, channel, message="")
497       super(bot, server, source, target, message)
498       @channel = channel
499     end
500   end
501
502   # class to manage IRC INVITEs
503   # +address?+ can be used as a shortcut to see if the bot was invited,
504   # which should be true except for server bugs
505   class InviteMessage < BasicUserMessage
506     # channel user was invited to
507     attr_reader :channel
508
509     def inspect
510       fields = ' channel=' << channel.to_s
511       super(fields)
512     end
513
514     def initialize(bot, server, source, target, channel, message="")
515       super(bot, server, source, target, message)
516       @channel = channel
517     end
518   end
519
520   # class to pass IRC Nick changes in. @message contains the old nickame,
521   # @sourcenick contains the new one.
522   class NickMessage < BasicUserMessage
523     attr_accessor :is_on
524     def initialize(bot, server, source, oldnick, newnick)
525       super(bot, server, source, oldnick, newnick)
526       @is_on = []
527     end
528
529     def oldnick
530       return @target
531     end
532
533     def newnick
534       return @message
535     end
536
537     def inspect
538       fields = ' old=' << oldnick
539       fields << ' new=' << newnick
540       super(fields)
541     end
542   end
543
544   # class to manage mode changes
545   class ModeChangeMessage < BasicUserMessage
546     attr_accessor :modes
547     def initialize(bot, server, source, target, message="")
548       super(bot, server, source, target, message)
549       @address = (source == @bot.myself)
550       @modes = []
551     end
552
553     def inspect
554       fields = ' modes=' << modes.inspect
555       super(fields)
556     end
557   end
558
559   # class to manage NAME replies
560   class NamesMessage < BasicUserMessage
561     attr_accessor :users
562     def initialize(bot, server, source, target, message="")
563       super(bot, server, source, target, message)
564       @users = []
565     end
566
567     def inspect
568       fields = ' users=' << users.inspect
569       super(fields)
570     end
571   end
572
573   class QuitMessage < BasicUserMessage
574     attr_accessor :was_on
575     def initialize(bot, server, source, target, message="")
576       super(bot, server, source, target, message)
577       @was_on = []
578     end
579   end
580
581   class TopicMessage < BasicUserMessage
582     # channel topic
583     attr_reader :topic
584     # topic set at (unixtime)
585     attr_reader :timestamp
586     # topic set on channel
587     attr_reader :channel
588
589     # :info if topic info, :set if topic set
590     attr_accessor :info_or_set
591     def initialize(bot, server, source, channel, topic=ChannelTopic.new)
592       super(bot, server, source, channel, topic.text)
593       @topic = topic
594       @timestamp = topic.set_on
595       @channel = channel
596       @info_or_set = nil
597     end
598
599     def inspect
600       fields = ' topic=' << topic
601       fields << ' (set on ' << timestamp << ')'
602       super(fields)
603     end
604   end
605
606   # class to manage channel joins
607   class JoinMessage < BasicUserMessage
608     # channel joined
609     attr_reader :channel
610
611     def inspect
612       fields = ' channel=' << channel.to_s
613       super(fields)
614     end
615
616     def initialize(bot, server, source, channel, message="")
617       super(bot, server, source, channel, message)
618       @channel = channel
619       # in this case sourcenick is the nick that could be the bot
620       @address = (source == @bot.myself)
621     end
622   end
623
624   # class to manage channel parts
625   # same as a join, but can have a message too
626   class PartMessage < JoinMessage
627   end
628
629   class UnknownMessage < BasicUserMessage
630   end
631 end