Search code examples
pythonsocketstwitchreconnect

I get Winerror 10038 when i try to reconnect


Twitch randomly disconnects my python bot. I googled a lot and found out that this is a common problem. Only solution seems to be an automated reconnect. Tried this, but my knowledge seems to be way too limited to make it work.

I tried to shut down the socket, close it and then use the same routine to connect that i initially use to connect. Tried a few variations, but nothing worked i Always get the Error-Code: "Winerror 10038" when i try to re-connect

import socket
import sys
import modules.cfg
import time

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

def connect():
    '''
    Connection to Twitch IRC using cfg.py
    '''
    irc.connect((modules.cfg.HOST,modules.cfg.PORT))
    irc.send(str("PASS " + modules.cfg.PASS + "\r\n").encode("utf-8"))
    irc.send(str("NICK " + modules.cfg.NICK + "\r\n").encode("utf-8"))
    irc.send(str("JOIN " + modules.cfg.CHAN + "\r\n").encode("utf-8"))
    irc.send(str("CAP REQ :twitch.tv/commands\r\n").encode("utf-8")) #whisper enable
    irc.send(str("CAP REQ :twitch.tv/membership\r\n").encode("utf-8"))

def read_chat():
    response = irc.recv(4096).decode('utf-8') #receive text
    if response == "PING :tmi.twitch.tv\r\n":
        print("Ping received")
        irc.send("PONG :tmi.twitch.tv\r\n".encode("utf-8")) 
    return response


def send(msg):
    try:
        irc.send("PRIVMSG {} : {}\r\n".format(modules.cfg.CHAN, msg).encode("utf-8"))
    except:
        irc.shutdown(socket.SHUT_RDWR)
        irc.close()
        print("\n\nDisconnected\n")
        time.sleep(10)
        connect()
        print("Reconnected\n\n")

I am pretty new to coding and it´s some kind of a hobby of mine. Hopefully someone can help me! Thank you guys


Solution

  • Thx to user207421 i finally found the way.. for me it is a bit strange, but it works.

    def re_connect():
        irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        irc.connect((modules.cfg.HOST,modules.cfg.PORT))
        irc.send(str("PASS " + modules.cfg.PASS + "\r\n").encode("utf-8"))
        irc.send(str("NICK " + modules.cfg.NICK + "\r\n").encode("utf-8"))
        irc.send(str("JOIN " + modules.cfg.CHAN + "\r\n").encode("utf-8"))
        irc.send(str("CAP REQ :twitch.tv/commands\r\n").encode("utf-8")) #whisper enable
        irc.send(str("CAP REQ :twitch.tv/membership\r\n").encode("utf-8"))
    
    
    def send(msg):
        try:
            irc.send("PRIVMSG {} : {}\r\n".format(modules.cfg.CHAN, msg).encode("utf-8"))
        except:
            irc.shutdown(socket.SHUT_RDWR)
            irc.close()
            print("\n\nDisconnected\n")
            time.sleep(10)
            re_connect()
            print("Reconnected\n\n")