webhooks.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. from flask import Flask, request, json, Blueprint, current_app, render_template, jsonify, request
  2. from ownchatbot.db import get_db
  3. from ownchatbot.owncast_com import send_chat
  4. from ownchatbot.user_handlers import add_user_to_points, change_name, get_users_points, remove_duplicates
  5. from ownchatbot.bot_messages import do_reward, help_message
  6. from ownchatbot.reward_handlers import all_active_goals, all_active_votes
  7. from ownchatbot.kofi_handlers import accept_donation
  8. import json
  9. ocb = Blueprint('webhooks', __name__)
  10. def format(rawjson): # Make data legible
  11. formatted_data = json.dumps(rawjson, indent=4)
  12. return formatted_data
  13. @ocb.route('/kofiHook', methods=["POST"])
  14. def kofiHook():
  15. current_app.logger.info(f'----------------------------------------------------------------------------')
  16. current_app.logger.info(f'Kofi request')
  17. if request.content_type == 'application/x-www-form-urlencoded':
  18. raw_data = request.form.get('data') # Get the kofi data
  19. if raw_data:
  20. raw_data = json.loads(raw_data)
  21. is_authed = raw_data['verification_token']
  22. if is_authed == current_app.config['KOFI_TOKEN']:
  23. type = raw_data['type']
  24. is_public = raw_data['is_public']
  25. if is_public:
  26. from_name = raw_data['from_name']
  27. new_sub = raw_data['is_first_subscription_payment']
  28. message = raw_data['message']
  29. shop_items = raw_data['shop_items']
  30. name = raw_data['from_name']
  31. email = raw_data['email']
  32. amount = raw_data['amount']
  33. sub_payment = raw_data['is_subscription_payment']
  34. first_sub = raw_data['is_first_subscription_payment']
  35. tier_name = raw_data['tier_name']
  36. if type == 'Shop Order':
  37. current_app.logger.info(f'\n{name} purchased {format(shop_items)}\nMessage: {message}\n')
  38. if type == 'Donation':
  39. donation_info = [is_public, name, email, amount, message]
  40. tip_points = current_app.config['KOFI_SETTINGS']['tip_points']
  41. accept_donation(donation_info, tip_points)
  42. if type == 'Subscription':
  43. if first_sub:
  44. if tier_name:
  45. current_app.logger.info(f'\n{name} <{email}> subscribed as a {tier_name} tier member.')
  46. else:
  47. current_app.logger.info(f'\n{name} <{email}> subscribed.')
  48. else:
  49. if tier_name:
  50. current_app.logger.info(f'\n{name} <{email}> renewed their {tier_name} tier membership.')
  51. else:
  52. current_app.logger.info(f'\n{name} <{email}> renewed their membership.')
  53. return jsonify({'status': 'success'}), 200
  54. else:
  55. current_app.logger.info(f'Token invalid. Rejecting.')
  56. return jsonify({'status': 'unauthorized'}), 401
  57. @ocb.route('/chatHook', methods=['POST'])
  58. def chat_hook():
  59. prefix = current_app.config['PREFIX']
  60. data = request.json
  61. db = get_db()
  62. if data['type'] in ['CHAT', 'NAME_CHANGED', 'USER_JOINED']: # Check if the viewer is in the chatbot database
  63. user_id = data['eventData']['user']['id']
  64. authed = data['eventData']['user']['authenticated']
  65. display_name = data['eventData']['user']['displayName']
  66. if add_user_to_points(db, user_id, display_name, authed):
  67. current_app.logger.debug(f'Added/updated {user_id} database.')
  68. if data['type'] == 'USER_JOINED': # Do username house cleaning when a viewer joins
  69. if data['eventData']['user']['authenticated']:
  70. remove_duplicates(db, user_id, display_name)
  71. elif data['type'] == 'NAME_CHANGE':
  72. user_id = data['eventData']['user']['id']
  73. new_name = data['eventData']['newName']
  74. change_name(db, user_id, new_name)
  75. if data['eventData']['user']['authenticated']:
  76. remove_duplicates(db, user_id, new_name)
  77. elif data['type'] == 'CHAT': # If a chat message, sort out what command it is
  78. user_id = data['eventData']['user']['id']
  79. display_name = data['eventData']['user']['displayName']
  80. current_app.logger.debug(f'Chat message from {display_name}:')
  81. current_app.logger.debug(f'{data["eventData"]["rawBody"]}')
  82. lowercase_msg = data['eventData']['rawBody'].lower() # Convert body to lower case to match reward case
  83. if lowercase_msg.startswith(f'{prefix}help'): # Send the help message
  84. help_message()
  85. elif lowercase_msg.startswith(f'{prefix}points'): # Get the viewer's current points
  86. points = get_users_points(db, user_id)
  87. if points is None:
  88. send_chat('Couldn\'t get your points, for some highly technical reason.')
  89. else:
  90. send_chat(f'{display_name}, you have {points} points.')
  91. elif lowercase_msg.startswith(f'{prefix}rewards'): # Send rewards list
  92. if current_app.config['REWARDS']:
  93. rewards_msg = f'Currently active rewards:'
  94. for reward, details in current_app.config['REWARDS'].items():
  95. if details.get('categories'):
  96. if not (set(details['categories']) & set(current_app.config['ACTIVE_CAT'])): # If there are no common categories, continue
  97. continue
  98. if 'type' in details and details['type'] == 'goal':
  99. rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} goal at {details["target"]} contributed points.'
  100. else:
  101. rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} for {details["price"]} points.'
  102. if 'info' in details:
  103. rewards_msg = f'{rewards_msg}<br>{details["info"]}'
  104. else:
  105. rewards_msg = f'{rewards_msg}'
  106. else:
  107. rewards_msg = 'There are currently no active rewards.'
  108. send_chat(rewards_msg)
  109. elif lowercase_msg.startswith(f'{prefix}'): # Send to handle rewards
  110. do_reward(lowercase_msg, user_id)
  111. return data
  112. @ocb.route('/goals', methods=['GET']) # Route for goals overlay
  113. def goals():
  114. db = get_db()
  115. return render_template('goals.html',
  116. goals=all_active_goals(db))
  117. @ocb.route('/votes', methods=['GET']) # Route for votes overlay
  118. def votes():
  119. db = get_db()
  120. return render_template('votes.html',
  121. votes=all_active_votes(db))