Python : Check if IRC connection is lost (PING PONG?)

后端 未结 4 1857
一向
一向 2020-12-25 09:28

So my question is, how would i get my bot to listen if there is a PING and if there\'s no ping in an interval of a minute, it will react as though the connection has been lo

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 09:39

    last_ping = time.time()
    threshold = 5 * 60 # five minutes, make this whatever you want
    while connected:
        data = irc.recv ( 4096 )
        # If Nick is in use
        if data.find ( 'Nickname is already in use' ) != -1:
            NICK = NICK + str(time.time())
            Connection()
        # Ping Pong so we don't get disconnected
        if data.find ( 'PING' ) != -1:
            irc.send ( 'PONG ' + data.split() [ 1 ] + '\r\n' )
            last_ping = time.time()
        if (time.time() - last_ping) > threshold:
            break
    

    This will record the time each time it gets a ping, and if it goes too long without one, break out of the connected loop. You don't need while connected == True:, just while connected: does the same thing.

    Also, consider using connection instead of Connection, it's the Python convention to use capitalized names only for classes.

提交回复
热议问题