import config import logging from slixmpp import ClientXMPP import time import requests import json import sys import os import asyncio logging.basicConfig(filename=config.log_file, level=logging.INFO) def get_now(): # This creates a timestamp for the log now = str(time.strftime("%Y/%m/%d %H:%M:%S")) return now def send_ownchat(msg): # Sends the message to Owncast chat msg_body = {'body': msg} headers = {'Authorization': config.auth_bearer} response = requests.post(f'{config.api_url}/api/integrations/chat/send', data=json.dumps(msg_body), headers=headers) return response.json() class CommandBot(ClientXMPP): # The XMPP bot def __init__(self, jid, password): ClientXMPP.__init__(self, jid, password) self.add_event_handler("session_start", self.session_start) self.add_event_handler("message", self.message) self.add_event_handler("disconnected", self.do_reconnect) def session_start(self, event): self.send_presence() self.get_roster() def do_reconnect(self, event): # Try to reconnect if disconnected logging.info('Disconnected. Reconnecting...') time.sleep(1) os.execv(__file__, sys.argv) sys.exit() def message(self, msg): if msg['type'] in ('chat', 'normal'): self.msg = msg self.cmd = self.msg['body'] # Get the body out of the message self.cmd = self.cmd.lower() self.sender = self.msg['from'] # Get sender self.sender = str(self.sender) # Convert to string so split() can work with it self.sender = self.sender.split('/')[0] # Only save the information before the forward slash time.sleep(1) if self.sender in config.approved_senders: # Check if the sender has permission to send commands self.send = send_ownchat(self.msg['body']) self.result = self.send logging.info(f'Recieved response \"{self.result}\" from Owncast server.') else: # If not, say so logging.info(f'{self.sender} sent a command, but is not in the approved senders list.') self.msg.reply('Access denied. You are not on the list.').send() try: if __name__ == '__main__': xmpp = CommandBot(config.user, config.passwd) xmpp.connect() asyncio.get_event_loop().run_forever() except KeyboardInterrupt: # Catch ctrl-alt-del print('\nExiting program...') sys.exit() except Exception as error: # Log/print all other errors print(error) logging.info(f'ERROR:{error}') sys.exit()