2010-02-06 96 views
0

當我運行該腳本:Python的IRC客戶端

import socket 
from time import strftime 

time = strftime("%H:%M:%S") 

irc = 'irc.tormented-box.net' 
port = 6667 
channel = '#tormented' 
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
sck.connect((irc, port)) 
print sck.recv(4096) 
sck.send('NICK supaBOT\r\n') 
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n') 
sck.send('JOIN ' + channel + '\r\n') 
sck.send('PRIVMSG #tormented :supaBOT\r\n') 
while True: 
    data = sck.recv(4096) 
    if data.find('PING') != -1: 
     sck.send('PONG ' + data.split() [1] + '\r\n') 
    elif data.find ('PRIVMSG') != -1: 
     nick = data.split ('!') [ 0 ].replace (':', '') 
     message = ':'.join (data.split (':') [ 2: ]) 
     destination = ''.join (data.split (':') [ :2 ]).split (' ') [ -2 ] 
     if destination == 'supaBOT': 
      destination = 'PRIVATE' 
     print '(', destination, ')', nick + ':', message 
     get = message.split(' ') [1] 
     if get == 'hi': 
      try: 
       args = message.split(' ') [2:] 
       sck.send('PRIVMSG ' + destination + ' :' + nick + ': ' + 'hello' + '\r\n') 
      except: 
       pass 

我得到這樣的錯誤:

get = message.split(' ')[1] 

IndexError: list index out of range 

我怎樣才能解決呢?

+1

這AARGH錯字讓我想起:http://pythong.org/(警告:你可以不看這個)。 – 2010-02-06 10:12:06

回答

3

這意味着message裏沒有空格,所以當它被一個空格分開時,會得到一個包含單個元素的列表 - 您試圖訪問此列表的第二個元素。你應該爲這種情況插入一張支票。

編輯:回覆您的評論:您如何添加支票取決於您的程序的邏輯。最簡單的辦法是這樣的:

if ' ' in msg: 
    get = message.split(' ')[1] 
else: 
    get = message 
+0

如何插入支票? – sourD 2010-02-06 10:08:45

0

嘗試

get = message.split(" ",1)[-1] 

>>> "abcd".split(" ",1)[-1] 
'abcd' 
>>> "abcd efgh".split(" ",1)[-1] 
'efgh'