owncast_com.py 2.0 KB

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