I had been working on an IRC bot framework for a while, and I feel like I've finally got my code polished enough to share with other people. It's a asynchronous I/O bot with an event-oriented framework. Requires Python 3 to run.
import asynchat
import asyncore
import collections
import errno
import socket
try:
import ssl
except ImportError:
ssl = False
__verbose__ = True
"""
TODO:
threading support
password support
client abstraction
"""
#
class ParseError(Exception):
def __init__(self, raw):
if __verbose__:
print('ParseError: {raw}'.format(**locals()))
self.raw = raw
#
def parse_line(raw_line):
if __verbose__:
print('parsing line: \"{raw_line}\"'.format(**locals()))
try:
if raw_line.startswith(':'):
prefix, raw = raw_line[1:].split(' ', 1)
else:
prefix, raw = (None, raw_line)
parts = raw.split(' :', 1)
if len(parts) > 1:
trailing = parts[1]
else:
trailing = None
parts = parts[0].split(' ')
command = parts[0]
parameters = parts[1:]
if trailing is not None:
parameters.append(trailing)
except:
raise ParseError(raw_line)
if __verbose__:
print('prefix: {prefix}'.format(**locals()))
print('command: {command}'.format(**locals()))
print('parameters: {parameters}\n'.format(**locals()))
return prefix, command, parameters
#
class Publisher:
def __init__(self, subscribers=None):
if subscribers is None:
subscribers = collections.defaultdict(set)
self.subscribers = subscribers
def add(self, topic, subscriber):
self.subscribers[topic].add(subscriber)
def discard(self, topic, subscriber):
self.subscribers[topic].discard(subscriber)
def remove(self, topic, subscriber):
self.subscribers[topic].remove(subscriber)
def publish(self, topic, *args, **kwargs):
for subscriber in self.subscribers[topic]:
try:
subscriber(topic, *args, **kwargs)
except Exception as exception:
for subscriber in self.subscribers[exception]:
subscriber(topic, exception, *args, **kwargs)
"""Based on code by Evan Fosmark.
http://dev.guardedcode.com/projects/ircutils/
Copyright (c) 2010 Evan Fosmark
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE."""
class Connection(asynchat.async_chat):
def __init__(self,
host,
publisher=None,
port=None,
ssl_=False,
ipv6=False):
if port is None:
port = (6667, 7000)[ssl_]
self.address = (host, port)
self.publisher = publisher
self.ssl_ = ssl_
if ssl_:
if ssl:
self.recv = self._ssl_recv
self.send = self._ssl_send
else:
raise ImportError
asynchat.async_chat.__init__(self)
if ipv6:
self.create_socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_terminator(b'\r\n')
self.collect_incoming_data = self._collect_incoming_data
#
def found_terminator(self):
if __verbose__:
print('found terminator...')
data = self._get_data()
try:
prefix, command, parameters = parse_line(data.decode())
except ParseError as error:
self.publisher.publish(error, self)
else:
if __verbose__:
print('publishing line...\n')
self.publisher.publish(command, self, prefix, parameters)
#
def handle_connect(self):
if __verbose__:
print('connection established...')
if self.ssl_:
if __verbose__:
print('initializing ssl...')
self.ssl_ = ssl.wrap_socket(self.socket, do_handshake_on_connect=False)
self.set_socket(self.ssl_)
if __verbose__:
print('publishing handle_connect...\n')
self.publisher.publish('handle_connect', self)
def _ssl_recv(self, buffersize):
#TODO
pass
def _ssl_send(self, data):
#TODO
pass
#
def message(self, command, parameters=tuple(), trailing=None):
if __verbose__:
print('messaging...')
print('command: {command}'.format(**locals()))
print('parameters: {parameters}'.format(**locals()))
print('trailing: {trailing}'.format(**locals()))
parts = [command.upper()]
if parameters:
parts.append(' '.join(parameters))
if trailing:
parts.append(''.join((':', trailing)))
message = ''.join((' '.join(parts), '\r\n'))
data = message.encode()
if __verbose__:
print('data: {data}'.format(**locals()))
print()
self.push(data)
#
def connect(self):
if __verbose__:
print('connecting...')
asynchat.async_chat.connect(self, self.address)
self.publisher.publish('connect', self)
class Client:
pass
class Bot:
pass
if __name__ == '__main__':
import copy
def connect(topic, connection):
connection.message('NICK', (connection.nickname,))
connection.message('USER', (connection.user, '+B', '*'), trailing=connection.realname)
def pong(command, connection, prefix, parameters):
connection.message('PING', (parameters[0],))
def echo(bot_command, connection, args, bot_args):
connection.message('NOTICE', (args[2][0],), trailing=bot_args[1][0])
class PrivateMessageHandler:
def __init__(self, publisher=None):
if publisher is None:
publisher = Publisher()
self.publisher = publisher
def __call__(self, command, connection, prefix, parameters):
bot_prefix, bot_command, bot_parameters = parse_line(parameters[-1])
self.publisher.publish(bot_command, connection, (prefix, command, parameters), (bot_prefix, bot_parameters))
class Channel:
def __init__(self, channel):
self.channel = channel
def __call__(self, command, connection, prefix, parameters):
connection.message('JOIN', (self.channel,))
c = Connection('irc.dal.net', Publisher())
c.nickname = 'lrh9bot'
c.user = 'lrh9bot'
c.realname = 'lrh9bot'
pub = c.publisher
add = pub.add
add('PING', pong)
add('connect', connect)
add('376', Channel('#ai'))
priv_msg = private_message_handler = PrivateMessageHandler()
priv_msg.publisher.add('ECHO', echo)
add('PRIVMSG', priv_msg)
t = Connection('irc.freenode.net', copy.deepcopy(pub))
t.nickname = 'lrh9bot'
t.user = 'lrh9bot'
t.realname = 'lrh9bot'
t.publisher.add('376', Channel('#irchacks'))
c.connect()
t.connect()
asyncore.loop()