Skip to content

Commit

Permalink
Attempt to handle IRC reconnection
Browse files Browse the repository at this point in the history
  • Loading branch information
parklez committed Jul 9, 2021
1 parent 39e896b commit feeb536
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 16 deletions.
2 changes: 1 addition & 1 deletion parky_bot/gui/main_window.py
Expand Up @@ -52,5 +52,5 @@ def on_closing(self):
# self.send = None
# gc.collect()

self.bot.irc.disconnect()
self.bot.is_pooling = False
self.bot.irc.disconnect()
44 changes: 29 additions & 15 deletions parky_bot/twitch/bot.py
Expand Up @@ -16,42 +16,54 @@ def __init__(self, irc, twitch=None):
self.is_pooling = True
self.twitch_init = False
self.irc_init = False
self.irc_connected_successfully = False

def pooling(self):
if not self.irc.username:
LOGGER.info('IRC username not set, stopping...')
return

def connect_to_twitch(self):
if not self.twitch_init and self.twitch and self.twitch.channel:
LOGGER.debug('Initializing Twitch API connection...')
self.twitch_init = True
self.twitch.connect()

def connect_to_chat(self):
if not self.irc.username:
LOGGER.info('IRC username not set, stopping...')
return

if not self.irc_init:
LOGGER.debug('Initializing chat connection...')
self.irc_init = True
self.irc.welcome()

def pooling(self):
self.connect_to_twitch()
self.connect_to_chat()
data = ''
self.irc.irc_sock.setblocking(0)
LOGGER.info('Now pooling...')
LOGGER.debug('Attemping to receive message from chat...')

while self.is_pooling:
try:
data = self.irc.irc_sock.recv(6144).decode('UTF-8')
if not self.irc_connected_successfully:
self.irc_connected_successfully = True
LOGGER.info('Connected to chat - GLHF!')
except (ConnectionAbortedError, OSError):
try:
time.sleep(0.1)
except KeyboardInterrupt:
self.is_pooling = False
if not self.is_pooling:
break
LOGGER.error('Connection aborted... re-connecting in 3 seconds...')
time.sleep(3)
self.irc_connected_successfully = False
self.irc.reconnect()
continue
except KeyboardInterrupt:
self.is_pooling = False
break
return

if data == '':
LOGGER.critical('IRC client received 0 bytes, stopping...')
self.is_pooling = False
break
LOGGER.error('Received 0 bytes from chat, re-connecting in 3 seconds...')
time.sleep(3)
self.irc_connected_successfully = False
self.irc.reconnect()
continue

if data == 'PING :tmi.twitch.tv\r\n':
self.irc.send_pong()
Expand All @@ -72,6 +84,8 @@ def pooling(self):
self.filter(m)

data = ''
time.sleep(0.1)

LOGGER.info('Stopped pooling.')

def filter(self, message: Message):
Expand Down
5 changes: 5 additions & 0 deletions parky_bot/twitch/irc.py
Expand Up @@ -24,6 +24,11 @@ def __init__(self, username: str, channel: str, token: str):

#self.welcome()

def reconnect(self):
self.disconnect()
self.irc_sock = socket.socket()
self.welcome()

def welcome(self):
"""Connects to twitch IRC in few steps:
Expand Down

0 comments on commit feeb536

Please sign in to comment.