owncastcom.py 2.6 KB

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