webhooks.py 8.5 KB

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