Reputation: 867
I am trying to make an IRC bot, but it keeps timing out after 240 seconds. How can I fix this?
import socket
host = 'test'
port = 6667
channel = '#test'
nick = "test"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send('NICK ' + str(nick) + ' \n\r')
s.send('USER v v v :v Script' + '\r\n')
s.send('JOIN '+channel+' \n\r')
while True:
command = s.recv(4096)
print command
Upvotes: 2
Views: 1435
Reputation: 38442
My problem was that I wasn't even reliably receiving PING packets from the IRC server. I fixed it by adding keepalives at the socket level:
# enable keepalives at the socket (SOL_SOCKET) level
self.client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# after 1 second of TCP inactivity, trigger keepalive pings
self.client.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
# send a keepalive ping every 60 seconds
self.client.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 60)
# quit after 5 consecutive failures
self.client.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
That, combined with sending back a PONG for each PING, is keeping my connection open longer.
Upvotes: 0
Reputation: 174977
You aren't replying to ping requests from the server.
When you're idle for a long time, the server thinks the connection is dead, and sends a ping request, you need to reply with pong (and whatever the server sent to you after the ping). So if the server sent you this, that should be your reply:
PING :HELLO_WORLD
PONG :HELLO_WORLD
Without that, the server will confirm the link is dead and terminate the connection.
Upvotes: 5
Reputation: 110311
You could try using irclib- however hat is happening,most likely, is that you are not replying to the server's PING message.
Whenever a received message starts with "PING", you have to reply it with a "PONG" message containg the word PONG and your program name (and optionally host) - leaving an space after "PONG".
Check the full IRC specifcations for PING and PONG messages, and take a look onother things ou might be missing along your experiments: http://www.irchelp.org/irchelp/rfc/rfc.html
Upvotes: 1