Created
December 20, 2011 21:14
-
-
Save FSX/1503305 to your computer and use it in GitHub Desktop.
A very simple IRC bot. It does nothing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import socket | |
from tornado import ioloop | |
from tornado import iostream | |
RE_ORIGIN = re.compile(r'([^!]*)!?([^@]*)@?(.*)') | |
def parse_origin(raw_origin): | |
"""Parse a string similar to 'FSX!~FSX@hostname' | |
into 'FSX', '~FSX' and 'hostname'""" | |
match = RE_ORIGIN.match(raw_origin or '') | |
return match.groups() # Nickname, username, hostname | |
class IrcClient(object): | |
def __init__(self, host, port, ssl=False): | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) | |
if ssl: | |
self._stream = iostream.SSLIOStream(s) | |
else: | |
self._stream = iostream.IOStream(s) | |
self._stream.connect((host, port), self._handle_connect) | |
def _handle_connect(self): | |
# Send nick and channels | |
self._write(('NICK', 'TestBot')) | |
self._write(('USER', 'TestBot', '+iw', 'TestBot'), 'TestBot') | |
self._write(('JOIN',), '#somerandomchannel') | |
self._stream.read_until('\r\n', self._on_read) | |
def _on_read(self, data): | |
print '<< %r' % data | |
# Split source from data | |
if data.startswith(':'): | |
source, data = data[1:].split(' ', 1) | |
else: | |
source = None | |
# Split arguments from message | |
if ' :' in data: | |
args, data = data.split(' :', 1) | |
else: | |
args, data = data, '' | |
args = args.split() | |
# Parse the source (where the data comes from) | |
nickname, username, hostname = parse_origin(source) | |
# Respond to server ping to keep connection alive | |
if args[0] == 'PING': | |
self._write(('PONG', data)) | |
self._stream.read_until('\r\n', self._on_read) | |
def _write(self, args, text=None): | |
if text is not None: | |
self._stream.write('%s :%s\r\n' % (' '.join(args), text)) | |
else: | |
self._stream.write('%s\r\n' % ' '.join(args)) | |
if __name__ == '__main__': | |
IrcClient('irc.rizon.net', 9999, True) | |
ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment