1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#!/usr/bin/env python
"""
IRC Bot Example
This example shows how to use several components in circuits as well
as one of the builtin networking protocols. This IRC Bot simply connects
to the Libera.Chat IRC Network and joins the #circuits channel. It will also
echo anything privately messages to it in response.
"""
import sys
from circuits import Component, Debugger
from circuits.net.sockets import TCPClient, connect
from circuits.protocols.irc import ERR_NICKNAMEINUSE, ERR_NOMOTD, IRC, JOIN, NICK, PRIVMSG, RPL_ENDOFMOTD, USER
class Bot(Component):
# Define a separate channel so we can create many instances of ``Bot``
channel = 'ircbot'
def init(self, host='irc.libera.chat', port='6667', channel=channel):
self.host = host
self.port = int(port)
# Add TCPClient and IRC to the system.
TCPClient(channel=self.channel).register(self)
IRC(channel=self.channel).register(self)
def ready(self, component):
"""
Ready Event
This event is triggered by the underlying ``TCPClient`` Component
when it is ready to start making a new connection.
"""
self.fire(connect(self.host, self.port))
def connected(self, host, port):
"""
connected Event
This event is triggered by the underlying ``TCPClient`` Component
when a successfully connection has been made.
"""
self.fire(NICK('circuits'))
self.fire(USER('circuits', 'circuits', host, 'Test circuits IRC Bot'))
def disconnected(self):
"""
disconnected Event
This event is triggered by the underlying ``TCPClient`` Component
when the connection is lost.
"""
raise SystemExit(0)
def numeric(self, source, numeric, *args):
"""
Numeric Event
This event is triggered by the ``IRC`` Protocol Component when we have
received an IRC Numberic Event from server we are connected to.
"""
if numeric == ERR_NICKNAMEINUSE:
self.fire(NICK(f'{args[0]:s}_'))
elif numeric in (RPL_ENDOFMOTD, ERR_NOMOTD):
self.fire(JOIN('#circuits'))
def privmsg(self, source, target, message):
"""
Message Event
This event is triggered by the ``IRC`` Protocol Component for each
message we receieve from the server.
"""
if target.startswith('#'):
self.fire(PRIVMSG(target, message))
else:
self.fire(PRIVMSG(source[0], message))
# Configure and run the system
bot = Bot(*sys.argv[1:])
Debugger().register(bot)
# To register a 2nd ``Bot`` instance. Simply use a separate channel.
# Bot(*sys.argv[1:], channel="foo").register(bot)
bot.run()
|