Skip to content

Instantly share code, notes, and snippets.

@zeekay
Created February 4, 2012 23:00
Show Gist options
  • Save zeekay/1740951 to your computer and use it in GitHub Desktop.
Save zeekay/1740951 to your computer and use it in GitHub Desktop.
import gevent
from gevent import queue, socket
class Tcp(object):
def __init__(self, settings):
self.host = settings['host']
self.port = settings['port']
self.recv_queue = queue.Queue()
self.send_queue = queue.Queue()
self.socket = socket.socket()
def connect(self):
self.socket.connect((self.host, self.port))
try:
jobs = [gevent.spawn(self.recv_loop), gevent.spawn(self.send_loop)]
gevent.joinall(jobs)
finally:
gevent.killall(jobs)
def disconnect(self):
self.socket.close()
def recv_loop(self):
while True:
data = self.socket.recv(4096)
for line in data.splitlines():
self.recv_queue.put(line)
def send_loop(self):
while True:
line = self.send_queue.get()
self.socket.send(line)
class Bot(Tcp):
def __init__(self, settings):
self.channels = settings['channels']
self.nick = settings['nick']
self.connection = Tcp(settings)
self.connect()
self.loop()
def connect(self):
gevent.spawn(self.connection.connect)
self.send('NICK', self.nick)
self.send('USER', self.nick, '3', '*', self.nick)
for channel in self.channels:
self.send('JOIN', channel)
def send(self, *args):
self.connection.send_queue.put(' '.join(args) + '\r\n')
def loop(self):
while True:
line = self.connection.recv_queue.get()
print line
SETTINGS = {
'host': 'irc.oftc.net',
'port': 6667,
'nick': 'botler',
'channels': ['#bots'],
}
if __name__ == '__main__':
jobs = [gevent.spawn(lambda: Bot(SETTINGS))]
gevent.joinall(jobs)
@gf0842wf
Copy link

Why use inheritance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment