owncast_com.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from flask import current_app
  2. import requests
  3. from ownchatbot.user_handlers import award_chat_points
  4. def live_now(): # Check if stream is live
  5. owncast_url = current_app.config['OWNCAST_URL']
  6. if owncast_url != '': # If owncast URL is set, award points
  7. url = f'{owncast_url}/api/status'
  8. try:
  9. response = requests.get(url)
  10. except requests.exceptions.RequestException as cserror:
  11. current_app.logger.error(f'Couldn\'t check if stream is live: {cserror.args[0]}')
  12. return False
  13. return response.json()['online']
  14. else:
  15. current_app.logger.error('Owncast url is not set. Can\'t check if stream is live.')
  16. def award_points(db): # Award points to users
  17. owncast_url = current_app.config['OWNCAST_URL']
  18. access_token = current_app.config['ACCESS_TOKEN']
  19. url = f'{owncast_url}/api/integrations/clients'
  20. auth_bearer = f'Bearer {access_token}'
  21. headers = {'Authorization': auth_bearer}
  22. try:
  23. response = requests.get(url, headers=headers)
  24. except requests.exceptions.RequestException as aperror:
  25. current_app.logger.error(f'Couldn\'t get user info: {aperror.args[0]}')
  26. return
  27. if response.status_code != 200:
  28. current_app.logger.error(f'Couldn\'t award points: {response.status_code}.')
  29. return
  30. unique_users = set(map(lambda user_object: user_object['user']['id'], response.json()))
  31. for user_id in unique_users:
  32. award_chat_points(db, user_id, current_app.config['POINTS_AWARD'])
  33. def send_chat(message): # Send message to owncast chat
  34. owncast_url = current_app.config['OWNCAST_URL']
  35. access_token = current_app.config['ACCESS_TOKEN']
  36. url = f'{owncast_url}/api/integrations/chat/send'
  37. auth_bearer = f'Bearer {access_token}'
  38. headers = {'Authorization': auth_bearer}
  39. try:
  40. response = requests.post(url, headers=headers, json={'body': message})
  41. except requests.exceptions.RequestException as scerror:
  42. current_app.logger.error(f'Couldn\'t send {message} to Owncast: {scerror.args[0]}')
  43. return
  44. if response.status_code != 200:
  45. current_app.logger.error(f'Couldn\'t send {message} to Owncast: {response.status_code}.')
  46. return
  47. return response.json()