'Using .find() function, output says 'argument should be integer or bytes-like object, not 'str' '

I'm currently working on a script to resolve the first challenge of the root-me.org programming category. Being unable to find out a solution by myself, i found a solution on the internet from a YouTube tutorial
In order to still learn something from this exercise, i decided to analyze entirely the script, written in Python (2.x i presume, since the print statements are written like "print x" and not "print(x)"), commenting each line so i don't miss a single element that i might don't be aware about. Unfortunately, I'm stuck at a .find() function. Here is a fragment of the code:

text = irc.recv(2048)
  if len(text) > 0:
   print(text)
  else:
   continue

  if text.find("PING") != -1:

The "irc" object is a socket-type object created with the same-name module. And when the script is executed, an error is raised from the last line stating that

"TypeError: argument should be integer or bytes-like object, not 'str'"

I precise that when i copy/paste the full script on pycharm and run it, it works perfectly (the code is accessible here)
Where did it went wrong? Thanks for your help and sorry if i wasn't precise enough, I don't seek help often



Solution 1:[1]

output of socket.recv() is bytes and you can't find a substring from it first, use decode to string with encoding="utf_8"

if text.decode(encoding="utf_8").find("PING") != -1:

Solution 2:[2]

As amir Reza Seddighin wrote, socket.recv() returns a bytes object (nowadays), and its .find() method doesn't take a string argument. Alternatively to convert the bytes to a string by means of .decode(), you can change the string literal argument to bytes by simply prepending b, i. e. text.find(b"PING").

Solution 3:[3]

The easier way to do this.

def listen(self):
    while self.is_connected:
        recv = self.irc_sock.recv(4096)
        
        if str(recv).find("PING") != -1:
            _ping = recv.split()[1]
            self.irc_sock.send(bytes(f'PONG {_ping}\r\n', 'UTF-8'))

An another way:

if recv.find(b'PING') != -1:
     sck.send("PONG ".encode() + recv.split()[1] + "\r\n".encode())

Or better use this. I used this in below all time.

if 'PING' in str(data):
    _ping = data.split()[1]
    self.irc_sock.send(bytes(f'PONG {_ping}\r\n', 'UTF-8'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 amir Reza Seddighin
Solution 2 Armali
Solution 3