webhooks.py 11 KB

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