Python Forum
Twitch Chat Bot - Disconnects after 10 minutes - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Twitch Chat Bot - Disconnects after 10 minutes (/thread-7070.html)



Twitch Chat Bot - Disconnects after 10 minutes - sp4wny - Dec-20-2017

Task to complete:
So i decided to learn Python (i'm a complete novice) and my first project is a Twitch Chat bot. (my code is listed below) but i'm having the most annoying issue i've come across.

Problem:
After 10 minutes of inactivity my bot disconnects and stops replying to commands.

Is anyone able to help me with why my bot would disconnect after 10 minutes? I'm sure its relating to the PING/PONG stage that needs to take place, I can see the PING in my Python console, but i never see a PONG reply from my bot.

Any assistance anyone can offer would be gratefully appreciated!

# import functions/scripts
import socket
import threading
import traceback
from time import sleep

### connecting to Twitch IRC // DO NOT CHANGE THIS VALUE
HOST = "irc.chat.twitch.tv"
PORT = 6667

### User Editable Settings
NICK = "sp4wnytv"  # Bots nickname
CHAN = "sp4wnyuk"  # Channel bot is joining
PASS = "INSERTYOURKEYHERE"  #Twitch OAuth

readbuffer = ""
MODT = False

### DO NOT EDIT THESE VALUES
CHANNEL_NAME = CHAN
CHANNEL_NAME = CHANNEL_NAME.lower()
SLEEP_TIME = 120
IRC_CHANNEL = "#" + CHANNEL_NAME


# Connecting to Twitch IRC by passing credentials and joining a certain channel
s = socket.socket()
s.connect((HOST, PORT))
s.send(bytes("PASS %s\r\n" % PASS, "UTF-8"))
s.send(bytes("NICK %s\r\n" % NICK, "UTF-8"))
s.send(bytes("JOIN #%s\r\n" % CHAN, "UTF-8"))
s.send(bytes("CAP REQ :twitch.tv/membership\r\n", "UTF-8"))
s.send(bytes("CAP REQ :twitch.tv/commands\r\n", "UTF-8"))
s.send(bytes("CAP REQ :twitch.tv/tags\r\n", "UTF-8"))


def socketconnection():
    global s, HOST, PORT, NICK, CHAN
    try:
        s.close()
        s.socket.socket()
        s.connect((HOST, PORT))
        s.send(bytes("PASS %s\r\n" % PASS, "UTF-8"))
        s.send(bytes("NICK %s\r\n" % NICK, "UTF-8"))
        s.send(bytes("JOIN #%s\r\n" % CHAN, "UTF-8"))
        s.send(bytes("CAP REQ :twitch.tv/membership\r\n", "UTF-8"))
        s.send(bytes("CAP REQ :twitch.tv/commands\r\n", "UTF-8"))
        s.send(bytes("CAP REQ :twitch.tv/tags\r\n", "UTF-8"))
    except:
        print(traceback.format_exc())

### Functions


def getuser(line):
    separate = line.split(":", 2)
    user = separate[1].split("!", 1)[0]
    return user


def sendmessage(text):
    # Method for sending a message
    # message = "PRIVMSG #" + CHAN + " :" + str(text)
    s.send(bytes("PRIVMSG #" + CHAN + " :" + str(text) + "\r\n", "UTF-8"))


def console(line):
    # Gets if it is a user or twitch server
    if "PRIVMSG" in line:
        return False
    else:
        return True


def puppet():
    try:
        while True:
            message = input(' assuming direct control: ')
            sendmessage(message)
            commands(message, 'sp4wnybot')
    except BrokenPipeError:
        socketconnection()


def commands(message, username):

    if message == "!meme":
        sendmessage("EleGiggle")

    if message == "!sliced":
        sendmessage("**unsheathes katana**")

    if message == "!whoami":
        sendmessage(username)

    if message == "!points":
        requestpoints(message, username)

    if message == '!uptimet':
        uptime()

    if message == '!followage':
        followage(username)

    if message == '!followers':
        followcount()


sendmessage('bot has joined the channel HeyGuys')
t = threading.Thread(target=puppet).start()


def messageloop():
    while True:
        global s, readbuffer, dbcon, cursor

        try:
            readbuffer = readbuffer + s.recv(1024).decode("UTF-8")
        except KeyboardInterrupt:
            raise
        except:
            print(traceback.format_exc())

        temp = str.split(readbuffer, "\r\n")
        # temp = [ str(e.encode('UTF-8')).rstrip() for e in temp ]
        readbuffer = temp.pop()

        for line in temp:
            print("LINE PRINT | " + line)
            if line[0] == "PING":
                s.send(bytes("PONG %s\r\n" % line[1], "UTF-8"))
                s.send("PONG :tmi.twitch.tv\r\n".encode("UTF-8"))
                print("PONG REPLIED: " + line[1])
                break

            if line == "":
                break

            if "PRIVMSG" in line:

                parts = str.split(line, ":")
                message = parts[2][:len(parts[2])]

                usernamesplit = str.split(parts[1], "!")
                username = usernamesplit[0]

                cursor.execute('INSERT OR IGNORE INTO channelPoints (username, points) VALUES (?,?)', (username, '0'))
                givepoints(username, 1)
                dbcon.commit()

                commands(message.lower(), username.lower())
                print("[Chat] " + getuser(line) + " : " + message)

            else:
                parts = str.split(line, ":")

                try:
                    message = parts[2][:len(parts[2])]
                except:
                    message = ""

                usernamesplit = str.split(parts[1], "!")
                username = usernamesplit[0]

                print("[Bot] " + username + " : " + message)
                commands(message.lower(), username.lower())
            sleep(1)


MAX_SEND_RATE = 20
SEND_RATE_WITHIN_SECONDS = 30


while True:
    try:
        messageloop()
    except KeyboardInterrupt:
        raise
    except:
        print(traceback.format_exc())
        socketconnection()
        messageloop()

Just to advise, you may see references to points or database updating, i have removed the core mechanics for this and just stripped my bot back to the basic connect and respond commands while i trouble shoot this issue