Procházet zdrojové kódy

Set some messages to be sent only to the user, instead of chat

deadtom před 3 týdny
rodič
revize
efdc906546
3 změnil soubory, kde provedl 57 přidání a 22 odebrání
  1. 17 17
      ownchatbot/bot_messages.py
  2. 35 0
      ownchatbot/owncast_com.py
  3. 5 5
      ownchatbot/webhooks.py

+ 17 - 17
ownchatbot/bot_messages.py

@@ -1,6 +1,6 @@
 from flask import current_app
 from ownchatbot.db import get_db, is_cool
-from ownchatbot.owncast_com import send_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
 from ownchatbot.user_handlers import spend_points, get_users_points, refund_points, get_all_users_with_user_id
 import os
@@ -56,20 +56,20 @@ def do_reward(message, user_id):  # Parse the chat command
 
     if reward_type == 'goal':  # If it's a goal contribution, do the thing
         if not contribution:
-            send_chat(f'{username}, you didn\'t tell me how many points you want to contribute.')
+            send_private_chat(user_id, f'{username}, you didn\'t tell me how many points you want to contribute.')
             return
         if goal_reached(db, reward):
-            send_chat(f'{username}, we already completed this goal.')
+            send_private_chat(user_id, f'{username}, we already completed this goal.')
             return
         if int(contribution) > goal_left(db, reward):  # If they're contributing more than they need to
             current_app.logger.info(f'{username} contributed more than what was needed to reach the target.')
             contribution = goal_left(db, reward)  # only spend what is needed to reach the goal.
         if int(contribution) > points:
-            send_chat(f'{username}, you don\'t have that many points.')
+            send_private_chat(user_id, f'{username}, you don\'t have that many points.')
         elif int(contribution) < 0:
-            send_chat(f'{username}, you can\'t contribute negative points.')
+            send_private_chat(user_id, f'{username}, you can\'t contribute negative points.')
         elif int(contribution) == 0:
-            send_chat(f'{username}, you can\'t contribute zero points.')
+            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)
@@ -78,22 +78,22 @@ def do_reward(message, user_id):  # Parse the chat command
             if was_goal_reached(db, reward):
                 send_chat(f'\"{prefix}{reward}\" target reached! 🎉')
         else:
-            send_chat(f'Couldn\'t contribute to the \"{prefix}{reward}\" goal for {username}, for some highly technical reason.')
+            send_private_chat(user_id, f'Couldn\'t contribute to the \"{prefix}{reward}\" goal for {username}, for some highly technical reason.')
         return
 
     price = current_app.config['REWARDS'][reward]['price']  # Do they have enough points?
     if not points or points < price:
-        send_chat(f'{username}, you don\'t have enough points for \"{prefix}{reward}\".')
+        send_private_chat(user_id, f'{username}, you don\'t have enough points for \"{prefix}{reward}\".')
         return
 
     if reward_type == 'vote':  # If it's a vote, do the thing
         if check_vote(db, reward, user_id):  # See if viewer already voted
-            send_chat(f'{username}, you already voted for \"{prefix}{reward}\".')
+            send_private_chat(user_id, f'{username}, you already voted for \"{prefix}{reward}\".')
         else:
             if add_to_vote(db, reward, user_id) and spend_points(db, user_id, price):
                 send_chat(f'{username} voted for \"{prefix}{reward}\" for {porps(price)}.')
             else:
-                send_chat(f'Couldn\'t vote for \"{prefix}{reward}\" for {username}, for some highly technical reason.')
+                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?
@@ -101,10 +101,10 @@ def do_reward(message, user_id):  # Parse the chat command
                     spend_points(db, user_id, price)):
                 send_chat(f'{username} redeemed \"{prefix}{reward}\" for {porps(price)}.')
             else:
-                send_chat(f'Couldn\'t redeem \"{prefix}{reward}\"for {username}, for some highly technical reason.')
+                send_private_chat(user_id, f'Couldn\'t redeem \"{prefix}{reward}\"for {username}, for some highly technical reason.')
         else:
             hot_time = is_cool(reward)[1]
-            send_chat(f'Couldn\'t redeem \"{prefix}{reward}\"for {username}.<br>That reward has {mas(hot_time)} left to cool down.')
+            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?
@@ -115,16 +115,16 @@ def do_reward(message, user_id):  # Parse the chat command
                 send_chat(f'{username} redeemed \'{prefix}{reward}\' for {porps(price)}.')
             else:
                 if refund_points(db, user_id, price):
-                    send_chat(f'Couldn\'t redeem \"{prefix}{reward}\"for {username}, for some highly technical reason.')
+                    send_private_chat(user_id, f'Couldn\'t redeem \"{prefix}{reward}\"for {username}, for some highly technical reason.')
         else:
             hot_time = is_cool(reward)[1]
-            send_chat(f'Couldn\'t redeem \"{prefix}{reward}\"for {username}.<br>That reward has {mas(hot_time)} left to cool down.')       
+            send_chat(f'\"{prefix}{reward}\" has {mas(hot_time)} left to cool down.')
             
     else:  # If we can't find the reward, say so
-        send_chat(f'\"{prefix}{reward}\", {username}? No such reward.')
+        send_private_chat(user_id, f'\"{prefix}{reward}\", {username}? No such reward.')
 
 
-def help_message():
+def help_message(user_id):
     prefix = current_app.config['PREFIX']
     kofi_settings = current_app.config['KOFI_SETTINGS']
     kofi_integration = current_app.config['KOFI_INTEGRATION']
@@ -138,7 +138,7 @@ def help_message():
         message = f'{message}<br>\
         Kofi is enabled! Once you\'ve authenticated with Owncast, you\'ll recieve\
         {kofi_settings["tip_points"]} points for every dollar you tip on Kofi.'
-    send_chat(message)
+    send_private_chat(user_id, message)
 
 
 def save_announce(announce_dict):  # Write rewards to announce.py

+ 35 - 0
ownchatbot/owncast_com.py

@@ -1,6 +1,23 @@
 from flask import current_app
 import requests
 from ownchatbot.user_handlers import award_chat_points
+import random
+
+
+def get_client_id(user_id):
+    owncast_url = current_app.config['OWNCAST_URL']
+    access_token = current_app.config['ACCESS_TOKEN']
+    url = f'{owncast_url}/api/integrations/moderation/chat/user/{user_id}'
+    auth_bearer = f'Bearer {access_token}'
+    headers = {'Authorization': auth_bearer}
+    try:
+        response = requests.get(url, headers=headers)
+        response = response.json()
+        client_id = response['connectedClients'][0]['id']
+    except requests.exceptions.RequestException as gcierror:
+        current_app.logger.error(f'Couldn\'t get client id from Owncast: {gcierror.args[0]}')
+    current_app.logger.debug(f'Got client id {client_id}')
+    return client_id
 
 
 def live_now():  # Check if stream is live
@@ -51,3 +68,21 @@ def send_chat(message):  # Send message to owncast chat
         current_app.logger.error(f'Couldn\'t send {message} to Owncast: {response.status_code}.')
         return
     return response.json()
+
+
+def send_private_chat(user_id, message):  # Check to see who is connected
+    client_id = get_client_id(user_id)
+    owncast_url = current_app.config['OWNCAST_URL']
+    access_token = current_app.config['ACCESS_TOKEN']
+    url = f'{owncast_url}/api/integrations/chat/system/client/{client_id}'
+    auth_bearer = f'Bearer {access_token}'
+    headers = {'Authorization': auth_bearer}
+    try:
+        response = requests.post(url, headers=headers, json={'body': message})
+    except requests.exceptions.RequestException as swerror:
+        current_app.logger.error(f'Couldn\'t send {message} to Owncast: {swerror.args[0]}')
+        sys.exit()
+    if response.status_code != 200:
+        current_app.logger.error(f'Couldn\'t send {message} to Owncast: {response.status_code}.')
+        sys.exit()
+    response = response.json()

+ 5 - 5
ownchatbot/webhooks.py

@@ -1,6 +1,6 @@
 from flask import Flask, request, json, Blueprint, current_app, render_template, jsonify, request
 from ownchatbot.db import get_db
-from ownchatbot.owncast_com import send_chat
+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
 from ownchatbot.bot_messages import do_reward, help_message
 from ownchatbot.reward_handlers import all_active_goals, all_active_votes, all_active_rewards
@@ -93,14 +93,14 @@ def chat_hook():
         
         lowercase_msg = data['eventData']['rawBody'].lower()  # Convert body to lower case to match reward case
         if lowercase_msg.startswith(f'{prefix}help'):  # Send the help message
-            help_message()
+            help_message(user_id)
             
         elif lowercase_msg.startswith(f'{prefix}points'):  # Get the viewer's current points
             points = get_users_points(db, user_id)
             if points is None:
-                send_chat('Couldn\'t get your points, for some highly technical reason.')
+                send_private_chat(user_id, f'{display_name}, couldn\'t get your points, for some highly technical reason.')
             else:
-                send_chat(f'{display_name}, you have {points} points.')
+                send_private_chat(user_id, f'{display_name}, you have {points} points.')
                 
         elif lowercase_msg.startswith(f'{prefix}rewards'):  # Send rewards list
             if current_app.config['REWARDS']:
@@ -119,7 +119,7 @@ def chat_hook():
                         rewards_msg = f'{rewards_msg}'
             else:
                 rewards_msg = 'There are currently no active rewards.'
-            send_chat(rewards_msg)
+            send_private_chat(user_id, rewards_msg)
                     
         elif lowercase_msg.startswith(f'{prefix}'):  # Send to handle rewards
             do_reward(lowercase_msg, user_id)