From 87ca8a5e431f3d0d0b918db13d4939a679223f50 Mon Sep 17 00:00:00 2001 From: Adrien Bourmault Date: Tue, 8 Feb 2022 15:46:17 +0100 Subject: [PATCH] WIP: refactoring --- bot_main.py | 231 ------------------------------------------------- commands.py | 8 ++ localServer.py | 20 +++-- serviceData.py | 183 --------------------------------------- 4 files changed, 22 insertions(+), 420 deletions(-) delete mode 100755 bot_main.py delete mode 100644 serviceData.py diff --git a/bot_main.py b/bot_main.py deleted file mode 100755 index d7963ab..0000000 --- a/bot_main.py +++ /dev/null @@ -1,231 +0,0 @@ -#!/usr/bin/env python3 - -import logging -from getpass import getpass -from argparse import ArgumentParser -import slixmpp -import random -import threading -import socket -import time -import signal - -from hintTables import * -from commands import * -from serviceData import ServiceData -from localServer import LocalServer - -class MUCBot(slixmpp.ClientXMPP): - - """ - A simple Slixmpp bot that will greets those - who enter the room, and acknowledge any messages - that mentions the bot's nickname. - """ - - def __init__(self, jid, password, room, nick): - slixmpp.ClientXMPP.__init__(self, jid + "/Isengard", password) - - self.room = room - self.nick = nick - self.owners = {} - self.serviceData = None - - # The session_start event will be triggered when - # the bot establishes its connection with the server - # and the XML streams are ready for use. We want to - # listen for this event so that we we can initialize - # our roster. - self.add_event_handler("session_start", self.start) - - # The groupchat_message event is triggered whenever a message - # stanza is received from any chat room. If you also also - # register a handler for the 'message' event, MUC messages - # will be processed by both handlers. - self.add_event_handler("groupchat_message", self.muc_message) - - # The groupchat_presence event is triggered whenever a - # presence stanza is received from any chat room, including - # any presences you send yourself. To limit event handling - # to a single room, use the events muc::room@server::presence, - # muc::room@server::got_online, or muc::room@server::got_offline. - self.add_event_handler("muc::%s::got_online" % self.room, - self.muc_online) - - - async def start(self, event): - """ - Requestthe roster and broadcast initial presence stanza. - """ - - await self.get_roster() - self.send_presence() - self.plugin['xep_0045'].join_muc(self.room, - self.nick, - # password=the_room_password, - ) - - def push(self, destmuc, msg): - self.send_message( mto=destmuc, - mbody=msg, - mtype='groupchat') - print("To: %s\nBody: %s" % (destmuc, msg)) - - def muc_message(self, msg): - """ - Whenever the bot's nickname is mentioned, respond to - the message from any muc - """ - - if msg['mucnick'] == self.nick: - return - - # Commands - - cmdhints = list(commandtable.keys()) - random.shuffle(cmdhints) - - for opcod in cmdhints: - if msg['body'][0] == "!" and opcod in msg['body']: - self.send_message(mto=msg['from'].bare, - mbody="%s, %s" % (msg['mucnick'], - commandtable[opcod](self.owners[msg['from'].bare], - msg['mucnick'], - msg['body'], - self.serviceData)), - mtype='groupchat') - return - - # When people speak to each other without necessarily highlighting Isengard - - anechints = list(annecdotetable.keys()) - random.shuffle(anechints) - - for hint in anechints: - if hint in msg['body']: - self.send_message(mto=msg['from'].bare, - mbody="%s" % (annecdotetable[hint][ - random.randrange(0,len(annecdotetable[hint])) - ]), - mtype='groupchat') - return - - if self.nick not in msg['body']: - return - - # When people talk to Isengard - - topichints = list(topictable.keys()) - random.shuffle(topichints) - - for hint in topichints: - if hint in msg['body']: - self.send_message(mto=msg['from'].bare, - mbody="%s, %s" % (msg['mucnick'], - topictable[hint][ - random.randrange(0,len(topictable[hint])) - ]), - mtype='groupchat') - return - - # And fallback - - self.send_message(mto=msg['from'].bare, - mbody="%s, je n'ai pas compris (je suis un peu bot)" % msg['mucnick'], - mtype='groupchat') - - def muc_online(self, presence): - """ - Send a welcome message that includes - the user's nickname - """ - - if presence['muc']['nick'] in self.serviceData.maintainerData: - self.send_message(mto=presence['from'].bare, - mbody="Salut %s, vos services ont produit des " + - "alertes en votre absence !\nUtilisez la commande"+ - " `hist` pour consulter l'historique" - % (presence['muc']['nick']), - mtype='groupchat') - - if presence['muc']['affiliation'] == "owner": - if not presence['from'].bare in self.owners: - self.owners[presence['from'].bare] = [] - - self.owners[presence['from'].bare].append(presence['muc']['nick']) - -if __name__ == '__main__': - - def cleanExit(): - global localservthread - localservthread.pleaseStop = True - # stop tcp server - sockfd = socket.socket() - port = 12346 - sockfd.connect(('127.0.0.1', port)) - sockfd.send(b'') - sockfd.close() - - exit(0) - - - def signalHandler(sig, frame): - print("Exiting...") - cleanExit() - - signal.signal(signal.SIGINT, signalHandler) - - # Setup the command line arguments. - parser = ArgumentParser() - - # Output verbosity options. - parser.add_argument("-q", "--quiet", help="set logging to ERROR", - action="store_const", dest="loglevel", - const=logging.ERROR, default=logging.INFO) - parser.add_argument("-d", "--debug", help="set logging to DEBUG", - action="store_const", dest="loglevel", - const=logging.DEBUG, default=logging.INFO) - - # JID and password options. - parser.add_argument("-j", "--jid", dest="jid", - help="JID to use") - parser.add_argument("-p", "--password", dest="password", - help="password to use") - parser.add_argument("-r", "--room", dest="room", - help="MUC room to join") - parser.add_argument("-n", "--nick", dest="nick", - help="MUC nickname") - - args = parser.parse_args() - - # Setup logging. - logging.basicConfig(level=args.loglevel, - format='%(levelname)-8s %(message)s') - - # Setup the MUCBot and register plugins. Note that while plugins may - # have interdependencies, the order in which you register them does - # not matter. - xmpp = MUCBot(args.jid, args.password, args.room, args.nick) - xmpp.register_plugin('xep_0030') # Service Discovery - xmpp.register_plugin('xep_0045') # Multi-User Chat - xmpp.register_plugin('xep_0199') # XMPP Ping - - # Create buffer - sBuffer = ServiceData(xmpp) - xmpp.serviceData = sBuffer - - # Connect to the XMPP server and start processing XMPP stanzas. - xmpp.connect() - - localservthread = LocalServer(sBuffer) - localservthread.start() - - time.sleep(1) - - if not localservthread.is_alive(): - exit(1) - - try: - xmpp.process() - except KeyboardInterrupt: - cleanExit() diff --git a/commands.py b/commands.py index a9d2a1a..295f1fe 100644 --- a/commands.py +++ b/commands.py @@ -1,4 +1,12 @@ import pickle +import logging +from systemd.journal import JournalHandler + +# Logging +log = logging.getLogger(__name__) +log.addHandler(JournalHandler()) +log.setLevel(logging.INFO) + # Isengard commands diff --git a/localServer.py b/localServer.py index 8a7bdbe..04a763d 100644 --- a/localServer.py +++ b/localServer.py @@ -1,19 +1,27 @@ import random import threading import socket +import logging +from systemd.journal import JournalHandler + +# Logging +log = logging.getLogger(__name__) +log.addHandler(JournalHandler()) +log.setLevel(logging.INFO) + class LocalServer(threading.Thread): def __init__(self, sharedBuffer): threading.Thread.__init__(self) self.sharedBuffer = sharedBuffer self.pleaseStop = False - + def run(self): - - sockfd = socket.socket() + + sockfd = socket.socket() print("Socket successfully created") port = 12346 # Reserve a port on your computer...in our case it is 12345, but it can be anything - sockfd.bind(('127.0.0.1', port)) + sockfd.bind(('127.0.0.1', port)) print("Socket binded to %s" %(port)) sockfd.listen(5) # Put the socket into listening mode print("Socket is listening") @@ -23,10 +31,10 @@ class LocalServer(threading.Thread): print('Got connection from', addr) rcvStr = client.recv(1024).decode() print(rcvStr) - + if rcvStr != '': self.sharedBuffer.push(rcvStr) - + client.send(b'') # Send a message to the client client.close() print("Socket is listening") diff --git a/serviceData.py b/serviceData.py deleted file mode 100644 index b77c6ef..0000000 --- a/serviceData.py +++ /dev/null @@ -1,183 +0,0 @@ -import datetime - -class ServiceData: - - def __init__(self, linkedBot): - self.serviceData = {} - self.maintainerData = {} - self.linkedBot = linkedBot - - def flush(self): - - for host in self.serviceData: - if not isinstance(self.serviceData[host], dict): - continue - - maintainer = self.serviceData[host]["maintainer"] - - if self.serviceData[host]["needUpdate"]: - destmuc = self.serviceData[host]["destmuc"] - text = self.serviceData[host]["text"] - msg = "(néant)" - - if self.serviceData[host]["status_type"] == "PROBLEM": - msg = "{}, je détecte un problème sur {} ({})".format(maintainer, host, text) - - elif self.serviceData[host]["status_type"] == "UNKNOWN": - msg = "{}, état de {} inconnu ({})".format(maintainer, host, text) - - elif self.serviceData[host]["status_type"] == "CUSTOM": - msg = "{}, nouvelle notification de {} ({})".format(maintainer, host, text) - - elif self.serviceData[host]["status_type"] == "RECOVERY": - msg = "{}, problème résolu sur {} ({})".format(maintainer, host, text) - - self.linkedBot.push(destmuc, msg) - - self.serviceData[host]["needUpdate"] = False - - for service in self.serviceData[host]: - if not isinstance(self.serviceData[host][service], dict): - continue - - if self.serviceData[host][service]["needUpdate"]: - destmuc = self.serviceData[host][service]["destmuc"] - text = self.serviceData[host][service]["text"] - msg = "(néant)" - - if self.serviceData[host]["status_type"] == "PROBLEM" or - self.serviceData[host]["status_type"] == "UNKNOWN": - msg = "{}, je détecte de multiples problèmes sur {}".format(maintainer, host) - - elif self.serviceData[host][service]["status_type"] == "PROBLEM": - msg = "{}, je détecte un problème de {} sur {} ({})".format(maintainer, service, host, text) - - elif self.serviceData[host][service]["status_type"] == "UNKNOWN": - msg = "{}, état de {} inconnu pour {} ({})".format(maintainer, service, host, text) - - elif self.serviceData[host][service]["status_type"] == "RECOVERY": - msg = "{}, problème de {} résolu sur {} ({})".format(maintainer, service, host, text) - - self.linkedBot.push(destmuc, msg) - - self.serviceData[host][service]["needUpdate"] = False - - print("End of flush") - - def push(self, msg): - - # $notification.type$|$host.display_name$/$service.name$|$service.state$|$service.output$|$notification.author$|$notification.comment$ - # EX: cominfra@salons.a-lec.org|CUSTOM|ctrlv.chalec.org/SSH server|CRITICAL|connect to address ctrlv.chalec.org and port 22: Connexion refusée|neox@a-lec.org|AGAIN - try: - # Get current time - curtime = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S") - - # Get all params - destmuc, status_type, location, status_state, text, sender, comment = msg.split("|") - print("Dest: %s, Msg: %s" % (destmuc, msg)) - print("Status: %s" % (status_type + " (" + status_state + ")")) - - # check if message is about a service or host - if len(location.split("/")) > 1: - host, service = location.split("/") - else: - host = location - service = False - print("Host: %s, Service: %s" % (host, service)) - - print("Text: %s" % (text)) - - except Exception as e: - print("ERROR in serviceData.push():" + str(e)) - return - - # Is that host known - if host in self.serviceData: - - # Is it a service and is it known - if service and service in self.serviceData[host]: - # update host if needed - self.serviceData[host][service]["status_state"] = status_state - self.serviceData[host][service]["status_type"] = status_type - self.serviceData[host][service]["destmuc"] = destmuc - self.serviceData[host][service]["text"] = text - maintainer = self.serviceData[host]["maintainer"] - if status_type != self.serviceData[host][service]["status_type"] and - status_type != self.serviceData[host]["status_type"]: - self.serviceData[host][service]["needUpdate"] = True - - - # Is it an unkown service - elif service: - # create zone for service - self.serviceData[host][service] = {} - self.serviceData[host][service]["destmuc"] = destmuc - self.serviceData[host][service]["status_state"] = status_state - self.serviceData[host][service]["status_type"] = status_type - self.serviceData[host][service]["text"] = text - maintainer = self.serviceData[host]["maintainer"] - if status_type != self.serviceData[host]["status_type"]: - self.serviceData[host][service]["needUpdate"] = True - - # This is a host (not a service) - else: - # update host if needed - self.serviceData[host]["destmuc"] = destmuc - self.serviceData[host]["status_state"] = status_state - self.serviceData[host]["status_type"] = status_type - self.serviceData[host]["text"] = text - maintainer = self.serviceData[host]["maintainer"] - if status_type != self.serviceData[host]["status_type"]: - self.serviceData[host]["needUpdate"] = True - - # That host is not known - else: - - # create slot for host and service - if service: - self.serviceData[host] = {} - self.serviceData[host]["destmuc"] = None - self.serviceData[host]["status_state"] = None - self.serviceData[host]["status_type"] = None - self.serviceData[host]["text"] = None - self.serviceData[host]["maintainer"] = "Tout le monde" - self.serviceData[host]["needUpdate"] = False - self.serviceData[host][service] = {} - self.serviceData[host][service]["destmuc"] = destmuc - self.serviceData[host][service]["status_state"] = status_state - self.serviceData[host][service]["status_type"] = status_type - self.serviceData[host][service]["text"] = text - self.serviceData[host][service]["needUpdate"] = True - maintainer = self.serviceData[host]["maintainer"] - - # create slot for host - else: - self.serviceData[host] = {} - self.serviceData[host]["destmuc"] = destmuc - self.serviceData[host]["status_state"] = status_state - self.serviceData[host]["status_type"] = status_type - self.serviceData[host]["text"] = text - self.serviceData[host]["maintainer"] = "Tout le monde" - self.serviceData[host]["needUpdate"] = True - maintainer = self.serviceData[host]["maintainer"] - - # create maintainer in maintainer data if needed - if not maintainer in self.maintainerData: - self.maintainerData[maintainer] = {} - - # create host entry - if not service: - service = "GENERAL" - - if not host in self.maintainerData[maintainer]: - self.maintainerData[maintainer][host] = [] - - self.maintainerData[maintainer][host].append( - "%s [%s]: %s %s (%s %s)" % (curtime, status_state, service, text, sender, comment) - ) - - print(self.serviceData) - print("Flushing...") - self.flush() - print(self.serviceData) - print("End of push")