I’m currently developing my first significant project using Python, which is an IRC bot designed for Twitch chats. While it operates, it seems to be quite slow in processing incoming messages, and I’m having trouble understanding what’s causing the delay.
import re
import socket
import threading
import time
SERVER = "irc.twitch.tv"
PORT_NUM = 6667
BOT_NAME = ""
AUTH_TOKEN = ""
CHANNEL = ""
MSG_RATE = (15/25)
MSG_PATTERN = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
def send_message(connection, text):
connection.send("PRIVMSG #{} :{}".format(CHANNEL, text))
# Main chat connection
main_conn = socket.socket()
main_conn.connect((SERVER, PORT_NUM))
main_conn.send("PASS {}\r\n".format(AUTH_TOKEN).encode("utf-8"))
main_conn.send("NICK {}\r\n".format(BOT_NAME).encode("utf-8"))
main_conn.send("JOIN {}\r\n".format(CHANNEL).encode("utf-8"))
# Whisper connection
whisper_conn = socket.socket()
whisper_conn.connect((SERVER, PORT_NUM))
whisper_conn.send("PASS {}\r\n".format(AUTH_TOKEN).encode("utf-8"))
whisper_conn.send("NICK {}\r\n".format(BOT_NAME).encode("utf-8"))
whisper_conn.send("CAP REQ :twitch.tv/tags twitch.tv/commands {}\r\n".format(CHANNEL).encode("utf-8"))
while True:
chat_data = main_conn.recv(1024).decode("utf-8")
whisper_data = whisper_conn.recv(1024).decode("utf-8")
if whisper_data == "PING :tmi.twitch.tv\r\n":
whisper_conn.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
else:
whisper_user = re.search(r"\w+", whisper_data).group(0)
whisper_text = MSG_PATTERN.sub("", whisper_data)
print(whisper_user + ": " + whisper_text)
if chat_data == "PING :tmi.twitch.tv\r\n":
main_conn.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
else:
chat_user = re.search(r"\w+", chat_data).group(0)
chat_text = MSG_PATTERN.sub("", chat_data)
print(chat_user + ": " + chat_text)
time.sleep(1 / MSG_RATE)
To manage both regular chat messages and whispers, I’ve implemented two socket connections based on the recommendations I’ve seen. Since this is my first time working on such a complex Python program, I may be overlooking some simple solutions. Could you share any insights on what may be affecting the response speed?