kofi_handlers.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. from flask import current_app
  2. from sqlite3 import Error
  3. from ownchatbot.db import get_db
  4. from ownchatbot.user_handlers import get_id_by_email, award_chat_points, add_email_to_points, get_all_users_with_user_id
  5. from ownchatbot.owncast_com import send_chat
  6. import json
  7. import os
  8. def accept_donation(donation_info, tip_points):
  9. db = get_db()
  10. is_public = donation_info[0]
  11. email = donation_info[2]
  12. amount = donation_info[3]
  13. amount = int(float(amount)) # Convert from str to int
  14. message = donation_info[4]
  15. points = amount * tip_points # Multiply by streamers tip point award
  16. ids = get_id_by_email(db, email)
  17. if not ids: # If no id found with that email address
  18. if add_email_to_points(db, email, points): # Create empty account with email and points
  19. name = 'Someone'
  20. current_app.logger.info(f'No user with email \"{email}\" found in database, created empty account.')
  21. else: # Grant points to the corresponding id
  22. for id in ids:
  23. if award_chat_points(db, id[0], points): # Grant points
  24. for user in get_all_users_with_user_id(db, id[0]):
  25. name = user[1]
  26. current_app.logger.info(f'Granted user id {id[0]} {points} points for their ${amount} donation.')
  27. if is_public:
  28. message = f'{name} got {points} points for tipping ${amount} on Kofi!'
  29. current_app.logger.info(f'Public donation of ${amount} received from {name}')
  30. else:
  31. message = None
  32. current_app.logger.info(f'Private donation of ${amount} received from {name}')
  33. if message is not None: # Only send chat message if it's a public donation
  34. send_chat(message)
  35. def save_kofi_settings(ksettings_info): # Write rewards to kofi.py
  36. settings_file = os.path.join(current_app.instance_path, 'kofi.py')
  37. try:
  38. with open(settings_file, 'w') as f:
  39. f.write(f'KOFI_SETTINGS = {ksettings_info}')
  40. f.close
  41. current_app.config.from_pyfile('kofi.py', silent=True) # Reread kofi.py into the app
  42. except Exception as sks_error:
  43. current_app.logger.error(f'Couldn\'t save kofi.py: {sks_error.args[0]}')
  44. return False
  45. return True
  46. def kofi_pngs(): # Create a list of all pngs in the kofi img dir
  47. png_dir = 'static/img/kofi'
  48. png_dir = os.path.join(current_app.root_path, png_dir)
  49. png_files = []
  50. for file in os.listdir(png_dir):
  51. if file.lower().endswith('.png'):
  52. png_files.append(file)
  53. return png_files