-1

I'm creating a twitch chat bot to read the chat on my stream. But when I try to .split() the incoming string into separate strings to isolate the username and message, it displays an extra ' and ["'"]. when I try to print the strings separately by index I get an index error.

Following is the code which connects the the twitch chat fine, and the result when I type "test" into the chat.

from settings import *
import socket
import threading

class twitch:
    def __init__(self, host, port, nick, pwd, channel):
        self.s = socket.socket()
        self.s.connect((host, port))
        self.s.send(bytes("PASS " + pwd + "\r\n", "UTF-8"))
        self.s.send(bytes("NICK " + nick + "\r\n", "UTF-8"))
        self.s.send(bytes("JOIN #" + channel + " \r\n", "UTF-8"))
        self.s.send(bytes("PRIVMSG #" + channel + " :" + "Connected " + "\r\n", "UTF-8"))
        self.alive = True

        readerthread = threading.Thread(target=self.read_chat)
        readerthread.start()

    def read_chat(self):
        while self.alive:
            for line in str(self.s.recv(1024)).split('\\r\\n'):
                if "PING :tmi.twitch.tv" in line:
                    print(time.strftime("%H:%M:%S"), "PONG :tmi.twitch.tv")
                    s.send(bytes("PONG :tmi.twitch.tv\r\n", "UTF-8"))
                else:
                    print(line)
                    parts = line.split(":")
                    print(parts)

def main():
    tc = twitch(HOST, PORT, NICK, PASS, CHANNEL)

Printing the string (line) to the console produces: b':username!username@username.tmi.twitch.tv PRIVMSG #username :test

However when I split the string and print the list of strings (parts) it produces this: ["b'", 'username!username@username.tmi.twitch.tv PRIVMSG #username ', 'test'] ' ["'"]

1 Answers1

0

You are reading bytes. Hence the b'...'.
What does the 'b' character do in front of a string literal?


Convert it to a string and then handle it.
Convert bytes to a string?


code from the link.

>>> b"abcde"
b'abcde'

# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8") 
'abcde'
thatNLPguy
  • 101
  • 8
  • Thank you very much for the response. I tried adding x = line.decode("UTF-8") and i get: AttributeError: 'str' object has no attribute 'decode' – PileOfMeatballs Mar 26 '19 at 22:42
  • `for line in str(self.s.recv(1024)).split('\\r\\n'):` you appear to be casting to string. Remove the cast. `for line in (self.s.recv(1024)).split('\\r\\n'):` Then decode bytes – thatNLPguy Mar 27 '19 at 01:24