Merge pull request #36 from phixxy/web_ui

Web UI
This commit is contained in:
phixxy 2024-06-19 21:03:43 -07:00 committed by GitHub
commit f7dc58808b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 166 additions and 3 deletions

15
.env_default Normal file
View file

@ -0,0 +1,15 @@
discord_token='token'
flask_port='5000'
imgflip_username='username'
imgflip_password='password'
openai.api_key='api_key'
upload_phixxy='False'
ftp_server='www.example.com'
ftp_username='username'
ftp_password='password'
ftp_public_html='/home/debian/www.example.com/'
stable_diffusion_ip='disabled'
stable_diffusion_port='7861'
stable_diffusion_user=
stable_diffusion_password=
eleven_labs='api-key'

View file

@ -0,0 +1,73 @@
<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sparkytron Config</title>
</head>
<style>
body {
background-color: #333;
color: #fff;
}
.container {
background-color: #444;
border-radius: 10px;
padding: 20px;
margin-top: 50px;
}
.form-control {
background-color: #555;
color: #fff;
}
.btn-primary {
background-color: #6c757d;
border-color: #6c757d;
}
.btn-primary:hover {
background-color: #495057;
border-color: #495057;
}
.alert-success {
background-color: #198754;
color: #fff;
border-color: #198754;
}
</style>
<body>
<div class="container">
<h1 class="mt-5">Warning!</h1>
<p class="lead">This information is stored in PLAIN TEXT in a .env file!</p>
<form method="post">
{% for key, value in key_value_pairs.items() %}
<div class="row mb-3">
<label for="{{ key }}" class="col-sm-2 col-form-label">{{ key }}</label>
<div class="col-sm-10">
<input type="text" id="{{ key }}" name="{{ key }}" value="{{ value }}" class="form-control">
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
{{ message }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
</form>
</div>
</body>
</html>

View file

@ -9,4 +9,6 @@ psutil
aiofiles
inky
wakeonlan
beautifulsoup4
beautifulsoup4
Flask[async]
waitress

26
sparkytron_webui.py Normal file
View file

@ -0,0 +1,26 @@
import asyncio
import discord
import os
import subprocess
import sys
from dotenv import load_dotenv
from src.bot import bot
from src.webui import flask_app
from waitress import serve
def get_flask_app(process):
flask_app.bot_process = process
flask_app.secret_key = "woaoaoahaowhawoiahoahhhhhh"
return flask_app
def main():
load_dotenv()
flask_port = os.getenv("flask_port")
if not flask_port:
flask_port = '5000'
process = subprocess.Popen([sys.executable, "sparkytron3000.py"])
flask_app = get_flask_app(process)
serve(flask_app, host='0.0.0.0', port=flask_port)
if __name__ == "__main__":
main()

View file

@ -10,7 +10,6 @@ intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
logger = src.logger.logger_setup()
async def load_cogs(bot: commands.Bot, cog_path: str) -> None:
for cog_file in os.listdir(cog_path):
if cog_file[-3:] == '.py':
@ -27,6 +26,7 @@ async def on_ready():
await utils.delete_all_files("tmp/")
await load_cogs(bot, 'cogs/')
logger.info('We have logged in as {0.user}'.format(bot))
print("If using the webui, visit http://localhost:5000 to change config!")
except:
logger.warning(f"Error in on_ready")
@ -43,4 +43,4 @@ async def on_message(ctx):
except discord.ext.commands.errors.CommandNotFound:
logger.info("Command not found.")
except Exception as e:
logger.warning(f"Error processing commands: {e}")
logger.warning(f"Error processing commands: {e}")

47
src/webui.py Normal file
View file

@ -0,0 +1,47 @@
import logging
import os
import subprocess
import sys
from flask import Flask, render_template, request, flash
logger = logging.getLogger("bot")
flask_app = Flask(__name__, template_folder='../flask_templates')
def read_env(filename):
if os.path.exists(filename):
with open(filename, 'r') as file:
key_value_pairs = {}
for line in file:
try:
key, value = line.strip().split('=')
key = key.strip()
value = value.strip()[1:-1]
key_value_pairs[key] = value
except:
print("This line isnt a kv pair")
return key_value_pairs
else:
return None
@flask_app.route('/', methods=['GET', 'POST'])
async def index():
key_value_pairs = read_env('.env')
if not key_value_pairs:
logger.warn("No .env file found! Copying defaults.")
key_value_pairs = read_env('.env_default')
form_dict = {}
if request.method == 'POST':
if key_value_pairs:
for form_name in key_value_pairs.keys():
form_dict[form_name] = request.form[form_name]
with open('.env', 'w') as file:
for key, value in form_dict.items():
file.write(f"{key}='{value}'\n")
print(form_dict)
flask_app.bot_process.terminate()
flask_app.bot_process = subprocess.Popen([sys.executable, "sparkytron3000.py"])
message = "Variables Updated!"
flash(message)
return render_template('index.html', key_value_pairs = key_value_pairs)