Help with Python Bot Disconnects After 10 Minutes

I read the other questions on Python bot disconnects and I can’t seem to find an answer to this question.

I’m writing a basic bot that reads the chat and monitors it for commands. It works as intended EXCEPT that it won’t stay connected for more than 10 minutes. I thought there might have been a problem with my response to server PINGs so I just set up a thread that PINGs the Twitch server every 3 minutes to keep the connection alive. It still disconnects.

import socket
import time
import threading

HOST = "irc.chat.twitch.tv"
PORT = 6667
NICK = "xxxxxx"
PASS = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
CHANNEL = "xxxxxxxxx"

def check_in():
    print("check_in started.") 
    while True:
        time.sleep(180)
        s.send(bytes("PING :tmi.twitch.tv\\r\\n", "UTF-8"))
        print("PING Sent.")

def send_message(msg):
    s.send(bytes("PRIVMSG #" + CHANNEL + " :" + msg + "\r\n", "UTF-8"))

print("Connecting to host.")
s = socket.socket()
s.connect((HOST, PORT))
s.send(bytes("PASS " + PASS + "\r\n", "UTF-8"))
s.send(bytes("NICK " + NICK + "\r\n", "UTF-8"))
s.send(bytes("JOIN #" + CHANNEL + " \r\n", "UTF-8"))
print("Connected to host")

send_message("Connected to chat.")

checkdelay = threading.Thread(target=check_in)
checkdelay.start()

while True:
    for line in str(s.recv(1024)).split('\\r\\n'):
        parts = line.split(':')
        if len(parts) < 3:
            continue

        message = parts[2][:len(parts[2])]
        usernamesplit = parts[1].split("!")
        username = usernamesplit[0]
        print(time.strftime("%H:%M:%S"), username + ": " + message)

When it crashes I get the traceback below:

Traceback (most recent call last):
  File "T:/Python/aftabot/sandbox.py", line 31, in <module>
    for line in str(s.recv(1024)).split('\\r\\n'):
ConnectionAbortedError: [WinError 10053] An established connection was aborted
by the software in your host machine

I thought this might mean the windows firewall might be killing the connection so I made sure python3 and PyCharm have permission in the firewall. Same result.

You’re sending PING rather than replying to PINGs with PONG

About once every five minutes, the server will send you a PING :tmi.twitch.tv. To ensure that your connection to the server is not prematurely terminated, reply with PONG :tmi.twitch.tv.
https://dev.twitch.tv/docs/irc

Thanks but, as I stated in the original post, I had code that responded to the Twitch Server PING and the bot would still disconnect. In an effort to diagnose if the PING response was the problem, the above code PINGs the server preemptively to keep the connection alive. It still disconnects.

Do you have your code that you were responding to pings? As far as I know no one here is a mind reader so without the proper code in question it’s going to be a little hard for anyone to help you.

About once every five minutes, the server will send you a PING :tmi.twitch.tv. To ensure that your connection to the server is not prematurely terminated, reply with PONG :tmi.twitch.tv.

Sure. Code below makes connection and reads the chat. As far as I can tell, it appears to be responding to two PINGs from Twitch and then disconnects after 10 minutes or so.

import socket
import time

HOST = "irc.chat.twitch.tv"
PORT = 6667
NICK = "xxxxxxxxxxxx"
PASS = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
CHANNEL = "xxxxxxxxxxxxxxxx"

def send_message(msg):
    s.send(bytes("PRIVMSG #" + CHANNEL + " :" + msg + "\r\n", "UTF-8"))

print("Connecting to host.")
s = socket.socket()
s.connect((HOST, PORT))
s.send(bytes("PASS " + PASS + "\r\n", "UTF-8"))
s.send(bytes("NICK " + NICK + "\r\n", "UTF-8"))
s.send(bytes("JOIN #" + CHANNEL + " \r\n", "UTF-8"))
print("Connected to host")

send_message("Connected to chat.")

while True:
    for line in str(s.recv(1024)).split('\\r\\n'):
        if "PING :tmi.twitch.tv" in line:
            print("PONG :tmi.twitch.tv")
            s.send(bytes("PONG :tmi.twitch.tv", "UTF-8"))

        parts = line.split(':')
        if len(parts) < 3:
            continue

        message = parts[2][:len(parts[2])]
        usernamesplit = parts[1].split("!")
        username = usernamesplit[0]
        print(time.strftime("%H:%M:%S"), username + ": " + message)

I’ve done this and the result is the same. I’ve posted the code in my answer to modesttim.

Replacing

s.send(bytes("PONG :tmi.twitch.tv", "UTF-8"))

with

s.send(bytes("PONG :tmi.twitch.tv\r\n", "UTF-8"))

Works fine for me, been running for 15 min without any disconnects.

2 Likes

Yup. Running for 17 minutes and still connected. Thank you very much for your help.

1 Like

Reason being, the RFC 1459 IRC spec requires all messages be terminated with a cr-lf (carriage return-line feed) pair, which is equivalent to \r\n.

offtopic:
here
for line in str(s.recv(1024)).split('\\r\\n'):
it should be \r\n, because \\r\\n is not a cr-lf, but a 4 chars (‘r’, ‘n’, and 2 backslashes)

1 Like

that’s a good point and not off-topic at all.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.