owncastcom.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. import asyncio
  10. logging.basicConfig(filename=config.log_file, level=logging.INFO)
  11. def get_now(): # This creates a timestamp for the log
  12. now = str(time.strftime("%Y/%m/%d %H:%M:%S"))
  13. return now
  14. def send_ownchat(msg): # Sends the message to Owncast chat
  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): # The XMPP bot
  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()
  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. asyncio.get_event_loop().run_forever()
  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()