ircbot/ircbot/__init__.py

46 lines
1.3 KiB
Python
Raw Permalink Normal View History

2013-02-23 17:44:57 -08:00
import re
2013-02-23 17:03:18 -08:00
2013-02-23 15:22:22 -08:00
from twisted.words.protocols import irc
2013-02-24 20:42:00 -08:00
from twisted.internet import protocol
2013-02-23 15:22:22 -08:00
2013-02-23 17:44:57 -08:00
class IRCBot(irc.IRCClient):
2013-02-23 15:22:22 -08:00
@property
def nickname(self):
return self.factory.nickname
def signedOn(self):
for c in self.factory.channels:
self.join(c)
2013-02-23 15:22:22 -08:00
print('signed on as {}.'.format(self.nickname))
def joined(self, channel):
print('joined {}'.format(channel))
def privmsg(self, user, channel, msg):
2013-02-24 20:42:00 -08:00
""" deals with messages, both private and public, in a channel
Your code will most likely go in here.
"""
username = user.split('!', 1)[0]
if channel == self.nickname:
self.msg(username, "whisper back ...")
if self.nickname in msg:
2013-02-23 17:44:57 -08:00
msg = self.factory.nick_stripper.sub('', msg)
self.msg(channel, 'echo: {}'.format(msg))
2013-02-23 15:22:22 -08:00
2013-02-23 17:44:57 -08:00
class IRCBotFactory(protocol.ClientFactory):
protocol = IRCBot
2013-02-23 15:22:22 -08:00
2013-02-23 17:44:57 -08:00
def __init__(self, channels, nickname='bot'):
self.channels = channels
2013-02-23 15:22:22 -08:00
self.nickname = nickname
2013-02-23 17:44:57 -08:00
self.nick_stripper = re.compile(r'{}\s*?\:?'.format(self.nickname))
2013-02-23 15:22:22 -08:00
def clientConnectionLost(self, connector, reason):
print('lost connection({}), reconnecting.'.format(reason))
def clientConnectionFailed(self, connector, reason):
print('could not connect: {}'.format(reason))