commit before utter laptop death

This commit is contained in:
WhatDidYouExpect 2025-07-23 16:58:21 +02:00
parent 4e111b410d
commit d6b51c787a
11 changed files with 163 additions and 221 deletions

View file

@ -1,80 +1,71 @@
import os
import platform
from typing import Callable, List
from dotenv import load_dotenv
import pathlib
import subprocess
from dotenv import load_dotenv
import discord
from discord import Colour, Embed, File, Interaction, Message
from discord.ext import commands
from discord import app_commands
from discord.abc import Messageable
env_path = pathlib.Path(__file__).parent.parent / '.env'
def get_git_branch():
try:
branch = (
subprocess.check_output(
["git", "rev-parse", "--abbrev-ref", "HEAD"], stderr=subprocess.DEVNULL
)
.decode("utf-8")
.strip()
)
return branch
except subprocess.CalledProcessError:
return None
env_path = pathlib.Path(__file__).parent.parent / ".env"
load_dotenv(dotenv_path=env_path)
# ANSI colors
available_cogs: Callable[[], List[str]] = lambda: [
file[:-3] for file in os.listdir("assets/cogs") if file.endswith(".py")
]
ANSI = "\033["
RED = f"{ANSI}31m"
GREEN = f"{ANSI}32m"
YELLOW = f"{ANSI}33m"
PURPLE = f"{ANSI}35m"
DEBUG = f"{ANSI}1;30m"
DEBUG = f"{ANSI}90m"
RESET = f"{ANSI}0m"
VERSION_URL = "https://raw.githubusercontent.com/gooberinc/version/main"
UPDATE_URL = f"{VERSION_URL}/latest_version.json"
UPDATE_URL = VERSION_URL + "/latest_version.json"
print(UPDATE_URL)
LOCAL_VERSION_FILE = "current_version.txt"
MEMORY_FILE = "memory.json"
MEMORY_LOADED_FILE = "MEMORY_LOADED" # used in markov module
local_version = "3.0.0"
latest_version = "0.0.0"
os.environ['gooberlocal_version'] = local_version
def get_git_branch() -> str | None:
try:
return subprocess.check_output(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
stderr=subprocess.DEVNULL
).decode().strip()
except subprocess.CalledProcessError:
return None
# TOKEN = os.getenv("DISCORDBOTTOKEN", "0")
# PREFIX = os.getenv("BOTPREFIX", "g.")
# PING_LINE = os.getenv("PINGLINE")
# CHECKS_DISABLED = os.getenv("CHECKSDISABLED")
# LOCALE = os.getenv("LOCALE", "en")
# BLACKLISTED_USERS = os.getenv("BLACKLISTEDUSERS", "").split(",")
# USERTRAIN_ENABLED = os.getenv("USERTRAINENABLED", "true").lower() == "true"
# NAME = os.getenv("NAME")
# MEMORY_FILE = "memory.json"
# MEMORY_LOADED_FILE = "MEMORY_LOADED" # is this still even used?? okay just checked its used in the markov module
# ALIVEPING = os.getenv("ALIVEPING")
# AUTOUPDATE = os.getenv("AUTOUPDATE")
# REACT = os.getenv("REACT")
branch = get_git_branch()
beta = branch != "main" if branch else True
# gooberTOKEN = os.getenv("GOOBERTOKEN")
# splashtext = os.getenv("SPLASHTEXT")
# ownerid = int(os.getenv("OWNERID", "0"))
# showmemenabled = os.getenv("SHOWMEMENABLED")
TOKEN = os.getenv("DISCORDBOTTOKEN", "0")
PREFIX = os.getenv("BOTPREFIX", "g.")
PING_LINE = os.getenv("PINGLINE")
CHECKS_DISABLED = os.getenv("CHECKSDISABLED")
LOCALE = os.getenv("LOCALE", "en")
gooberTOKEN = os.getenv("GOOBERTOKEN")
splashtext = os.getenv("SPLASHTEXT")
ownerid = int(os.getenv("OWNERID", "0"))
status = os.getenv("STATUS")
showmemenabled = os.getenv("SHOWMEMENABLED")
BLACKLISTED_USERS = os.getenv("BLACKLISTEDUSERS", "").split(",")
USERTRAIN_ENABLED = os.getenv("USERTRAINENABLED", "true").lower() == "true"
NAME = os.getenv("NAME")
ALIVEPING = os.getenv("ALIVEPING")
AUTOUPDATE = os.getenv("AUTOUPDATE")
song = os.getenv("SONG")
REACT = os.getenv("REACT")
intents = discord.Intents.default()
intents.messages = True
intents.presences = True
intents.members = True
intents.message_content = True
bot = commands.Bot(
command_prefix=PREFIX,
intents=intents,
allowed_mentions=discord.AllowedMentions(
everyone=False, roles=False, users=False, replied_user=True
)
)
# IGNOREWARNING = False # is this either??? i don't think so?
# song = os.getenv("song")
arch = platform.machine()
slash_commands_enabled = True # 100% broken, its a newer enough version so its probably enabled by default.... fix this at somepoint or hard code it in goober central code
launched = False
latest_version = "0.0.0"
local_version = "3.0.0"
os.environ["gooberlocal_version"] = local_version
beta = get_git_branch() == "dev"

View file

@ -3,55 +3,75 @@ import json
import markovify
import pickle
from modules.globalvars import *
from modules.volta.main import _
import logging
from modules.volta.main import _
from modules.settings import instance as settings_manager
settings = settings_manager.settings
logger = logging.getLogger("goober")
def get_file_info(file_path: str) -> dict:
# Get file size and line count for a given file path
def get_file_info(file_path):
try:
file_size = os.path.getsize(file_path)
with open(file_path, "r") as f:
lines = f.readlines()
return {
"file_size_bytes": file_size,
"line_count": len(lines)
}
return {"file_size_bytes": file_size, "line_count": len(lines)}
except Exception as e:
return {"error": str(e)}
def load_memory() -> list:
try:
with open(MEMORY_FILE, "r") as f:
return json.load(f)
except FileNotFoundError:
return []
def save_memory(memory: list) -> None:
with open(MEMORY_FILE, "w") as f:
# Load memory data from file, or use default dataset if not loaded yet
def load_memory():
data = []
# Try to load data from MEMORY_FILE
try:
with open(settings["bot"]["active_memory"], "r") as f:
data = json.load(f)
except FileNotFoundError:
pass
return data
# Save memory data to MEMORY_FILE
def save_memory(memory):
with open(settings["bot"]["active_memory"], "w") as f:
json.dump(memory, f, indent=4)
def train_markov_model(memory: list, additional_data: list = None):
lines = [line for line in (memory or []) if isinstance(line, str)]
if additional_data:
lines.extend(line for line in additional_data if isinstance(line, str))
if not lines:
def train_markov_model(memory, additional_data=None) -> markovify.NewlineText | None:
if not memory:
return None
text = "\n".join(lines)
return markovify.NewlineText(text, state_size=2)
filtered_memory = [line for line in memory if isinstance(line, str)]
if additional_data:
filtered_memory.extend(
line for line in additional_data if isinstance(line, str)
)
def save_markov_model(model, filename: str = 'markov_model.pkl') -> None:
with open(filename, 'wb') as f:
if not filtered_memory:
return None
text = "\n".join(filtered_memory)
model = markovify.NewlineText(text, state_size=2)
return model
def save_markov_model(model, filename="markov_model.pkl"):
with open(filename, "wb") as f:
pickle.dump(model, f)
logger.info(f"Markov model saved to {filename}.")
def load_markov_model(filename: str = 'markov_model.pkl'):
def load_markov_model(filename="markov_model.pkl"):
try:
with open(filename, 'rb') as f:
with open(filename, "rb") as f:
model = pickle.load(f)
logger.info(f"{_('model_loaded')} {filename}.{RESET}")
return model
except FileNotFoundError:
logger.error(f"{filename} {_('not_found')}{RESET}")
return None
return None

View file

@ -19,11 +19,11 @@ class PermissionError(Exception):
def requires_admin():
async def wrapper(ctx: discord.ext.commands.Context):
print(ctx.author.id)
if ctx.author.id not in settings["bot"]["owner_ids"]:
await ctx.send(
"You don't have the necessary permissions to run this command!"
)
return False
await ctx.send("You don't have the necessary permissions to run this command!")
return
command = ctx.command
if not command:

View file

@ -1,4 +1,5 @@
from modules.globalvars import *
from modules.settings import Settings as SettingsManager
from modules.volta.main import _, check_missing_translations
import time
import os
@ -14,6 +15,13 @@ import logging
logger = logging.getLogger("goober")
settings_manager = SettingsManager()
settings = settings_manager.settings
MEMORY_FILE = settings["bot"]["active_memory"]
with open(settings["splash_text_loc"], "r", encoding="UTF-8") as f:
splash_text = "".join(f.readlines())
# import shutil
psutilavaliable = True
try:
@ -210,8 +218,8 @@ def presskey2skip(timeout):
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
beta = beta
def start_checks():
if CHECKS_DISABLED == "True":
logger.warning(f"{(_('checks_disabled'))}")
if settings["disable_checks"]:
logger.warning(f"{_('checks_disabled')}")
return
logger.info(_('running_prestart_checks'))
check_for_model()
@ -233,5 +241,4 @@ def start_checks():
pass
logger.info(_('continuing_in_seconds').format(seconds=5))
presskey2skip(timeout=5)
os.system('cls' if os.name == 'nt' else 'clear')
print(splashtext)
os.system('cls' if os.name == 'nt' else 'clear')

View file

@ -1,6 +1,6 @@
import sys
import traceback
from modules.globalvars import RED, RESET, splashtext
from modules.globalvars import RED, RESET
from modules.volta.main import _
def handle_exception(exc_type, exc_value, exc_traceback, *, context=None):