Creating a Python-based Chatbot for Twitch

Hey everyone! I’m trying to build a Twitch chatbot using Python 3. I’ve tried updating some older Python 2 code, but I’m stuck with an error I can’t resolve.

The error message reads:

TwitchBot\utils.py, line 17, in chat
    sock.send("PRIVMSG #{} :{}\r\n".format(cfg.CHAN, msg))
TypeError: a bytes-like object is required, not 'str'

I have two files in my project: utils.py and bot.py. Below is a simplified version of my code:

# utils.py
def chat(sock, msg):
    sock.send(f"PRIVMSG #{cfg.CHAN} :{msg}\r\n")

# bot.py
import socket

s = socket.socket()
s.connect((HOST, PORT))
s.send(f"PASS {PASS}\r\n".encode("utf-8"))
s.send(f"NICK {NICK}\r\n".encode("utf-8"))
s.send(f"JOIN {CHAN}\r\n".encode("utf-8"))

utils.chat(s, "Bot is online!")

Any advice on resolving this issue for Python 3? Thanks!

I ran into a similar issue when updating my Twitch bot to Python 3. The problem is that in Python 3, socket operations expect bytes instead of strings. To fix this, you need to encode your message before sending it.

Try modifying your utils.py file like this:

def chat(sock, msg):
    sock.send(f"PRIVMSG #{cfg.CHAN} :{msg}\r\n".encode('utf-8'))

This should resolve the TypeError you’re encountering. Also, make sure all your socket.send() calls in bot.py are encoded as well.

One more tip: consider using a library like twitchio or python-twitch-client. They handle a lot of the low-level socket stuff for you, making bot development much easier. Good luck with your project!