Python Forum
Twitch Chat Bot - Disconnects after 10 minutes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Twitch Chat Bot - Disconnects after 10 minutes
#1
Sad 
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question download watsapp chat Orliv 1 1,761 Jan-26-2021, 07:01 PM
Last Post: Larz60+
  Chat bot akanowhere 16 5,895 Dec-12-2019, 02:47 PM
Last Post: akanowhere
  Could you help with this bug I have looked for like 20 minutes ryder5227 1 2,207 Sep-29-2019, 10:58 PM
Last Post: jefsummers
  Python instantly closes (Twitch Plays, Python 2) JustHelpMePlease 1 1,920 Jun-16-2019, 06:29 AM
Last Post: stranac
  I am trying to send message in youtube live chat stylohunk 1 2,590 Jun-08-2019, 04:06 PM
Last Post: SheeppOSU
  calculating the datetime objects to get the minutes chris0147 1 2,931 Apr-04-2018, 12:04 AM
Last Post: snippsat
  just a trial. Please wait 5 minutes before deleting this thread sylas 2 3,439 Jun-06-2017, 03:34 PM
Last Post: snippsat
  Subtract Minutes from Datetime.Time tkj80 2 43,065 May-11-2017, 09:56 AM
Last Post: klllmmm
  Host and port problems for UDP chat server YevesDraco 2 3,820 May-07-2017, 04:35 PM
Last Post: YevesDraco
  How to use a UDP server and client to setup a chat abrew132 2 3,767 Mar-20-2017, 06:22 PM
Last Post: abrew132

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020