Class: Irc::Client

Inherits:
Object show all
Defined in:
lib/rbot/rfc2812.rb

Overview

Implements RFC 2812 and prior IRC RFCs.

Clients should register Proc{}s to handle the various server events, and the Client class will handle dispatch.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeClient

Create a new Client instance



961
962
963
964
965
966
967
968
969
970
971
972
973
# File 'lib/rbot/rfc2812.rb', line 961

def initialize
  @server = Server.new         # The Server
  @user = @server.user("*!*@*")     # The User representing the client on this Server

  @handlers = Hash.new

  # This is used by some messages to build lists of users that
  # will be delegated when the ENDOF... message is received
  @tmpusers = []

  # Same as above, just for bans
  @tmpbans = []
end

Instance Attribute Details

#serverObject (readonly)

the Server we’re connected to



956
957
958
# File 'lib/rbot/rfc2812.rb', line 956

def server
  @server
end

#userObject (readonly)

the User representing us on that server



958
959
960
# File 'lib/rbot/rfc2812.rb', line 958

def user
  @user
end

Instance Method Details

#[]=(key, value) ⇒ Object

key

server event to handle

value

proc object called when event occurs

set a handler for a server event

server events currently supported:

TODO handle errors ERR_CHANOPRIVSNEEDED, ERR_CANNOTSENDTOCHAN

welcome

server welcome message on connect

yourhost

your host details (on connection)

created

when the server was started

isupport

information about what this server supports

ping

server pings you (default handler returns a pong)

nicktaken

you tried to change nick to one that’s in use

badnick

you tried to change nick to one that’s invalid

topic

someone changed the topic of a channel

topicinfo

on joining a channel or asking for the topic, tells you who set it and when

names

server sends list of channel members when you join

motd

server message of the day

privmsg

privmsg, the core of IRC, a message to you from someone

public

optionally instead of getting privmsg you can hook to only the public ones…

msg

or only the private ones, or both

kick

someone got kicked from a channel

part

someone left a channel

quit

someone quit IRC

join

someone joined a channel

changetopic

the topic of a channel changed

invite

you are invited to a channel

nick

someone changed their nick

mode

a mode change

notice

someone sends you a notice

unknown

any other message not handled by the above



1015
1016
1017
# File 'lib/rbot/rfc2812.rb', line 1015

def []=(key, value)
  @handlers[key] = value
end

#deletehandler(key) ⇒ Object

key

event name

remove a handler for a server event



1021
1022
1023
# File 'lib/rbot/rfc2812.rb', line 1021

def deletehandler(key)
  @handlers.delete(key)
end

#process(serverstring) ⇒ Object

takes a server string, checks for PING, PRIVMSG, NOTIFY, etc, and parses numeric server replies, calling the appropriate handler for each, and sending it a hash containing the data from the server



1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
# File 'lib/rbot/rfc2812.rb', line 1028

def process(serverstring)
  data = Hash.new
  data[:serverstring] = serverstring

  unless serverstring.chomp =~ /^(:(\S+)\s)?(\S+)(\s(.*))?$/
    raise "Unparseable Server Message!!!: #{serverstring.inspect}"
  end

  prefix, command, params = $2, $3, $5

  if prefix != nil
    # Most servers will send a full nick!user@host prefix for
    # messages from users. Therefore, when the prefix doesn't match this
    # syntax it's usually the server hostname.
    #
    # This is not always true, though, since some servers do not send a
    # full hostmask for user messages.
    #
    if prefix =~ /^#{Regexp::Irc::BANG_AT}$/
      data[:source] = @server.user(prefix)
    else
      if @server.hostname
        if @server.hostname != prefix
          # TODO do we want to be able to differentiate messages that are passed on to us from /other/ servers?
          debug "Origin #{prefix} for message\n\t#{serverstring.inspect}\nis neither a user hostmask nor the server hostname\nI'll pretend that it's from the server anyway"
          data[:source] = @server
        else
          data[:source] = @server
        end
      else
        @server.instance_variable_set(:@hostname, prefix)
        data[:source] = @server
      end
    end
  end

  # split parameters in an array
  argv = []
  params.scan(/(?!:)(\S+)|:(.*)/) { argv << ($1 || $2) } if params

  if command =~ /^(\d+)$/ # Numeric replies
	data[:target] = argv[0]
    # A numeric reply /should/ be directed at the client, except when we're connecting with a used nick, in which case
    # it's directed at '*'
    not_us = !([@user.nick, '*'].include?(data[:target]))
    if not_us
      warning "Server reply #{serverstring.inspect} directed at #{data[:target]} instead of client (#{@user.nick})"
    end

    num=command.to_i
    case num
    when RPL_WELCOME
      data[:message] = argv[1]
      # "Welcome to the Internet Relay Network
      # <nick>!<user>@<host>"
      if not_us
        warning "Server thinks client (#{@user.inspect}) has a different nick"
        @user.nick = data[:target]
      end
      if data[:message] =~ /([^@!\s]+)(?:!([^@!\s]+?))?@(\S+)/
        nick = $1
        user = $2
        host = $3
        warning "Welcome message nick mismatch (#{nick} vs #{data[:target]})" if nick != data[:target]
        @user.user = user if user
        @user.host = host if host
      end
      handle(:welcome, data)
    when RPL_YOURHOST
      # "Your host is <servername>, running version <ver>"
      data[:message] = argv[1]
      handle(:yourhost, data)
    when RPL_CREATED
      # "This server was created <date>"
      data[:message] = argv[1]
      handle(:created, data)
    when RPL_MYINFO
      # "<servername> <version> <available user modes>
      # <available channel modes>"
      @server.parse_my_info(params.split(' ', 2).last)
      data[:servername] = @server.hostname
      data[:version] = @server.version
      data[:usermodes] = @server.usermodes
      data[:chanmodes] = @server.chanmodes
      handle(:myinfo, data)
    when RPL_ISUPPORT
      # "PREFIX=(ov)@+ CHANTYPES=#& :are supported by this server"
      # "MODES=4 CHANLIMIT=#:20 NICKLEN=16 USERLEN=10 HOSTLEN=63
      # TOPICLEN=450 KICKLEN=450 CHANNELLEN=30 KEYLEN=23 CHANTYPES=#
      # PREFIX=(ov)@+ CASEMAPPING=ascii CAPAB IRCD=dancer :are available
      # on this server"
      #
      @server.parse_isupport(argv[1..-2].join(' '))
      handle(:isupport, data)
    when ERR_NICKNAMEINUSE
      # "* <nick> :Nickname is already in use"
      data[:nick] = argv[1]
      data[:message] = argv[2]
      handle(:nicktaken, data)
    when ERR_ERRONEUSNICKNAME
      # "* <nick> :Erroneous nickname"
      data[:nick] = argv[1]
      data[:message] = argv[2]
      handle(:badnick, data)
    when RPL_TOPIC
      data[:channel] = @server.channel(argv[1])
      data[:topic] = argv[2]
      data[:channel].topic.text = data[:topic]

      handle(:topic, data)
    when RPL_TOPIC_INFO
      data[:nick] = @server.user(argv[0])
      data[:channel] = @server.channel(argv[1])

      # This must not be an IRC::User because it might not be an actual User,
      # and we risk overwriting valid User data
      data[:source] = argv[2].to_irc_netmask(:server => @server)

      data[:time] = Time.at(argv[3].to_i)

      data[:channel].topic.set_by = data[:source]
      data[:channel].topic.set_on = data[:time]

      handle(:topicinfo, data)
    when RPL_NAMREPLY
      # "( "=" / "*" / "@" ) <channel>
      # :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> )
      # - "@" is used for secret channels, "*" for private
      # channels, and "=" for others (public channels).
      data[:channeltype] = argv[1]
      data[:channel] = chan = @server.channel(argv[2])

      users = []
      argv[3].scan(/\S+/).each { |u|
        # FIXME beware of servers that allow multiple prefixes
        if(u =~ /^([#{@server.supports[:prefix][:prefixes].join}])?(.*)$/)
          umode = $1
          user = $2
          users << [user, umode]
        end
      }

      users.each { |ar|
        u = @server.user(ar[0])
        chan.add_user(u, :silent => true)
        debug "Adding user #{u}"
        if ar[1]
          ms = @server.mode_for_prefix(ar[1].to_sym)
          debug "\twith mode #{ar[1]} (#{ms})"
          chan.mode[ms].set(u)
        end
      }
      @tmpusers += users
    when RPL_ENDOFNAMES
      data[:channel] = @server.channel(argv[1])
      data[:users] = @tmpusers
      handle(:names, data)
      @tmpusers = Array.new
    when RPL_BANLIST
      data[:channel] = @server.channel(argv[1])
      data[:mask] = argv[2]
      data[:by] = argv[3]
      data[:at] = argv[4]
      @tmpbans << data
    when RPL_ENDOFBANLIST
      data[:channel] = @server.channel(argv[1])
      data[:bans] = @tmpbans
      handle(:banlist, data)
      @tmpbans = Array.new
    when RPL_LUSERCLIENT
      # ":There are <integer> users and <integer>
      # services on <integer> servers"
      data[:message] = argv[1]
      handle(:luserclient, data)
    when RPL_LUSEROP
      # "<integer> :operator(s) online"
      data[:ops] = argv[1].to_i
      handle(:luserop, data)
    when RPL_LUSERUNKNOWN
      # "<integer> :unknown connection(s)"
      data[:unknown] = argv[1].to_i
      handle(:luserunknown, data)
    when RPL_LUSERCHANNELS
      # "<integer> :channels formed"
      data[:channels] = argv[1].to_i
      handle(:luserchannels, data)
    when RPL_LUSERME
      # ":I have <integer> clients and <integer> servers"
      data[:message] = argv[1]
      handle(:luserme, data)
    when ERR_NOMOTD
      # ":MOTD File is missing"
      data[:message] = argv[1]
      handle(:motd_missing, data)
    when RPL_LOCALUSERS
      # ":Current local  users: 3  Max: 4"
      data[:message] = argv[1]
      handle(:localusers, data)
    when RPL_GLOBALUSERS
      # ":Current global users: 3  Max: 4"
      data[:message] = argv[1]
      handle(:globalusers, data)
    when RPL_STATSCONN
      # ":Highest connection count: 4 (4 clients) (251 since server was
      # (re)started)"
      data[:message] = argv[1]
      handle(:statsconn, data)
    when RPL_MOTDSTART
      # "<nick> :- <server> Message of the Day -"
      if argv[1] =~ /^-\s+(\S+)\s/
        server = $1
      else
        warning "Server doesn't have an RFC compliant MOTD start."
      end
      @motd = ""
    when RPL_MOTD
      if(argv[1] =~ /^-\s+(.*)$/)
        @motd << $1
        @motd << "\n"
      end
    when RPL_ENDOFMOTD
      data[:motd] = @motd
      handle(:motd, data)
    when RPL_DATASTR
      data[:text] = argv[1]
      handle(:datastr, data)
    when RPL_AWAY
      data[:nick] = user = @server.user(argv[1])
      data[:message] = argv[-1]
      user.away = data[:message]
      handle(:away, data)
	when RPL_WHOREPLY
      data[:channel] = channel = @server.channel(argv[1])
      data[:user] = argv[2]
      data[:host] = argv[3]
      data[:userserver] = argv[4]
      data[:nick] = user = @server.user(argv[5])
      if argv[6] =~ /^(H|G)(\*)?(.*)?$/
        data[:away] = ($1 == 'G')
        data[:ircop] = $2
        data[:modes] = $3.scan(/./).map { |mode|
          m = @server.supports[:prefix][:prefixes].index(mode.to_sym)
          @server.supports[:prefix][:modes][m]
        } rescue []
      else
        warning "Strange WHO reply: #{serverstring.inspect}"
      end
      data[:hopcount], data[:real_name] = argv[7].split(" ", 2)

      user.user = data[:user]
      user.host = data[:host]
      user.away = data[:away] # FIXME doesn't provide the actual message
      # TODO ircop status
      # TODO userserver
      # TODO hopcount
      user.real_name = data[:real_name]

      channel.add_user(user, :silent=>true)
      data[:modes].map { |mode|
        channel.mode[mode].set(user)
      }

      handle(:who, data)
    when RPL_ENDOFWHO
      handle(:eowho, data)
    when RPL_WHOISUSER
      @whois ||= Hash.new
      @whois[:nick] = argv[1]
      @whois[:user] = argv[2]
      @whois[:host] = argv[3]
      @whois[:real_name] = argv[-1]

      user = @server.user(@whois[:nick])
      user.user = @whois[:user]
      user.host = @whois[:host]
      user.real_name = @whois[:real_name]
    when RPL_WHOISSERVER
      @whois ||= Hash.new
      @whois[:nick] = argv[1]
      @whois[:server] = argv[2]
      @whois[:server_info] = argv[-1]
      # TODO update user info
    when RPL_WHOISOPERATOR
      @whois ||= Hash.new
      @whois[:nick] = argv[1]
      @whois[:operator] = argv[-1]
      # TODO update user info
    when RPL_WHOISIDLE
      @whois ||= Hash.new
      @whois[:nick] = argv[1]
      user = @server.user(@whois[:nick])
      @whois[:idle] = argv[2].to_i
      user.idle_since = Time.now - @whois[:idle]
      if argv[-1] == 'seconds idle, signon time'
        @whois[:signon] = Time.at(argv[3].to_i)
        user.signon = @whois[:signon]
      end
    when RPL_ENDOFWHOIS
      @whois ||= Hash.new
      @whois[:nick] = argv[1]
      data[:whois] = @whois.dup
      @whois.clear
      handle(:whois, data)
    when RPL_WHOISCHANNELS
      @whois ||= Hash.new
      @whois[:nick] = argv[1]
      @whois[:channels] ||= []
      user = @server.user(@whois[:nick])
      argv[-1].split.each do |prechan|
        pfx = prechan.scan(/[#{@server.supports[:prefix][:prefixes].join}]/)
        modes = pfx.map { |p| @server.mode_for_prefix p }
        chan = prechan[pfx.length..prechan.length]

        channel = @server.channel(chan)
        channel.add_user(user, :silent => true)
        modes.map { |mode| channel.mode[mode].set(user) }

        @whois[:channels] << [chan, modes]
      end
    when RPL_CHANNELMODEIS
      parse_mode(serverstring, argv[1..-1], data)
      handle(:mode, data)
    when RPL_CREATIONTIME
      data[:channel] = @server.channel(argv[1])
      data[:time] = Time.at(argv[2].to_i)
      data[:channel].creation_time=data[:time]
      handle(:creationtime, data)
    when RPL_CHANNEL_URL
      data[:channel] = @server.channel(argv[1])
      data[:url] = argv[2]
      data[:channel].url=data[:url].dup
      handle(:channel_url, data)
    when ERR_NOSUCHNICK
      data[:target] = argv[1]
      data[:message] = argv[2]
      handle(:nosuchtarget, data)
      if user = @server.get_user(data[:target])
        @server.delete_user(user)
      end
    when ERR_NOSUCHCHANNEL
      data[:target] = argv[1]
      data[:message] = argv[2]
      handle(:nosuchtarget, data)
      if channel = @server.get_channel(data[:target])
        @server.delete_channel(channel)
      end
    else
      warning "Unknown message #{serverstring.inspect}"
      handle(:unknown, data)
    end
	return # We've processed the numeric reply
  end

  # Otherwise, the command should be a single word
  case command.to_sym
  when :PING
    data[:pingid] = argv[0]
    handle(:ping, data)
  when :PONG
    data[:pingid] = argv[0]
    handle(:pong, data)
  when :PRIVMSG
    # you can either bind to 'PRIVMSG', to get every one and
    # parse it yourself, or you can bind to 'MSG', 'PUBLIC',
    # etc and get it all nicely split up for you.

    begin
      data[:target] = @server.user_or_channel(argv[0])
    rescue
      # The previous may fail e.g. when the target is a server or something
      # like that (e.g. $<mask>). In any of these cases, we just use the
      # String as a target
      # FIXME we probably want to explicitly check for the #<mask> $<mask>
      data[:target] = argv[0]
    end
    data[:message] = argv[1]
    handle(:privmsg, data)

    # Now we split it
    if data[:target].kind_of?(Channel)
      handle(:public, data)
    else
      handle(:msg, data)
    end
  when :NOTICE
    begin
      data[:target] = @server.user_or_channel(argv[0])
    rescue
      # The previous may fail e.g. when the target is a server or something
      # like that (e.g. $<mask>). In any of these cases, we just use the
      # String as a target
      # FIXME we probably want to explicitly check for the #<mask> $<mask>
      data[:target] = argv[0]
    end
    data[:message] = argv[1]
    case data[:source]
    when User
      handle(:notice, data)
    else
      # "server notice" (not from user, noone to reply to)
      handle(:snotice, data)
    end
  when :KICK
    data[:channel] = @server.channel(argv[0])
    data[:target] = @server.user(argv[1])
    data[:message] = argv[2]

    @server.delete_user_from_channel(data[:target], data[:channel])
    if data[:target] == @user
      @server.delete_channel(data[:channel])
    end

    handle(:kick, data)
  when :PART
    data[:channel] = @server.channel(argv[0])
    data[:message] = argv[1]

    @server.delete_user_from_channel(data[:source], data[:channel])
    if data[:source] == @user
      @server.delete_channel(data[:channel])
    end

    handle(:part, data)
  when :QUIT
    data[:message] = argv[0]
    data[:was_on] = @server.channels.inject(ChannelList.new) { |list, ch|
      list << ch if ch.has_user?(data[:source])
      list
    }

    @server.delete_user(data[:source])

    handle(:quit, data)
  when :JOIN
    data[:channel] = @server.channel(argv[0])
    data[:channel].add_user(data[:source])

    handle(:join, data)
  when :TOPIC
    data[:channel] = @server.channel(argv[0])
    data[:topic] = Channel::Topic.new(argv[1], data[:source], Time.new)
    data[:channel].topic.replace(data[:topic])

    handle(:changetopic, data)
  when :INVITE
    data[:target] = @server.user(argv[0])
    data[:channel] = @server.channel(argv[1])

    handle(:invite, data)
  when :NICK
    data[:is_on] = @server.channels.inject(ChannelList.new) { |list, ch|
      list << ch if ch.has_user?(data[:source])
      list
    }

    data[:newnick] = argv[0]
    data[:oldnick] = data[:source].nick.dup
    data[:source].nick = data[:newnick]

    debug "#{data[:oldnick]} (now #{data[:newnick]}) was on #{data[:is_on].join(', ')}"

    handle(:nick, data)
  when :MODE
    parse_mode(serverstring, argv, data)
    handle(:mode, data)
  when :ERROR
    data[:message] = argv[1]
    handle(:error, data)
  else
    warning "Unknown message #{serverstring.inspect}"
    handle(:unknown, data)
  end
end

#resetObject

Clear the server and reset the user



976
977
978
979
# File 'lib/rbot/rfc2812.rb', line 976

def reset
  @server.clear
  @user = @server.user("*!*@*")
end