Ending infinite loop for a bot
<p>I have created a chat bot for <strong>Twitch IRC</strong>, I can connect and create commands etc etc, however I cannot use keyboard-interrupt in the command prompt. I suspect it is because it's stuck in this infinite loop, and I don't know how to fix this? I am new to programming btw!</p>

<p>Here is the code I have in my <code>Run.py</code>, <code>openSocket()</code> is defined in another file, basically connection to the server. <code>s = socket.socket.</code>
First part in the while-loop basically just reads the server messages, I think it's pretty straight forward for you guys!</p>

<pre><code>s = openSocket()
joinRoom(s)
readbuffer = ""

while True:
        readbuffer = readbuffer + s.recv(1024).decode("utf-8")
        temp = str.split(readbuffer, "\n")
        readbuffer = temp.pop()

        for line in temp:
            if "PING" in line:
                s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
                print("---SENT PONG---")
            printMessage(getUser, getMessage, line)
            message = getMessage(line)

            for key in commands:
                command = key
                if command in message:
                    sendMessage(s, commands[command])
</code></pre>

<p>((Edit: I also have this problem where the connection to the server seems to time out for whatever reason. I managed to get it keep connection with ping/pong for about 40-45min, but then it disconnected again.</p>

<p>EDIT:</p>

<p>Sorry the original post was super messy. I have created this pastebin with the least amount of code I could use to recreate the problem.
If the IRC chat is inactive it will disconnect, and I can't get it to send 2 pings in a row without any messages in between, not sure if that's because it disconnects before the 2nd ping or because of the 2nd ping.</p>

<p>On at least one occasion it has disconnected even before I got the first ping from the server.</p>

<p>Pastebin: pastebin.com/sXUW50sS</p>

<p>Part of code that you posted doesn't have much to do with problem you described.</p>

<p>This is a guess (although an educated one). In you socket connection you are probably using <code>try: except:</code> and using <code>Pokemon</code> approach (gotta catch 'em all)</p>

<p>Thing here would be to find a line where you are doing something like this:</p>

<pre><code>except:
    pass
</code></pre>

<p>and change it to:</p>

<pre><code>except (KeyboardInterrupt, SystemExit):
    raise
except:
    pass
</code></pre>

<p>Obviously I'm not trying to say here that your porgram should catch all exceptions and just pass like if nothing happened. Main point is that you are probably already doing that (for i-have-no-idea-why reasons) and you should have special treatment for system errors.</p>

python loops infinite