Prechádzať zdrojové kódy

Filled in README.md. Edited TODO.md as things were completed. Changed how config.py is imported in hooks.py, and how variables from config.py are called. Edited config.py accordingly. Comments all around.

DeadTOm 1 týždeň pred
rodič
commit
5797d06d76
4 zmenil súbory, kde vykonal 42 pridanie a 63 odobranie
  1. 15 2
      README.md
  2. 1 2
      TODO.md
  3. 7 10
      config.py
  4. 19 49
      hooks.py

+ 15 - 2
README.md

@@ -1,3 +1,16 @@
-# OwncastWebHooks
+## DeadTOm's Owncast webhooks
 
-My Owncast webhooks, running on Flask.
+### Features so far
+* Sends chat messages to an XMPP account
+
+### Starting the Flask app
+Start from the folder where the app lives.
+My preferred method is gunicorn, with the following command:
+
+``` gunicorn -b 0.0.0.0:8057 -w 1 'hooks:app'
+```
+
+Or if running from a virtual environment, which you should be, use this command (change path as needed):
+
+``` .venv/bin/python -m gunicorn -b 0.0.0.0:8057 -w 1 'hooks:app'
+```

+ 1 - 2
TODO.md

@@ -1,2 +1 @@
-1. Properly import config.py into hooks.py (just "import config").
-2. Change all config variables in hooks.py to "config.variable".
+* Think of more stuff to add in here

+ 7 - 10
config.py

@@ -1,11 +1,8 @@
-# Example tag dictionary. Edit as needed
-tag_dict = {'python': '#Python', 'minecraft': '#Minecraft'}
+owncast_url = 'https://owncast.deadtom.me'
+api_url = 'http://localhost:8083'
+owncast_logfile = '/home/deadtom/logs/owncasthooks.log'
+hooks_path = '~/owncasthooks'  # Where does this file live?
 
-owncast_url = ''
-api_url = ''
-owncast_logfile = ''
-hooks_path = ''
-
-jid = ''  # XMPP sending acount username
-password = ''  # XMPP sending account password
-to = ''  # XMPP acount to send to
+jid = 'owncast@deadtom.me'  # XMPP sending acount username
+password = 'OxSfA3eXW0fqR7hpwvtT'  # XMPP sending account password
+to = 'deadtom@deadtom.me'  # XMPP acount to send to

+ 19 - 49
hooks.py

@@ -1,80 +1,50 @@
-try:
-    from config import *
-    from flask import Flask, jsonify, current_app, request
-    import requests
-    import logging
-    import time
-    import socket
-    import slixmpp
-    import sys
-except Exception as import_error:  # Log any errors loading modules, and try to keep running
-    fail_log = open(owncast_logfile, 'a')
-    fail_log.write(f'------{import_error}------\n')
-    fail_log.close()
-
-logging.basicConfig(filename=owncast_logfile, level=logging.INFO)
-
-testing = 0  # Are we testing? 1 for testing. 0 for live.
+from flask import Flask, jsonify, current_app, request
+import config
+import requests
+import logging
+import time
+import socket
+import slixmpp
+import sys
+
+logging.basicConfig(filename=config.owncast_logfile, level=logging.INFO)
 
 app = Flask(__name__)
 
 
-def get_now():  # This creates and returns a time stamp
+def get_now():  # Create a timestamp for logging
     now = str(time.strftime("%Y/%m/%d %H:%M:%S"))
     return now
 
-
-logging.info(f'\n\n\n\n{get_now()} - Webhook called.\n')
-
-
 class SendMsgBot(slixmpp.ClientXMPP):
     def __init__(self, jid, password, recipient, message):
-        slixmpp.ClientXMPP.__init__(self, jid, password)
-
+        slixmpp.ClientXMPP.__init__(self, config.jid, config.password)
         self.recipient = recipient
         self.msg = message
-
         self.add_event_handler("session_start", self.start)
 
     async def start(self, event):
         self.send_presence()
         await self.get_roster()
-
         self.send_message(mto=self.recipient, mbody=self.msg, mtype='chat')
-
         self.disconnect()
 
 
-def xmpp_chat(ownchat_msg):
-    xmpp = SendMsgBot(jid, password, to, ownchat_msg)
+def xmpp_chat(ownchat_msg):  # Send messages to XMPP
+    xmpp = SendMsgBot(config.jid, config.password, config.to, ownchat_msg)
     xmpp.register_plugin('xep_0030')  # Service Discovery
     xmpp.register_plugin('xep_0199')  # XMPP Ping
     xmpp.connect()
     xmpp.process(forever=False)
 
 
-def set_hashtags(title):  # Sets up hash tags to be appended to social media
-    logging.info(f'{get_now()} - Examining stream title \"{title}\" to apply hashtags.')
-    check_title = title.lower()
-    default_tags = '#Owncast '
-    tags = ''
-    # tag_dict located in config.py
-    for tag in tag_dict.keys():  # Iterate through each dict entry, and check for hashtag triggers
-        if tag in check_title:
-            print(f'Found {tag}, adding {tag_dict[tag]} to hashtags.')
-            tags = f'{tags}{tag_dict[tag]} '
-    tags = f'{tags}#Owncast'
-    logging.info(f'{get_now()} - Adding {tags} to title.')
-    return tags
-
-
-@app.route('/user_left/', methods=["POST"])
+@app.route('/user_left/', methods=["POST"])  # Notify XMPP that a user left
 def left():
     logging.info(f'{get_now()} - user_left request')
     raw_data = request.get_json(force=True)  # Get the raw data
     event_data = raw_data['eventData']
     logging.info(f'{get_now()} - {raw_data}')
-    response = requests.get(f'{api_url}/api/status')
+    response = requests.get(f'{config.api_url}/api/status')
     response = response.json()
     if response['online'] is True:  # Check if we are currently streaming, if so, send notification
         chatter_name = event_data['user']['displayName']
@@ -86,7 +56,7 @@ def left():
     return jsonify({"Data": raw_data, })
 
 
-@app.route('/user_joined/', methods=["POST"])
+@app.route('/user_joined/', methods=["POST"])  # Notify XMPP that a user joined
 def joined():
     logging.info(f'{get_now()} - user_joined request')
     raw_data = request.get_json(force=True)  # Get the raw data
@@ -99,7 +69,7 @@ def joined():
     return jsonify({"Data": raw_data, })
 
 
-@app.route('/name_changed/', methods=["POST"])
+@app.route('/name_changed/', methods=["POST"])  # Notify XMPP that a user changed their name
 def changed():
     logging.info(f'{get_now()} - name_changed request')
     raw_data = request.get_json(force=True)  # Get the raw data
@@ -115,7 +85,7 @@ def changed():
     return jsonify({"Data": raw_data, })
 
 
-@app.route('/message_sent/', methods=["POST"])
+@app.route('/message_sent/', methods=["POST"])  # Notify XMPP that a user sent a message
 def sent():
     logging.info(f'----------------------------------------------------------------------------')
     logging.info(f'{get_now()} - message_sent request')