Python TypeError with sockets

import socket, sys, string 

if len(sys.argv) !=4:
    print ("UsageL ./ninjabot.py <server> <port> <channel>")
    sys.exit(1)

irc = sys.argv[1]
port = int(sys.argv[2])
chan = sys.argv[3]
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send(b'NICK ninjabot\r\n')
sck.send(b'USER ninjabot ninjabot ninjabot :ninjabot Script\r\n')
sck.send('JOIN ' + " " + chan + '\r\n')
data = ''
while True:
    data = sck.recv(1024)
    if data.find('PING') != -1:
        sck.send('PONG ' + data.split() [1] + '\r\n')
        print (data)

print (data)

I get this error in sck.send('JOIN ' + " " + chan + '\r\n') but when i try this:

sck.send(b'JOIN ' + " " + chan + '\r\n')

I get TypeError: can't concat str to bytes

I know there's similar posts with this same issue, but none of those seem to help me.

1 answer

  • answered 2018-07-12 00:30 Addison Lynch

    This is due to the fact that b'JOIN' is of type bytes while " " as well as chan and "\r\n" are of type str.

    2 corrections:

    1. chan = sys.argv[3].encode()
    2. sck.send(b'JOIN ' + b" " + chan + b'\r\n')

    alternatively you could just:

    sck.send(b'JOIN %s\r\n' % chan.encode())

    this would be the best style. Similar corrections will be need to be made later in your snippet as well. socket.send is looking for a bytes string, so ensure that all strings which you pass it are either b"" or encoded otherwise using encode()