62

I'm moving my Twitch bot from Python 2.7 to Python 3.5. I keep getting the error: a bytes like object is required not 'str' on the 2nd line of the code below.

twitchdata = irc.recv(1204)
    data = twitchdata.split(":")[1]
    twitchuser = data.split("!")[0]
    twitchmsg = twitchdata.split(":")[2]
    chat = str(twitchuser) +": "+ str(twitchmsg)
    print(chat) #prints chat to console
Jean-Francois T.
  • 11,549
  • 7
  • 68
  • 107
spencermehta
  • 639
  • 1
  • 5
  • 10
  • See also: Ned Batcheler's [Pragmatic Unicode, or, How Do I Stop the Pain?](http://bit.ly/unipain) –  Apr 15 '15 at 07:07

1 Answers1

99

try

data = twitchdata.decode().split(":")[1]

instead of

data = twitchdata.split(":")[1]
valentin
  • 3,498
  • 15
  • 23
  • I think you mean `decode`. And of course the same would be needed for the other `split` calls, so the decoding should happen once, in the first line. Plus the question if ASCII is even the right encoding... –  Apr 15 '15 at 07:05
  • 1
    I think is only decode() and I think is related to https://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit – valentin Apr 15 '15 at 07:09
  • Thank you. I used data = twitchdata.decode("ascii").split(":")[1] and that worked – spencermehta Apr 15 '15 at 07:09
  • 2
    I thing is better without ascii, it will free your code from issues with unicode – valentin Apr 15 '15 at 07:12
  • I ve solved the same issue with `bytes(my_str, encoding='UTF-8')` and removing everything that was left for PY2 compatibility. – ivan866 Aug 21 '20 at 10:00