James Kirk James Kirk - 18 hours ago 2
Python Question

TypeError: Can't convert 'bytes' object to str implicitly despite adding .encode() to string

I am trying to write some code that connects to an IRC channel and allows the user to chat through the channel. I have been getting an error in my script that connects to the server:

TypeError: Can't convert 'bytes' object to str implicitly


The error is apparently in line 18, which is the code that sends the nickname to the server:

irc.send("USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n")


Source Code:

import sys
import socket

server = "chat.freenode.net"
channel = "#randomchannel123456789"
port = 7070

print("IRC Connecter")
print("-----------------------------")
nick = input("Input Nickname: ")

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("connecting to " + server)

irc.connect((server, port))
print("connected")

irc.send("USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n")
print("sent user")

irc.send ("NICK " + nick + "\n")
print("sent nick")

while 1:
text = irc.recv(2040)
print(text)

if text.find("PING") != -1:
irc.send("PONG " + text.split() [1] + "\r\n")


I'm pretty new to socket programming, so any help would be much appreciated.

Answer

The problem is that in that line:

"USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n"

The "USER ", " " and " : Test\n" are str but nick.encode is a bytes object. And the exception is telling you, that you can't add bytes and strs:

>>> b'a' + 'a'
TypeError: can't concat bytes to str

>>> 'a' + b'a'
TypeError: Can't convert 'bytes' object to str implicitly

You could convert the string literals to bytes, for example using the bytes literal (b""):

b"USER " + nick.encode() + b" " + nick.encode() + b" " + nick.encode() + b" : Test\n"