webhooks.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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, award_chat_points, user_in_points, get_all_users_with_user_id
  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. from ownchatbot import followers, donations, subscribers, rgoal, rmilestone
  11. ocb = Blueprint('webhooks', __name__)
  12. def format(rawjson): # Make data legible
  13. formatted_data = json.dumps(rawjson, indent=4)
  14. return formatted_data
  15. @ocb.route('/chatHook', methods=['POST'])
  16. def chat_hook():
  17. prefix = current_app.config['PREFIX']
  18. data = request.json
  19. db = get_db()
  20. if data['type'] in ['CHAT', 'NAME_CHANGED', 'USER_JOINED']: # Check if the viewer is in the chatbot database
  21. user_id = data['eventData']['user']['id']
  22. authed = data['eventData']['user']['authenticated']
  23. display_name = data['eventData']['user']['displayName']
  24. if add_user_to_points(db, user_id, display_name, authed):
  25. current_app.logger.debug(f'Added/updated {user_id} database.')
  26. current_app.logger.debug(f'{display_name}/{user_id}: {data["eventData"]}') # Log all chat messages
  27. if data['type'] == 'USER_JOINED': # Do username house cleaning when a viewer joins
  28. if data['eventData']['user']['authenticated']:
  29. remove_duplicates(db, user_id, display_name)
  30. elif data['type'] == 'NAME_CHANGE':
  31. user_id = data['eventData']['user']['id']
  32. new_name = data['eventData']['newName']
  33. change_name(db, user_id, new_name)
  34. if data['eventData']['user']['authenticated']:
  35. remove_duplicates(db, user_id, new_name)
  36. elif data['type'] == 'CHAT': # If a chat message, sort out what command it is
  37. user_id = data['eventData']['user']['id']
  38. display_name = data['eventData']['user']['displayName']
  39. current_app.logger.info(f'{display_name}/{user_id}: {data["eventData"]["rawBody"]}') # Log all chat messages
  40. lowercase_msg = data['eventData']['rawBody'].lower() # Convert body to lower case to match reward case
  41. if lowercase_msg.startswith(f'{prefix}help'): # Send the help message
  42. help_message(user_id)
  43. elif lowercase_msg.startswith(f'{prefix}points'): # Get the viewer's current points
  44. points = get_users_points(db, user_id)
  45. if points is None:
  46. send_private_chat(user_id, f'{display_name}, couldn\'t get your points, for some highly technical reason.')
  47. else:
  48. send_private_chat(user_id, f'{display_name}, you have {points} points.')
  49. elif lowercase_msg.startswith(f'{prefix}reg_mail'): # Generate a code to verify users account for email registration
  50. if current_app.config['KOFI_INTEGRATION']:
  51. mail_reg_code = get_email_code(db, user_id)
  52. if mail_reg_code: # If the viewer already has a code waiting
  53. 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!')
  54. else: # if not
  55. mail_reg_code = random.randint(100000, 999999)
  56. if set_email_code(db, user_id, mail_reg_code):
  57. 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!')
  58. else:
  59. send_chat(f'{display_name}, Kofi integration is not enabled on this stream.')
  60. elif lowercase_msg.startswith(f'{prefix}rewards'): # Send rewards list
  61. if current_app.config['REWARDS']:
  62. rewards_msg = f'Currently active rewards:'
  63. for reward, details in current_app.config['REWARDS'].items():
  64. if details.get('categories'):
  65. if not (set(details['categories']) & set(current_app.config['ACTIVE_CAT'])): # If there are no common categories, continue
  66. continue
  67. if 'type' in details and details['type'] == 'goal':
  68. rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} goal at {details["target"]} contributed points.'
  69. else:
  70. rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} for {details["price"]} points.'
  71. if 'info' in details:
  72. rewards_msg = f'{rewards_msg}<br>{details["info"]}'
  73. else:
  74. rewards_msg = f'{rewards_msg}'
  75. else:
  76. rewards_msg = 'There are currently no active rewards.'
  77. send_private_chat(user_id, rewards_msg)
  78. elif lowercase_msg.startswith(f'{prefix}'): # Send to handle rewards
  79. do_reward(lowercase_msg, user_id)
  80. return data
  81. @ocb.route('/followHook', methods=['POST']) # Called by Owncast when someone follows
  82. def follow_hook():
  83. data = request.json
  84. current_app.logger.debug(f'\n\n_______________\n/newFollow triggered!\n_______________')
  85. followers.append(data)
  86. return jsonify({'status': 'success'}), 200
  87. @ocb.route('/kofiHook', methods=["POST"])
  88. def kofi_hook():
  89. current_app.logger.info(f'----------------------------------------------------------------------------')
  90. current_app.logger.info(f'Kofi request')
  91. if request.content_type == 'application/x-www-form-urlencoded':
  92. raw_data = request.form.get('data') # Get the kofi data
  93. if raw_data:
  94. raw_data = json.loads(raw_data)
  95. is_authed = raw_data['verification_token']
  96. if is_authed == current_app.config['KOFI_TOKEN']:
  97. type = raw_data['type']
  98. is_public = raw_data['is_public']
  99. new_sub = raw_data['is_first_subscription_payment']
  100. message = raw_data['message']
  101. shop_items = raw_data['shop_items']
  102. from_name = raw_data['from_name']
  103. email = raw_data['email']
  104. amount = raw_data['amount']
  105. sub_payment = raw_data['is_subscription_payment']
  106. first_sub = raw_data['is_first_subscription_payment']
  107. tier_name = raw_data['tier_name']
  108. if type == 'Shop Order':
  109. current_app.logger.info(f'{from_name} purchased {format(shop_items)}\nMessage: {message}\n')
  110. if type == 'Donation':
  111. donation_info = [is_public, from_name, email, amount, message]
  112. donation_points = current_app.config['KOFI_SETTINGS']['donation_points']
  113. accept_donation(donation_info, donation_points)
  114. if is_public:
  115. alert_info = {'name': from_name, 'amount': amount}
  116. else:
  117. alert_info = {'name': 'Anonymous Hero', 'amount': amount}
  118. donations.append(alert_info) # Append info to be displayed in alert
  119. if type == 'Subscription':
  120. if current_app.config['KOFI_SETTINGS']['subs']: # Check that subscriptions are enabled
  121. if first_sub:
  122. if tier_name:
  123. current_app.logger.info(f'{from_name} <{email}> subscribed as a {tier_name} tier member.')
  124. else:
  125. current_app.logger.info(f'{from_name} <{email}> subscribed.')
  126. else:
  127. if tier_name:
  128. current_app.logger.info(f'{from_name} <{email}> renewed their {tier_name} tier membership.')
  129. else:
  130. current_app.logger.info(f'{from_name} <{email}> renewed their membership.')
  131. sub_info = [is_public, from_name, email, amount, message, first_sub, tier_name]
  132. sub_points = current_app.config['KOFI_SETTINGS']['sub_points']
  133. accept_sub(sub_info, sub_points)
  134. if is_public:
  135. alert_info = {'name': from_name, 'tiername': tier_name}
  136. else:
  137. alert_info = {'name': 'Anonymous Hero', 'teirname': tier_name}
  138. subscribers.append(alert_info) # Append info to be displayed in alert
  139. else:
  140. current_app.logger.info(f'Kofi membership received, but subscriptions are not enabled. Doing nothing.')
  141. return jsonify({'status': 'success'}), 200
  142. else:
  143. current_app.logger.info(f'Token invalid. Rejecting.')
  144. return jsonify({'status': 'unauthorized'}), 401
  145. @ocb.route('/checkFollows') # Polled by follower.html template to check for new followers
  146. def check_follows():
  147. global followers
  148. if followers:
  149. current_app.logger.debug(f'\n\n{format(followers[0])}\n\n')
  150. last_follower = followers.pop(0)
  151. return jsonify(last_follower)
  152. else:
  153. current_app.logger.info(f'No new followers')
  154. return jsonify(None)
  155. @ocb.route('/checkGoals') # Polled by follower.html template to check for new followers
  156. def check_goals():
  157. global rgoals
  158. if rgoals:
  159. current_app.logger.debug(f'\n\n{format(rgoals[0])}\n\n')
  160. last_goal = rgoals.pop(0)
  161. return jsonify(last_goal)
  162. else:
  163. current_app.logger.info(f'No new goals reached')
  164. return jsonify(None)
  165. return jsonify(None)
  166. @ocb.route('/checkMilestones') # Polled by follower.html template to check for new followers
  167. def check_milestones():
  168. global rmilestones
  169. if rmilestones:
  170. current_app.logger.debug(f'\n\n{format(rmilestones[0])}\n\n')
  171. last_milestone = rmilestones.pop(0)
  172. return jsonify(last_milestone)
  173. else:
  174. current_app.logger.info(f'No new milestones passed')
  175. return jsonify(None)
  176. @ocb.route('/checkDonations') # Polled by donation.html template to check for new kofi donations
  177. def check_donations():
  178. global donations
  179. if donations:
  180. current_app.logger.info(f'\n\n{format(donations[0])}\n\n')
  181. last_donation = donations.pop(0)
  182. return jsonify(last_donation)
  183. else:
  184. current_app.logger.info(f'No new donations')
  185. return jsonify(None)
  186. @ocb.route('/checkSubscribers') # Polled by subscriber.html template to check for new kofi subscribers
  187. def check_subscribers():
  188. global subscribers
  189. if subscribers:
  190. current_app.logger.info(f'\n\n{format(subscribers[0])}\n\n')
  191. last_subscriber = subscribers.pop(0)
  192. return jsonify(last_subscriber)
  193. else:
  194. current_app.logger.info(f'No new subscribers')
  195. return jsonify(None)