reward_handlers.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import os
  2. from flask import current_app
  3. from sqlite3 import Error
  4. from ownchatbot.user_handlers import spend_points
  5. import subprocess
  6. import json
  7. from ownchatbot.owncast_com import send_chat
  8. def sort_key(item): # Sort rewards by price
  9. price = item[1].get('price')
  10. return (price is None, price)
  11. def check_vote(db, vote_name, user_id): # Check if user has already voted on this vote
  12. try:
  13. cursor = db.execute(
  14. "SELECT voters FROM votes WHERE name = ?",
  15. (vote_name,)
  16. )
  17. row = cursor.fetchone()
  18. if row is None:
  19. current_app.logger.error(f'\"{vote_name}\" not found in vote table.')
  20. return False
  21. if row[0] == user_id:
  22. return True
  23. except Error as cverror:
  24. current_app.logger.error(f'Couldn\'t check if {user_id} already voted on \"{vote_name}\": {cverror.args[0]}')
  25. def add_to_vote(db, vote_name, user_id): # Add a count to a vote
  26. try: # Check if vote exists in the database
  27. cursor = db.execute(
  28. "SELECT count FROM votes WHERE name = ?",
  29. (vote_name,)
  30. )
  31. vote = cursor.fetchone()
  32. if vote is None:
  33. current_app.logger.error(f'{vote_name} not found in vote table.')
  34. return False
  35. else: # If vote exists, add a count
  36. db.execute(
  37. "UPDATE votes SET count = count + 1, voters = ? WHERE name = ?",
  38. (user_id, vote_name,)
  39. )
  40. db.commit()
  41. return True
  42. except Error as terror:
  43. current_app.logger.error(f'Couldn\'t add to \"{vote_name}\" vote: {terror.args[0]}')
  44. return False
  45. def add_to_queue(db, user_id, reward_name): # Add a reward to the queue
  46. try:
  47. db.execute(
  48. "INSERT INTO reward_queue(reward, user_id, fulfilled, refunded) VALUES(?, ?, ?, ?)",
  49. (reward_name, user_id, 0, 0)
  50. )
  51. db.commit()
  52. return True
  53. except Error as qerror:
  54. current_app.logger.error(f'Couldn\'t add to reward \"{reward_name}\" for {user_id} queue: {qerror.args[0]}')
  55. return False
  56. def run_script(reward_name, script_cmd): # Run a script form a special reward
  57. try:
  58. script_cmd = f'{script_cmd} &'
  59. subprocess.check_call(script_cmd, shell=True)
  60. except Exception as scerror:
  61. current_app.logger.error(f'Couldn\'t run script \"{reward_name}\": {scerror.args[0]}')
  62. return False
  63. return True
  64. def add_to_goal(db, user_id, reward_name, points_contributed): # Add a contribution to a goal
  65. try:
  66. cursor = db.execute(
  67. "SELECT progress, target FROM goals WHERE name = ?",
  68. (reward_name,)
  69. )
  70. row = cursor.fetchone()
  71. if row is None:
  72. current_app.logger.error(f'\"{reward_name}\" not found in goal table.')
  73. return False
  74. progress, target = row
  75. if progress + points_contributed > target:
  76. points_contributed = target - progress
  77. if points_contributed < 0:
  78. points_contributed = 0
  79. if spend_points(db, user_id, points_contributed):
  80. cursor = db.execute(
  81. "UPDATE goals SET progress = ? WHERE name = ?",
  82. (progress + points_contributed, reward_name)
  83. )
  84. db.commit()
  85. return True
  86. except Error as gerror:
  87. current_app.logger.error(f'Couldn\'t update goal: {gerror.args[0]}')
  88. return False
  89. def goal_left(db, reward_name):
  90. try:
  91. cursor = db.execute(
  92. "SELECT progress, target FROM goals WHERE name = ?",
  93. (reward_name,)
  94. )
  95. row = cursor.fetchone()
  96. if row is None:
  97. current_app.logger.error(f'{reward_name} not found in Goal table.')
  98. else:
  99. progress, target = row
  100. left = target - progress
  101. return left
  102. except Error as glerror:
  103. current_app.logger.error(f'Couldn\'t check progress for \"{reward_name}\" goal: {glerror.args[0]}')
  104. def goal_reached(db, reward_name): # Set a goal as completed
  105. try:
  106. cursor = db.execute(
  107. "SELECT complete FROM goals WHERE name = ?",
  108. (reward_name,)
  109. )
  110. row = cursor.fetchone()
  111. if row is None:
  112. current_app.logger.error(f'{reward_name} not found in goal table.')
  113. else:
  114. return row[0]
  115. except Error as grerror:
  116. current_app.logger.error(f'Couldn\'t check if goal was met: {grerror.args[0]}')
  117. return False
  118. def was_milestone_reached(db, reward_name): # Check if a milestone was reached
  119. try:
  120. all_rewards = current_app.config['REWARDS'] # Get milestone numbers from REWARDS
  121. milestones_info = all_rewards[reward_name]['milestones']
  122. ms1_goal = ms2_goal = ms3_goal = float('inf') # To avoid referencing unassigned variables, in case there aren't any milestones set
  123. ms1_reward = ms2_reward = ms3_reward = None # Initialize to None
  124. if len(milestones_info['milestone1']) > 1 and milestones_info['milestone1'][1]: # Check that there is a value for the milestone
  125. ms1_goal = milestones_info['milestone1'][1]
  126. ms1_reward = f'🚩 \"{milestones_info["milestone1"][0]}\"'
  127. if len(milestones_info['milestone2']) > 1 and milestones_info['milestone2'][1]:
  128. ms2_goal = milestones_info['milestone2'][1]
  129. ms2_reward = f'🚩🚩 \"{milestones_info["milestone2"][0]}\"'
  130. if len(milestones_info['milestone3']) > 1 and milestones_info['milestone3'][1]:
  131. ms3_goal = milestones_info['milestone3'][1]
  132. ms3_reward = f'🚩🚩🚩 \"{milestones_info["milestone3"][0]}\"'
  133. cursor = db.execute(
  134. "SELECT progress, milestones FROM goals WHERE name = ?",
  135. (reward_name,)
  136. ) # Get progress and milestones info from database
  137. row = cursor.fetchone()
  138. if row is None:
  139. current_app.logger.error(f'{reward_name} not found in Goal table.')
  140. else:
  141. progress = int(row['progress'])
  142. milestones = int(row['milestones'])
  143. if progress >= ms1_goal and progress < ms2_goal:
  144. new_milestones = 1
  145. ms_reward = ms1_reward
  146. elif progress >= ms2_goal and progress < ms3_goal:
  147. new_milestones = 2
  148. ms_reward = ms2_reward
  149. elif progress >= ms3_goal:
  150. new_milestones = 3
  151. ms_reward = ms3_reward
  152. else:
  153. new_milestones = 0
  154. if new_milestones > milestones: # If we're passing a milestone, get the reward
  155. cursor = db.execute(
  156. "UPDATE goals SET milestones = ? WHERE name = ?",
  157. (new_milestones, reward_name)
  158. )
  159. db.commit()
  160. current_app.logger.info(f'new_milestone: {new_milestones}') # TESTING
  161. if new_milestones < 3: # If there is another milestone
  162. next_milestone = new_milestones + 1 # Get the number of the next milestone
  163. next_milestone = f'milestone{next_milestone}' # Set up the dict entry name
  164. if next_milestone:
  165. next_milestone = milestones_info[next_milestone][0] # Get the name of the next milestone
  166. else:
  167. next_milestone = "Done"
  168. current_app.logger.info(f'The next milestone is \"{next_milestone}\"') # TESTING
  169. return ms_reward, next_milestone
  170. else:
  171. return False
  172. return False
  173. except Error as wmrerror:
  174. current_app.logger.error(f'Couldn\'t check if a milestone was reached: {wmrerror.args[0]}')
  175. return False
  176. def was_goal_reached(db, reward_name): # Check if a goal was reached
  177. try:
  178. cursor = db.execute(
  179. "SELECT progress, target FROM goals WHERE name = ?",
  180. (reward_name,)
  181. )
  182. row = cursor.fetchone()
  183. if row is None:
  184. current_app.logger.error(f'{reward_name} not found in Goal table.')
  185. else:
  186. progress, target = row
  187. if progress == target:
  188. cursor = db.execute(
  189. "UPDATE goals SET complete = TRUE WHERE name = ?",
  190. (reward_name,)
  191. )
  192. db.commit()
  193. return True
  194. return False
  195. except Error as wgrerror:
  196. current_app.logger.error(f'Couldn\'t mark goal met: {wgrerror.args[0]}')
  197. return False
  198. def all_votes(db): # Get all the votes
  199. try:
  200. cursor = db.execute(
  201. "SELECT votes.name, votes.count, votes.info FROM votes"
  202. )
  203. return cursor.fetchall()
  204. except Error as aterror:
  205. current_app.logger.error(f'Couldn\'t select all votes: {aterror.args[0]}')
  206. def refund_reward(db, reward_id): # Refund a user for a particular reward
  207. reward_id = reward_id
  208. try:
  209. cursor = db.execute(
  210. "UPDATE reward_queue SET refunded = 1 WHERE id = ?",
  211. (reward_id,)
  212. )
  213. db.commit()
  214. current_app.logger.info(f'Set {reward_id} as refunded in the database')
  215. return True
  216. except Error as rferror:
  217. current_app.logger.error(f'Couldn\'t refund reward id {reward_id}: {rferror.args[0]}')
  218. return False
  219. def fulfill_reward(db, reward_id): # Mark a reward as fulfilled in the database
  220. reward_id = reward_id
  221. try:
  222. cursor = db.execute(
  223. "UPDATE reward_queue SET fulfilled = 1 WHERE id = ?",
  224. (reward_id,)
  225. )
  226. db.commit()
  227. current_app.logger.info(f'{reward_id} marked fulfilled.')
  228. return True
  229. except Error as frerror:
  230. current_app.logger.error(f'Couldn\'t fulfill reward id {reward_id}: {frerror.args[0]}')
  231. return False
  232. def all_active_votes(db): # Get only active votes
  233. votes = all_votes(db)
  234. all_active_votes = []
  235. try:
  236. for name, count, info in votes:
  237. if is_reward_active(name):
  238. all_active_votes.append((name, count, info))
  239. return all_active_votes
  240. except Exception as aaverror:
  241. current_app.logger.error(f'General exception: {aaverror}')
  242. def all_goals(db): # Get all the goals
  243. try:
  244. cursor = db.execute(
  245. "SELECT name, progress, target, info FROM goals"
  246. )
  247. return cursor.fetchall()
  248. except Exception as agerror:
  249. current_app.logger.error(f'Couldn\'t select all goals: {agerror.args[0]}')
  250. def all_active_goals(db): # Get only active goals
  251. goals = all_goals(db)
  252. all_active_goals = []
  253. try:
  254. for name, progress, target, info in goals:
  255. if is_reward_active(name):
  256. all_active_goals.append((name, progress, target, info))
  257. return all_active_goals
  258. except Exception as aagerror:
  259. current_app.logger.error(f'General exception: {aagerror}')
  260. def all_active_rewards(): # Get only active rewards
  261. rewards = current_app.config['REWARDS']
  262. all_active_rewards = {}
  263. for reward_name, reward_dict in rewards.items():
  264. if reward_dict.get('categories'): # If reward has empty categories list
  265. for category in reward_dict['categories']: # Compare each category to ACTIVE_CAT list
  266. if category in current_app.config['ACTIVE_CAT']:
  267. all_active_rewards[reward_name] = reward_dict
  268. break
  269. return all_active_rewards
  270. def all_active_redeems():
  271. rewards = current_app.config['REWARDS']
  272. just_redeems = []
  273. for reward_name, details in rewards.items():
  274. if details.get("type") not in ["goal", "vote"]:
  275. just_redeems.append(reward_name)
  276. return just_redeems
  277. def save_alerts(alerts_dict): # Write alerts to alerts.py
  278. alerts_dict = json.dumps(alerts_dict, indent=4)
  279. alerts_file = os.path.join(current_app.instance_path, 'alerts.py')
  280. new_alerts = f"ALERTS = {alerts_dict}"
  281. try:
  282. with open(alerts_file, 'w') as af:
  283. af.write(new_alerts)
  284. af.close
  285. current_app.logger.info('Saved new alerts.py.')
  286. except Exception as saerror:
  287. current_app.logger.error(f'Couldn\'t save alerts.py: {saerror.args[0]}')
  288. return False
  289. current_app.config.from_pyfile('alerts.py', silent=True) # Reread alerts.py into the app
  290. return True
  291. def del_alert_file(alert_file):
  292. filepath = os.path.join(current_app.config['ASSETS_FOLDER'], alert_file)
  293. try:
  294. os.remove(filepath)
  295. current_app.logger.info(f"Successfully removed \"{alert_file}\" from alerts folder.")
  296. return True
  297. except FileNotFoundError:
  298. current_app.logger.error(f"Couldn't delet \"{alert_file}\": File not found.")
  299. return False
  300. except PermissionError:
  301. current_app.logger.error(f"No permission to delete file: \"{alert_file}\"")
  302. return False
  303. except Exception as daferror:
  304. current_app.logger.error(f"An error occurred: {daferror}")
  305. return False
  306. def save_rewards(reward_info): # Write rewards to rewards.py
  307. sorted_rewards = dict(sorted(reward_info.items(), key=sort_key))
  308. new_rewards = json.dumps(sorted_rewards, indent=4)
  309. rewards_file = os.path.join(current_app.instance_path, 'rewards.py')
  310. try:
  311. with open(rewards_file, 'w') as rf:
  312. rf.write(f'REWARDS = {new_rewards}')
  313. rf.close()
  314. except Exception as srerror:
  315. current_app.logger.error(f'Couldn\'t save rewards.py: {srerror.args[0]}')
  316. return False
  317. return True
  318. def save_config(config_dict): # Write settings to config.py
  319. settings_file = os.path.join(current_app.instance_path, 'config.py')
  320. secret_key = current_app.config['SECRET_KEY']
  321. new_settings = f"# Owncast stuff. Needed to interact with your Owncast instance\n\
  322. ACCESS_ID = '{config_dict['ACCESS_ID']}'\n\
  323. ACCESS_TOKEN = '{config_dict['ACCESS_TOKEN']}'\n\
  324. OWNCAST_URL = '{config_dict['OWNCAST_URL']}'\n\
  325. \n\
  326. # OwnchatBot Configuration \n\
  327. SECRET_KEY = '{secret_key}' # Needed for internal Flask stuff. DO NOT DELETE.\n\
  328. POINTS_INTERVAL = {config_dict['POINTS_INTERVAL']} # How long, in seconds, between points awards\n\
  329. POINTS_AWARD = {config_dict['POINTS_AWARD']} # How many points awarded each interval?\n\
  330. GUNICORN = {config_dict['GUNICORN']} # Integrate OwnchatBot logging into Gunicorn\n\
  331. PREFIX = '{config_dict['PREFIX']}' # Preceeds commands, so OwnchatBot knows what is a command\n\
  332. KOFI_TOKEN = '{config_dict['KOFI_TOKEN']}' # Needed to validate Ko-fi with OCB webhook. Get from Ko-fi Settings -> More -> API -> Webhooks -> Advanced - Verification Token.\n\
  333. KOFI_INTEGRATION = {config_dict['KOFI_INTEGRATION']} # Integrate OwnchatBot with Ko-fi"
  334. try:
  335. with open(settings_file, 'w') as cf:
  336. cf.write(new_settings)
  337. cf.close
  338. except Exception as scerror:
  339. current_app.logger.error(f'Couldn\'t save config.py: {scerror.args[0]}')
  340. return False
  341. current_app.config.from_pyfile('config.py', silent=True) # Reread config.py into the app
  342. return True
  343. def reread_categories(): # Read _CAT varaibles and write to categories.py
  344. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  345. active_categories = current_app.config['ACTIVE_CAT']
  346. inactive_categories = current_app.config['INACTIVE_CAT']
  347. try:
  348. with open(categories_file, 'r', encoding='utf-8') as f: # Read categories.py, and set up lines to change
  349. category_data = f.readlines()
  350. category_data[0] = f'ACTIVE_CAT = {active_categories}\n'
  351. category_data[1] = f'INACTIVE_CAT = {inactive_categories}\n'
  352. f.close
  353. with open(categories_file, 'w', encoding='utf-8') as f: # Write changes to categories.py
  354. f.writelines(category_data)
  355. f.close
  356. current_app.config.from_pyfile('categories.py', silent=True) # Reread categories into the app
  357. except Error as rcerror:
  358. current_app.logger.error(f'Couldn\'t reread categories: {rcerror.args[0]}')
  359. def activate_category(category): # Move an item from the ACTIVE_CAT list to the INACTIVE_CAT list
  360. try:
  361. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  362. active_categories = current_app.config['ACTIVE_CAT']
  363. inactive_categories = current_app.config['INACTIVE_CAT']
  364. active_categories.append(category) # Add to ACTIVE_CAT
  365. inactive_categories.remove(category) # Remove from INACTIVE_CAT
  366. reread_categories()
  367. except Error as acerror:
  368. current_app.logger.error(f'Couldn\'t activate {category}: {acerror.args[0]}')
  369. def deactivate_category(category): # Move an item from the INACTIVE_CAT list to the ACTIVE_CAT list
  370. try:
  371. categories_file = os.path.join(current_app.instance_path, 'categories.py')
  372. active_categories = current_app.config['ACTIVE_CAT']
  373. inactive_categories = current_app.config['INACTIVE_CAT']
  374. active_categories.remove(category) # Remove from ACTIVE_CAT
  375. inactive_categories.append(category) # Add to INACTIVE_CAT
  376. reread_categories()
  377. except Error as dcerror:
  378. current_app.logger.error(f'Couldn\'t deactivate {category}: {dcerror.args[0]}')
  379. def get_queue(db): # Get the reward queue and the username
  380. try:
  381. cursor = db.execute(
  382. """SELECT reward_queue.id, reward_queue.created, reward_queue.reward, reward_queue.user_id, reward_queue.fulfilled, reward_queue.refunded, points.name
  383. FROM reward_queue
  384. INNER JOIN points
  385. on reward_queue.user_id = points.id"""
  386. )
  387. return cursor.fetchall()
  388. except Error as gqerror:
  389. current_app.logger.error(f'Couldn\'t get queue: {gqerror.args[0]}')
  390. def is_reward_active(reward_name): # Check if reward is active
  391. active_categories = current_app.config['ACTIVE_CAT']
  392. reward_dict = current_app.config['REWARDS'].get(reward_name, None)
  393. try:
  394. if reward_dict:
  395. if 'categories' in reward_dict: # Is there a categories key at all?
  396. for category in reward_dict['categories']: # Cycle through categories and compare to active_categories
  397. if category in active_categories:
  398. return True
  399. return False
  400. elif reward_dict['categories'] == []: # If categories key is there but empty, return False
  401. return False
  402. else:
  403. return True
  404. return None
  405. except Error as iraerror:
  406. current_app.logger.error(f'Couldn\'t check if {reward_name} is active: {iraerror.args[0]}')