Python IRC Client
When I run the script:
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')
s开发者_StackOverflowck.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
I get this is the error:
get = message.split(' ')[1]
IndexError: list index out of range
How can I fix it?
This means that message
has no spaces in it, so when it's split by a space, you get a list containing a single element - you are trying to access the second element of this list. You should insert a check for this case.
EDIT: In reply to your comment: how you add the check depends on the logic of your program. The simplest solution would be something like:
if ' ' in msg:
get = message.split(' ')[1]
else:
get = message
Try
get = message.split(" ",1)[-1]
Example
>>> "abcd".split(" ",1)[-1]
'abcd'
>>> "abcd efgh".split(" ",1)[-1]
'efgh'
精彩评论