Skip to content

Instantly share code, notes, and snippets.

@chris-belcher
Created December 14, 2016 15:55
Show Gist options
  • Save chris-belcher/39033530fe550506b833e71c6f19f82d to your computer and use it in GitHub Desktop.
Save chris-belcher/39033530fe550506b833e71c6f19f82d to your computer and use it in GitHub Desktop.
IRC script which sends its own pings without creating any other threads
#irc script which sends its own pings without creating any other threads
import socket, random
from datetime import datetime
nick = 'testbot-' + hex(random.randint(0, 0xffffff))[2:]
hostport = ('irc.snoonet.org', 6667)
ping_interval_seconds = 30
ping_timeout_seconds = 60
sock = socket.socket()
sock.connect(hostport)
print 'connected'
sock.settimeout(10)
sock.sendall('USER user b c :real\r\n')
sock.sendall('NICK ' + nick + '\r\n')
try:
recv_buffer = ""
last_ping = datetime.now()
waiting_for_pong = False
while 1:
try:
#print 'reading'
recv_data = sock.recv(4096)
if not recv_data or len(recv_data) == 0:
raise EOFError()
recv_buffer += recv_data
lb = recv_data.find('\n')
if lb == -1:
continue
while lb != -1:
line = recv_buffer[:lb].rstrip()
recv_buffer = recv_buffer[lb + 1:]
lb = recv_buffer.find('\n')
print str(datetime.now()) + ' ' + line
chunks = line.split(' ')
if chunks[0] == 'PING':
sock.sendall(line.replace('PING', 'PONG') + '\r\n')
elif len(chunks) > 1 and chunks[1] == 'PONG':
print 'server replied to ping'
last_ping = datetime.now()
waiting_for_pong = False
except socket.timeout:
#print 'timed out'
if waiting_for_pong:
if (datetime.now() - last_ping).total_seconds() < ping_timeout_seconds:
continue
print 'server ping timed out'
sock.close()
else:
if (datetime.now() - last_ping).total_seconds() < ping_interval_seconds:
continue
last_ping = datetime.now()
print 'sending ping to server'
waiting_for_pong = True
sock.sendall('PING :hello world\r\n')
except IOError as e:
print repr(e)
finally:
try:
sock.close()
except IOError:
pass
print 'end'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment