Adam Grieger
Adam Grieger

Reputation: 21

Twitch IRC chat bot successfully connects but does not detect commands

I started making a simple Twitch chat bot using Python. It connects fine, and it can also see the messages that other people are sending in the chat. My problem, however, is that I cannot seem to detect commands when they are used. I can grab the username and message of chat entries and even print them to the console, but passing them to the chat() function doesn't do anything.

Another quirk is that the bot will sometimes randomly send chat messages containing the PONG responses.

I think I am missing something obvious, perhaps with how I am checking for commands in chat, or my whole chat() function.

import re
from time import sleep
import socket


HOST = "irc.twitch.tv"
PORT = 6667
NICK = "bot_name"
PASS = "oauth:..."
CHAN = "#channel"
RATE = (20 / 30)
CHAT_MSG = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")


def main_loop():
    try:
        s = socket.socket()
        s.connect((HOST, PORT))
        s.send("PASS {}\r\n".format(PASS).encode("utf-8"))
        s.send("NICK {}\r\n".format(NICK).encode("utf-8"))
        s.send("JOIN {}\r\n".format(CHAN).encode("utf-8"))
        connected = True
    except Exception as e:
        print(str(e))
        connected = False

    while connected:
        response = s.recv(1024).decode("utf-8")
        if response == "PING :tmi.twitch.tv\r\n":
            s.send("PONG :tmi.twitch.tv\r\n".encode())
            print("PONG")
        else:
            username = re.search(r"\w+", response).group(0)
            message = CHAT_MSG.sub("", response)

            if message == "!test":
                chat(s, "Testing command received!")

            print(username + ": " + message)
        sleep(1)


def chat(sock, msg):
    sock.send("PRIVMSG {} :{}".format(CHAN, msg).encode())


if __name__ == "__main__":
    main_loop()

Upvotes: 1

Views: 2454

Answers (1)

Adam Grieger
Adam Grieger

Reputation: 21

I found out the solution, if anyone else has the same problem! The message that is passed through the chat() function must have \r\n added to the end of the string and the command to check for would be !test\r\n. I am sure this is just the way in which IRC works, but this addition now lets the bot respond to commands!

Upvotes: 1

Related Questions