Jelajahi Sumber

Fixed UnboundLocalError and NameError errors, added pluralization to rewards command, added next milestone chat message

deadtom 17 jam lalu
induk
melakukan
4201122cea
3 mengubah file dengan 45 tambahan dan 27 penghapusan
  1. 12 8
      ownchatbot/bot_messages.py
  2. 11 1
      ownchatbot/reward_handlers.py
  3. 22 18
      ownchatbot/webhooks.py

+ 12 - 8
ownchatbot/bot_messages.py

@@ -1,6 +1,6 @@
-from flask import current_app, url_for
+from flask import current_app
 from ownchatbot.db import get_db, is_cool
-from ownchatbot.owncast_com import send_chat, send_private_chat, send_system_chat
+from ownchatbot.owncast_com import send_chat, send_private_chat
 from ownchatbot.reward_handlers import run_script, add_to_queue, add_to_vote, add_to_goal, was_goal_reached, goal_reached, is_reward_active, check_vote, all_active_goals, goal_left, was_milestone_reached, save_alerts
 from ownchatbot.user_handlers import spend_points, get_users_points, refund_points, get_all_users_with_user_id
 import os
@@ -73,19 +73,23 @@ def do_reward(message, user_id):  # Parse the chat command
             send_private_chat(user_id, f'{username}, you can\'t contribute zero points.')
         elif add_to_goal(db, user_id, reward, int(contribution)):
             send_chat(f'{username} contributed {porps(contribution)} to the \"{prefix}{reward}\" goal.')
-            wmr = was_milestone_reached(db, reward)
             if was_goal_reached(db, reward):  # Was a goal reached?
                 alerts_dict['g_name'] = username
                 alerts_dict['g_reward'] = reward
                 save_alerts(alerts_dict)
                 send_chat(f'\"{prefix}{reward}\" target reached! 🎉')
-                send_system_chat(f'![Goal Reached]({url_for(web_panels.assets, asset_name=alerts_dict["GOAL_ALERT"])})')
             else:  # If goal wasn't reached, was a milestone passed?
-                if wmr:
+                check_milestones = was_milestone_reached(db, reward)
+                if check_milestones is not False:  # Testing it this way because non-false returns two values
+                    wmr, next_milestone = check_milestones
                     alerts_dict['m_name'] = username
                     alerts_dict['m_reward'] = wmr
                     save_alerts(alerts_dict)
                     send_chat(f'{wmr} milestone reached!')
+                    if next_milestone == 'Done':
+                        send_chat(f'Last milestone passed!')
+                    else:
+                        send_chat(f'Next milestone is \"{next_milestone}\"')
         else:
             send_private_chat(user_id, f'Couldn\'t contribute to the \"{prefix}{reward}\" goal for {username}, for some highly technical reason.')
         return
@@ -103,7 +107,7 @@ def do_reward(message, user_id):  # Parse the chat command
                 send_chat(f'{username} voted for \"{prefix}{reward}\" for {porps(price)}.')
             else:
                 send_private_chat(user_id, f'Couldn\'t vote for \"{prefix}{reward}\" for {username}, for some highly technical reason.')
-            
+
     elif reward_type == 'redeem':  # If it's a redeem, do the thing
         if is_cool(reward)[0]:  # Is there an active cool down?
             if (add_to_queue(db, user_id, reward) and
@@ -114,7 +118,7 @@ def do_reward(message, user_id):  # Parse the chat command
         else:
             hot_time = is_cool(reward)[1]
             send_chat(f'\"{prefix}{reward}\" has {mas(hot_time)} left to cool down.')
-            
+
     elif reward_type == 'special':  # If it's a special, do the thing
         if is_cool(reward)[0]:  # Is there an active cool down?
             script_cmd = current_app.config['REWARDS'][reward]['cmd']
@@ -128,7 +132,7 @@ def do_reward(message, user_id):  # Parse the chat command
         else:
             hot_time = is_cool(reward)[1]
             send_chat(f'\"{prefix}{reward}\" has {mas(hot_time)} left to cool down.')
-            
+
     else:  # If we can't find the reward, say so
         send_private_chat(user_id, f'\"{prefix}{reward}\", {username}? No such reward.')
 

+ 11 - 1
ownchatbot/reward_handlers.py

@@ -4,6 +4,7 @@ from sqlite3 import Error
 from ownchatbot.user_handlers import spend_points
 import subprocess
 import json
+from ownchatbot.owncast_com import send_chat
 
 
 def sort_key(item):  # Sort rewards by price
@@ -181,7 +182,16 @@ def was_milestone_reached(db, reward_name):  # Check if a milestone was reached
                     (new_milestones, reward_name)
                 )
                 db.commit()
-                return ms_reward
+                current_app.logger.info(f'new_milestone: {new_milestones}')  # TESTING
+                if new_milestones < 3:  # If there is another milestone
+                    next_milestone = new_milestones + 1  # Get the number of the next milestone
+                    next_milestone = f'milestone{next_milestone}'  # Set up the dict entry name
+                    if next_milestone:
+                        next_milestone = milestones_info[next_milestone][0]  # Get the name of the next milestone
+                else:
+                    next_milestone = "Done"
+                    current_app.logger.info(f'The next milestone is \"{next_milestone}\"')  # TESTING
+                return ms_reward, next_milestone
             else:
                 return False
         return False

+ 22 - 18
ownchatbot/webhooks.py

@@ -2,7 +2,7 @@ from flask import Flask, request, json, Blueprint, current_app, render_template,
 from ownchatbot.db import get_db, clear_fulfilled_rewards
 from ownchatbot.owncast_com import send_chat, send_private_chat
 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
-from ownchatbot.bot_messages import do_reward, help_message
+from ownchatbot.bot_messages import do_reward, help_message, porps
 from ownchatbot.reward_handlers import all_active_goals, all_active_votes, all_active_rewards, save_alerts
 from ownchatbot.kofi_handlers import accept_donation, accept_sub
 import json
@@ -65,7 +65,7 @@ def chat_hook():
             if points is None:
                 send_private_chat(user_id, f'{display_name}, couldn\'t get your points, for some highly technical reason.')
             else:
-                send_private_chat(user_id, f'{display_name}, you have {points} points.')
+                send_private_chat(user_id, f'{display_name}, you have {points} {porps(points)}.')
 
         elif lowercase_msg.startswith(f'{prefix}reg_mail'):  # Generate a code to verify users account for email registration
             if current_app.config['KOFI_INTEGRATION']:
@@ -87,9 +87,11 @@ def chat_hook():
                         if not (set(details['categories']) & set(current_app.config['ACTIVE_CAT'])):  # If there are no common categories, continue
                             continue
                     if 'type' in details and details['type'] == 'goal':
-                        rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} goal at {details["target"]} contributed points.'
+                        rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} goal at {details["target"]} contributed {porps(details["target"])}.'
+                    elif 'type' in details and details['type'] == 'vote':
+                        rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} vote for {details["price"]} {porps(details["price"])}.'
                     else:
-                        rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} for {details["price"]} points.'
+                        rewards_msg = f'{rewards_msg}<br>* {prefix}{reward} for {details["price"]} {porps(details["price"])}.'
                     if 'info' in details:
                         rewards_msg = f'{rewards_msg}<br>{details["info"]}'
                     else:
@@ -129,12 +131,11 @@ def kofi_hook():
                 if type == 'Donation':
                     donation_info = [is_public, from_name, email, amount, message]
                     donation_points = current_app.config['KOFI_SETTINGS']['donation_points']
-                    accept_donation(donation_info, donation_points)
-                    if is_public:
-                        alert_info = {'name': from_name, 'amount': amount}
-                    else:
-                        alert_info = {'name': 'Anonymous Hero', 'amount': amount}
-                    donations.append(alert_info)  # Append info to be displayed in alert
+                    if accept_donation(donation_info, donation_points):
+                        if is_public:
+                            alert_info = {'name': from_name, 'amount': amount}
+                        else:
+                            alert_info = {'name': 'Anonymous Hero', 'amount': amount}
                 if type == 'Subscription':
                     if current_app.config['KOFI_SETTINGS']['subs']:  # Check that subscriptions are enabled
                         if first_sub:
@@ -150,19 +151,22 @@ def kofi_hook():
 
                         sub_info = [is_public, from_name, email, amount, message, first_sub, tier_name]
                         sub_points = current_app.config['KOFI_SETTINGS']['sub_points']
-                        accept_sub(sub_info, sub_points)
-                        if is_public:
-                            alert_info = {'name': from_name, 'tiername': tier_name}
-                        else:
-                            alert_info = {'name': 'Anonymous Hero', 'teirname': tier_name}
-                        subscribers.append(alert_info)  # Append info to be displayed in alert
+                        if accept_sub(sub_info, sub_points):
+                            if is_public:
+                                alert_info = {'name': from_name, 'tiername': tier_name}
+                            else:
+                                alert_info = {'name': 'Anonymous Hero', 'teirname': tier_name}
                     else:
                         current_app.logger.info(f'Kofi membership received, but subscriptions are not enabled. Doing nothing.')
-
                 return jsonify({'status': 'success'}), 200
             else:
                 current_app.logger.info(f'Token invalid. Rejecting.')
                 return jsonify({'status': 'unauthorized'}), 401
+        else:
+            return jsonify({'status': 'Failed. No data'}), 400
+        return jsonify({'status': 'success'}), 200
+    else:
+        return jsonify({'status': 'Failed. Invalid content type'}), 400
 
 
 @ocb.route('/checkFollows')  # Polled by follower.html template to check for new followers
@@ -173,7 +177,7 @@ def check_follows():
         current_app.logger.info(f'New follower: \"{follower["name"]}\"')
         alerts_dict['follower'] = ''
         save_alerts(alerts_dict)
-        
+
         return jsonify(follower)
     else:
         current_app.logger.debug(f'No new followers')