pluto/handler/irc.py

235 lines
7.9 KiB
Python
Raw Normal View History

2021-12-24 17:24:45 +00:00
# Twisted/Klein imports
from twisted.logger import Logger
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor, ssl
from twisted.internet.task import deferLater
2021-12-24 17:24:45 +00:00
# Project imports
from settings import settings
2021-12-28 12:50:19 +00:00
from commands import IRCCommands
2021-12-24 17:24:45 +00:00
class IRCBot(irc.IRCClient):
def __init__(self, log):
2021-12-27 21:27:41 +00:00
"""
Initialise IRC bot.
:param log: logger instance
:type log: Logger
"""
2021-12-24 17:24:45 +00:00
self.log = log
2021-12-28 12:50:19 +00:00
self.cmd = IRCCommands()
# Parse the commands into "commandname": "commandclass"
self.cmdhash = {getattr(self.cmd, x).name: x for x in dir(self.cmd) if not x.startswith("_")}
2021-12-24 17:24:45 +00:00
self.nickname = settings.IRC.Nick
self.password = settings.IRC.Pass
self.realname = self.nickname
self.username = self.nickname
2021-12-27 21:13:13 +00:00
# Don't give away information about our client
2021-12-24 17:24:45 +00:00
self.userinfo = None
self.fingerReply = None
self.versionName = None
self.sourceURL = None
2021-12-27 21:13:13 +00:00
self.lineRate = None # Don't throttle messages, we may need to send a lot
2021-12-24 17:24:45 +00:00
2021-12-27 13:50:32 +00:00
self.prefix = settings.IRC.Prefix
2021-12-24 17:24:45 +00:00
self.admins = (settings.IRC.Admins).split("\n")
self.highlight = (settings.IRC.Highlight).split("\n")
2021-12-27 19:30:03 +00:00
self.channel = settings.IRC.Channel
2021-12-24 17:24:45 +00:00
def parse(self, user, host, channel, msg):
2021-12-27 21:13:13 +00:00
"""
Simple handler for IRC commands.
2021-12-27 21:19:58 +00:00
:param user: full user string with host
:param host: user's hostname
:param channel: channel the message was received on
:param msg: the message
2021-12-27 21:27:41 +00:00
:type user: string
:type host: string
:type channel: string
:type msg: string
2021-12-27 21:13:13 +00:00
"""
2021-12-24 17:24:45 +00:00
spl = msg.split()
# nick = user.split("!")[0]
cmd = spl[0]
2021-12-31 00:51:43 +00:00
length = len(spl)
2021-12-24 17:24:45 +00:00
2021-12-28 12:50:19 +00:00
# Check if user is authenticated
authed = host in self.admins
2021-12-31 00:51:43 +00:00
if cmd == "help" and length == 2 and authed:
if spl[1] in self.cmdhash:
cmdname = self.cmdhash[spl[1]]
obj = getattr(self.cmd, cmdname)
helptext = getattr(obj, "helptext")
self.msg(channel, helptext)
return
else:
self.msg(channel, f"No such command: {spl[1]}")
return
if cmd == "helpall" and authed:
for command in self.cmdhash:
cmdname = self.cmdhash[command]
obj = getattr(self.cmd, cmdname)
helptext = getattr(obj, "helptext")
self.msg(channel, f"{cmdname}: {helptext}")
return
2021-12-28 12:50:19 +00:00
if cmd in self.cmdhash:
# Get the class name of the referenced command
cmdname = self.cmdhash[cmd]
# Get the class name
obj = getattr(self.cmd, cmdname)
def msgl(x):
self.msg(channel, x)
# Check if the command required authentication
if obj.authed:
if host in self.admins:
2022-01-27 19:12:15 +00:00
obj.run(cmd, spl, length, authed, msgl, self.agora, self.revolut, self.tx, self.notify)
2021-12-28 12:50:19 +00:00
else:
# Handle authentication here instead of in the command module for security
self.msg(channel, "Access denied.")
2021-12-27 22:09:35 +00:00
else:
2021-12-28 12:50:19 +00:00
# Run an unauthenticated command, without passing through secure library calls
obj.run(cmd, spl, len(spl), authed, msgl)
return
self.msg(channel, "Command not found.")
if authed:
# Give user command hints if they are authenticated
self.msg(channel, f"Commands loaded: {', '.join(self.cmdhash.keys())}")
2021-12-24 17:24:45 +00:00
def signedOn(self):
2021-12-27 21:13:13 +00:00
"""
Called when we have signed on to IRC.
Join our channel.
"""
2021-12-24 17:24:45 +00:00
self.log.info("Signed on as %s" % (self.nickname))
deferLater(reactor, 2, self.join, self.channel)
2021-12-24 17:24:45 +00:00
def joined(self, channel):
2021-12-27 21:13:13 +00:00
"""
Called when we have joined a channel.
Setup the Agora LoopingCall to get trades.
This is here to ensure the IRC client is initialised enough to send the trades.
2021-12-27 21:19:58 +00:00
:param channel: channel we joined
2021-12-27 21:27:41 +00:00
:type channel: string
2021-12-27 21:13:13 +00:00
"""
2021-12-27 19:30:03 +00:00
self.agora.setup_loop()
2021-12-24 17:24:45 +00:00
self.log.info("Joined channel %s" % (channel))
def privmsg(self, user, channel, msg):
2021-12-27 21:13:13 +00:00
"""
Called on received PRIVMSGs.
Pass through identified commands to the parse function.
2021-12-27 21:19:58 +00:00
:param user: full user string with host
:param channel: channel the message was received on
:param msg: the message
2021-12-27 21:27:41 +00:00
:type user: string
:type channel: string
:type msg: string
2021-12-27 21:13:13 +00:00
"""
2021-12-24 17:24:45 +00:00
nick = user.split("!")[0]
if channel == self.nickname:
channel = nick
host = user.split("!")[1]
host = host.split("@")[1]
ident = user.split("!")[1]
ident = ident.split("@")[0]
self.log.info("(%s) %s: %s" % (channel, user, msg))
if msg[0] == self.prefix:
if len(msg) > 1:
if msg.split()[0] != "!":
self.parse(user, host, channel, msg[1:])
2021-12-28 12:50:19 +00:00
elif host in self.admins and channel == nick:
if len(msg) > 0:
spl = msg.split()
if len(spl) > 0:
if spl[0] != "!":
self.parse(user, host, channel, msg)
2021-12-24 17:24:45 +00:00
2021-12-27 21:19:58 +00:00
def noticed(self, user, channel, msg):
2021-12-27 21:13:13 +00:00
"""
Called on received NOTICEs.
2021-12-27 21:19:58 +00:00
:param user: full user string with host
:param channel: channel the notice was received on
:param msg: the message
2021-12-27 21:27:41 +00:00
:type user: string
:type channel: string
:type msg: string
2021-12-27 21:13:13 +00:00
"""
2021-12-24 17:24:45 +00:00
nick = user.split("!")[0]
if channel == self.nickname:
channel = nick
2021-12-27 21:19:58 +00:00
# self.log.info("[%s] %s: %s" % (channel, user, msg))
2021-12-24 17:24:45 +00:00
class IRCBotFactory(protocol.ClientFactory):
def __init__(self):
self.log = Logger("irc")
2021-12-27 13:50:32 +00:00
def sendmsg(self, msg):
"""
Passthrough function to send a message to the channel.
"""
if self.client:
self.client.msg(self.client.channel, msg)
else:
self.log.error("Trying to send a message without connected client: {msg}", msg=msg)
return
2021-12-24 17:24:45 +00:00
def buildProtocol(self, addr):
2021-12-27 21:13:13 +00:00
"""
Custom override for the Twisted buildProtocol so we can access the Protocol instance.
Passes through the Agora instance to IRC.
:return: IRCBot Protocol instance
"""
2021-12-24 17:24:45 +00:00
prcol = IRCBot(self.log)
self.client = prcol
2022-02-07 13:24:09 +00:00
setattr(self.client, "agora", self.agora)
setattr(self.client, "revolut", self.revolut)
setattr(self.client, "tx", self.tx)
setattr(self.client, "notify", self.notify)
2021-12-24 17:24:45 +00:00
return prcol
def clientConnectionLost(self, connector, reason):
2021-12-27 21:13:13 +00:00
"""
Called when connection to IRC server lost. Reconnect.
2021-12-27 21:19:58 +00:00
:param connector: connector object
:param reason: reason connection lost
2021-12-27 21:27:41 +00:00
:type connector: object
:type reason: string
2021-12-27 21:13:13 +00:00
"""
2021-12-27 21:27:41 +00:00
self.log.error("Lost connection: {reason}, reconnecting", reason=reason)
2021-12-24 17:24:45 +00:00
connector.connect()
def clientConnectionFailed(self, connector, reason):
2021-12-27 21:13:13 +00:00
"""
Called when connection to IRC server failed. Reconnect.
2021-12-27 21:19:58 +00:00
:param connector: connector object
:param reason: reason connection failed
2021-12-27 21:27:41 +00:00
:type connector: object
:type reason: string
2021-12-27 21:13:13 +00:00
"""
2021-12-27 21:27:41 +00:00
self.log.error("Could not connect: {reason}", reason=reason)
2021-12-27 13:50:32 +00:00
connector.connect()
2021-12-24 17:24:45 +00:00
def bot():
2021-12-27 21:27:41 +00:00
"""
Load the certificates, start the Bot Factory and connect it to the IRC server.
:return: Factory instance
:rtype: Factory
"""
2021-12-27 21:19:58 +00:00
# Load the certificates
2021-12-24 17:35:41 +00:00
context = ssl.DefaultOpenSSLContextFactory(settings.IRC.Cert, settings.IRC.Cert)
2021-12-27 21:19:58 +00:00
# Define the factory instance
2021-12-24 17:24:45 +00:00
factory = IRCBotFactory()
reactor.connectSSL(settings.IRC.Host, int(settings.IRC.Port), factory, context)
return factory