owncastcom.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #!/home/deadtom/python/.xmpp-venv/bin/python
  2. import config
  3. import logging
  4. from slixmpp import ClientXMPP
  5. import time
  6. import requests
  7. import json
  8. import sys
  9. import os
  10. logging.basicConfig(filename=config.log_file, level=logging.INFO)
  11. def get_now(): # This creates and returns a time stamp
  12. now = str(time.strftime("%Y/%m/%d %H:%M:%S"))
  13. return now
  14. def send_ownchat(msg):
  15. msg_body = {'body': msg}
  16. headers = {'Authorization': config.auth_bearer}
  17. response = requests.post(f'{config.api_url}/api/integrations/chat/send', data=json.dumps(msg_body),
  18. headers=headers)
  19. return response.json()
  20. class CommandBot(ClientXMPP):
  21. def __init__(self, jid, password):
  22. ClientXMPP.__init__(self, jid, password)
  23. self.add_event_handler("session_start", self.session_start)
  24. self.add_event_handler("message", self.message)
  25. self.add_event_handler("disconnected", self.do_reconnect)
  26. def session_start(self, event):
  27. self.send_presence()
  28. self.get_roster()
  29. def do_reconnect(self, event): # Try to reconnect if disconnected
  30. logging.info('Disconnected. Reconnecting...')
  31. time.sleep(1)
  32. os.execv(__file__, sys.argv)
  33. sys.exit()
  34. def message(self, msg):
  35. if msg['type'] in ('chat', 'normal'):
  36. self.msg = msg
  37. self.cmd = self.msg['body'] # Get the body out of the message
  38. self.cmd = self.cmd.lower() # Convert it to lower case to avoid problems looking up available commands
  39. self.sender = self.msg['from'] # Get sender
  40. self.sender = str(self.sender) # Convert to string so split() can work with it
  41. self.sender = self.sender.split('/')[0] # Only save the information before the forward slash
  42. time.sleep(1)
  43. if self.sender in config.approved_senders: # Check if the sender has permission to send commands
  44. self.send = send_ownchat(self.msg['body'])
  45. self.result = self.send
  46. logging.info(f'Recieved response \"{self.result}\" from Owncast server.')
  47. else: # If not, say so
  48. logging.info(f'{self.sender} sent a command, but is not in the approved senders list.')
  49. self.msg.reply('Access denied. You are not on the list.').send()
  50. try:
  51. if __name__ == '__main__':
  52. xmpp = CommandBot(config.user, config.passwd)
  53. xmpp.connect()
  54. xmpp.process(forever=True)
  55. except KeyboardInterrupt: # Catch ctrl-alt-del
  56. print('\nExiting program...')
  57. sys.exit()
  58. except Exception as error: # Log/print all other errors
  59. print(error)
  60. logging.info(f'ERROR:{error}')
  61. sys.exit()