turns out volta was compatible with old versions of goober lul

This commit is contained in:
WhatDidYouExpect 2025-07-18 01:50:58 +02:00
parent 3621a65481
commit 21b5107dd6
5 changed files with 229 additions and 144 deletions

6
.gitignore vendored
View file

@ -5,4 +5,8 @@ MEMORY_LOADED
memory.json
*.pkl
memories/
models/
models/
log.txt
translationcompleteness.py
translation_report.txt
output.png

132
bot.py
View file

@ -20,6 +20,7 @@ from better_profanity import profanity
from config import *
import traceback
import shutil
from volta import *
from nltk.sentiment.vader import SentimentIntensityAnalyzer
analyzer = SentimentIntensityAnalyzer()
@ -66,63 +67,6 @@ def load_translations():
translations = load_translations()
def get_translation(lang: str, key: str):
lang_translations = translations.get(lang, translations["en"])
if key not in lang_translations:
print(f"{RED}Missing key: {key} in language {lang}{RESET}")
return lang_translations.get(key, key)
def is_name_available(NAME):
if os.getenv("gooberTOKEN"):
return
try:
response = requests.post(f"{VERSION_URL}/check-if-available", json={"name": NAME}, headers={"Content-Type": "application/json"})
if response.status_code == 200:
data = response.json()
return data.get("available", False)
else:
print(f"{get_translation(LOCALE, 'name_check')}", response.json())
return False
except Exception as e:
print(f"{get_translation(LOCALE, 'name_check2')}", e)
return False
def register_name(NAME):
try:
if ALIVEPING == False:
return
# check if the name is avaliable
if not is_name_available(NAME):
if os.getenv("gooberTOKEN"):
return
print(f"{RED}{get_translation(LOCALE, 'name_taken')}{RESET}")
quit()
# if it is register it
response = requests.post(f"{VERSION_URL}/register", json={"name": NAME}, headers={"Content-Type": "application/json"})
if response.status_code == 200:
data = response.json()
token = data.get("token")
if not os.getenv("gooberTOKEN"):
print(f"{GREEN}{get_translation(LOCALE, 'add_token').format(token=token)} gooberTOKEN=<token>.{RESET}")
quit()
else:
print(f"{GREEN}{RESET}")
return token
else:
print(f"{RED}{get_translation(LOCALE, 'token_exists').format()}{RESET}", response.json())
return None
except Exception as e:
print(f"{RED}{get_translation(LOCALE, 'registration_error').format()}{RESET}", e)
return None
register_name(NAME)
def save_markov_model(model, filename='markov_model.pkl'):
model_file = f"models/{filename}"
@ -180,42 +124,7 @@ os.environ['gooberlocal_version'] = local_version
def check_for_update():
if ALIVEPING == "false":
return
global latest_version, local_version
latest_version_info = get_latest_version_info()
if not latest_version_info:
print(f"{get_translation(LOCALE, 'fetch_update_fail')}")
return None, None
latest_version = latest_version_info.get("version")
os.environ['gooberlatest_version'] = latest_version
download_url = latest_version_info.get("download_url")
if not latest_version or not download_url:
print(f"{RED}{get_translation(LOCALE, 'invalid_server')}{RESET}")
return None, None
if local_version == "0.0.0" or None:
print(f"{RED}I cant find the local_version variable! Or its been tampered with and its not an interger!{RESET}")
return
generate_sha256_of_current_file()
gooberhash = latest_version_info.get("hash")
if local_version < latest_version:
print(f"{YELLOW}{get_translation(LOCALE, 'new_version').format(latest_version=latest_version, local_version=local_version)}{RESET}")
print(f"{YELLOW}{get_translation(LOCALE, 'changelog').format(VERSION_URL=VERSION_URL)}{RESET}")
if local_version == latest_version:
print(f"{GREEN}{get_translation(LOCALE, 'latest_version')} {local_version}{RESET}")
print(f"{get_translation(LOCALE, 'latest_version2').format(VERSION_URL=VERSION_URL)}\n\n")
if gooberhash != currenthash:
print(f"{YELLOW}{get_translation(LOCALE, 'modification_warning')}")
print(f"{YELLOW}{get_translation(LOCALE, 'reported_version')} {local_version}{RESET}")
print(f"{DEBUG}{get_translation(LOCALE, 'current_hash')} {currenthash}{RESET}")
check_for_update()
return
def get_file_info(file_path):
try:
@ -317,7 +226,6 @@ async def on_ready():
synced = await bot.tree.sync()
print(f"{GREEN}{get_translation(LOCALE, 'synced_commands')} {len(synced)} {get_translation(LOCALE, 'synced_commands2')} {RESET}")
slash_commands_enabled = True
ping_server()
print(f"{GREEN}{get_translation(LOCALE, 'started').format()}{RESET}")
except Exception as e:
print(f"{RED}{get_translation(LOCALE, 'fail_commands_sync')} {e}{RESET}")
@ -327,33 +235,7 @@ async def on_ready():
return
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{song}"))
def ping_server():
if ALIVEPING == "false":
print(f"{YELLOW}{get_translation(LOCALE, 'pinging_disabled')}{RESET}")
os.environ['gooberauthenticated'] = 'No'
return
file_info = get_file_info(MEMORY_FILE)
payload = {
"name": NAME,
"memory_file_info": file_info,
"version": local_version,
"slash_commands": slash_commands_enabled,
"token": gooberTOKEN
}
try:
response = requests.post(VERSION_URL+"/ping", json=payload)
if response.status_code == 200:
print(f"{GREEN}{get_translation(LOCALE, 'goober_ping_success').format(NAME=NAME)}{RESET}")
os.environ['gooberauthenticated'] = 'Yes'
else:
print(f"{RED}{get_translation(LOCALE, 'goober_ping_fail')} {response.status_code}{RESET}")
os.environ['gooberauthenticated'] = 'No'
except Exception as e:
print(f"{RED}{get_translation(LOCALE, 'goober_ping_fail2')} {str(e)}{RESET}")
os.environ['gooberauthenticated'] = 'No'
positive_gifs = os.getenv("POSITIVE_GIFS").split(',')
positive_gifs = os.getenv("POSITIVEGIFS").split(',')
def is_positive(sentence):
scores = analyzer.polarity_scores(sentence)
@ -695,15 +577,9 @@ async def ping(ctx):
@bot.hybrid_command(description=f"{get_translation(LOCALE, 'command_about_desc')}")
async def about(ctx):
print("-----------------------------------\n\n")
try:
check_for_update()
except Exception as e:
pass
print("-----------------------------------")
embed = discord.Embed(title=f"{get_translation(LOCALE, 'command_about_embed_title')}", description="", color=discord.Color.blue())
embed.add_field(name=f"{get_translation(LOCALE, 'command_about_embed_field1')}", value=f"{NAME}", inline=False)
embed.add_field(name=f"{get_translation(LOCALE, 'command_about_embed_field2name')}", value=f"{get_translation(LOCALE, 'command_about_embed_field2value').format(local_version=local_version, latest_version=latest_version)}", inline=False)
embed.add_field(name=f"{get_translation(LOCALE, 'command_about_embed_field2name')}", value=f"{get_translation(LOCALE, 'command_about_embed_field2value').format(local_version=local_version, latest_version='I have not been updated with the new version checking!')}", inline=False)
await send_message(ctx, embed=embed)

View file

@ -7,20 +7,16 @@ load_dotenv()
VERSION_URL = "https://goober.expect.ovh"
UPDATE_URL = VERSION_URL+"/latest_version.json"
LOCAL_VERSION_FILE = "current_version.txt"
TOKEN = os.getenv("DISCORD_BOT_TOKEN")
PREFIX = os.getenv("BOT_PREFIX")
hourlyspeak = int(os.getenv("hourlyspeak"))
PING_LINE = os.getenv("PING_LINE")
random_talk_channel_id1 = int(os.getenv("rnd_talk_channel1"))
LOCALE = os.getenv("locale")
gooberTOKEN = os.getenv("gooberTOKEN")
random_talk_channel_id2 = int(os.getenv("rnd_talk_channel2"))
cooldown_time = os.getenv("cooldown")
splashtext = os.getenv("splashtext")
ownerid = int(os.getenv("ownerid"))
showmemenabled = os.getenv("showmemenabled")
BLACKLISTED_USERS = os.getenv("BLACKLISTED_USERS", "").split(",")
USERTRAIN_ENABLED = os.getenv("USERTRAIN_ENABLED", "true").lower() == "true"
TOKEN = os.getenv("DISCORDBOTTOKEN")
PREFIX = os.getenv("BOTPREFIX")
PING_LINE = os.getenv("PINGLINE")
LOCALE = os.getenv("LOCALE")
gooberTOKEN = os.getenv("GOOBERTOKEN")
splashtext = os.getenv("SPLASHTEXT")
ownerid = int(os.getenv("OWNERID"))
showmemenabled = os.getenv("SHOWMEMENABLED")
BLACKLISTED_USERS = os.getenv("BLACKLISTEDUSERS", "").split(",")
USERTRAIN_ENABLED = os.getenv("USERTRAINENABLED", "true").lower() == "true"
NAME = os.getenv("NAME")
last_random_talk_time = 0
MEMORY_FILE = "memory.json"
@ -28,7 +24,7 @@ DEFAULT_DATASET_FILE = "defaultdataset.json"
MEMORY_LOADED_FILE = "MEMORY_LOADED"
ALIVEPING = os.getenv("ALIVEPING")
IGNOREWARNING = False
song = os.getenv("song")
song = os.getenv("SONG")
arch = platform.machine()
RED = "\033[31m"
GREEN = "\033[32m"

1
modules/volta Submodule

@ -0,0 +1 @@
Subproject commit 628de5f76ea2a258448d2ddfc081c2ce58f509fd

208
volta.py Normal file
View file

@ -0,0 +1,208 @@
# If you're seeing this after cloning the Goober repo, note that this is a standalone module for translations.
# While it's used by Goober Core, it lives in its own repository and should not be modified here.
# For updates or contributions, visit: https://github.com/gooberinc/volta
# Also, Note to self: Add more comments it needs more love
import os
import locale
import json
import pathlib
import threading
import time
from dotenv import load_dotenv
ANSI = "\033["
RED = f"{ANSI}31m"
GREEN = f"{ANSI}32m"
YELLOW = f"{ANSI}33m"
DEBUG = f"{ANSI}1;30m"
RESET = f"{ANSI}0m"
LOCALE = os.getenv("LOCALE")
module_dir = pathlib.Path(__file__).parent.parent
working_dir = pathlib.Path.cwd()
EXCLUDE_DIRS = {'.git', '__pycache__'}
locales_dirs = []
ENGLISH_MISSING = False
FALLBACK_LOCALE = "en"
if os.getenv("fallback_locale"):
FALLBACK_LOCALE = os.getenv("fallback_locale")
def find_locales_dirs(base_path):
found = []
for root, dirs, files in os.walk(base_path):
dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS]
if 'locales' in dirs:
locales_path = pathlib.Path(root) / 'locales'
found.append(locales_path)
dirs.remove('locales')
return found
def find_dotenv(start_path: pathlib.Path) -> pathlib.Path | None:
current = start_path.resolve()
while current != current.parent:
candidate = current / ".env"
if candidate.exists():
return candidate
current = current.parent
return None
env_path = find_dotenv(pathlib.Path(__file__).parent)
if env_path:
load_dotenv(dotenv_path=env_path)
print(f"[VOLTA] {GREEN}Loaded .env from {env_path}{RESET}")
else:
print(f"[VOLTA] {YELLOW}No .env file found from {__file__} upwards.{RESET}")
locales_dirs.extend(find_locales_dirs(module_dir))
if working_dir != module_dir:
locales_dirs.extend(find_locales_dirs(working_dir))
translations = {}
_file_mod_times = {}
import locale
import platform
import os
import sys
def get_system_locale():
system = platform.system() # fallback incase locale isnt set
if system == "Windows":
lang, _ = locale.getdefaultlocale()
return lang or os.getenv("LANG")
elif system == "Darwin":
try:
import subprocess
result = subprocess.run(
["defaults", "read", "-g", "AppleLocale"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True
)
return result.stdout.strip() or locale.getdefaultlocale()[0]
except Exception:
return locale.getdefaultlocale()[0]
elif system == "Linux":
return (
os.getenv("LC_ALL") or
os.getenv("LANG") or
locale.getdefaultlocale()[0]
)
return locale.getdefaultlocale()[0]
def load_translations():
global translations, _file_mod_times
translations.clear()
_file_mod_times.clear()
for locales_dir in locales_dirs:
for filename in os.listdir(locales_dir):
if filename.endswith(".json"):
lang_code = filename[:-5]
file_path = locales_dir / filename
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
if lang_code not in translations:
translations[lang_code] = {}
translations[lang_code].update(data)
_file_mod_times[(lang_code, file_path)] = file_path.stat().st_mtime
except Exception as e:
print(f"[VOLTA] {RED}Failed loading {file_path}: {e}{RESET}")
def reload_if_changed():
while True:
for (lang_code, file_path), last_mtime in list(_file_mod_times.items()):
try:
current_mtime = file_path.stat().st_mtime
if current_mtime != last_mtime:
print(f"[VOLTA] {RED}Translation file changed: {file_path}, reloading...{RESET}")
load_translations()
break
except FileNotFoundError:
print(f"[VOLTA] {RED}Translation file removed: {file_path}{RESET}")
_file_mod_times.pop((lang_code, file_path), None)
if lang_code in translations:
translations.pop(lang_code, None)
def set_language(lang: str):
global LOCALE, ENGLISH_MISSING
if not LOCALE:
LOCALE = get_system_locale()
elif lang in translations:
LOCALE = lang
else:
print(f"[VOLTA] {RED}Language '{lang}' not found, defaulting to 'en'{RESET}")
if FALLBACK_LOCALE in translations:
LOCALE = FALLBACK_LOCALE
else:
print(f"[VOLTA] {RED}The fallback translations cannot be found! No fallback available.{RESET}")
ENGLISH_MISSING = True
def check_missing_translations():
global LOCALE, ENGLISH_MISSING
load_translations()
if FALLBACK_LOCALE not in translations:
print(f"[VOLTA] {RED}Fallback translations ({FALLBACK_LOCALE}.json) missing from assets/locales.{RESET}")
ENGLISH_MISSING = True
return
if LOCALE == "en":
print("[VOLTA] Locale is English, skipping missing key check.")
return
en_keys = set(translations.get("en", {}).keys())
locale_keys = set(translations.get(LOCALE, {}).keys())
missing_keys = en_keys - locale_keys
total_keys = len(en_keys)
missing_count = len(missing_keys)
if missing_count > 0:
percent_missing = (missing_count / total_keys) * 100
if percent_missing == 100:
print(f"[VOLTA] {YELLOW}Warning: All keys are missing in locale '{LOCALE}'! Defaulting back to {FALLBACK_LOCALE}{RESET}")
set_language(FALLBACK_LOCALE)
elif percent_missing > 0:
print(f"[VOLTA] {YELLOW}Warning: {missing_count}/{total_keys} keys missing in locale '{LOCALE}' ({percent_missing:.1f}%)!{RESET}")
for key in sorted(missing_keys):
print(f" - {key}")
time.sleep(2)
else:
print(f"[VOLTA] All translation keys present for locale: {LOCALE}")
printedsystemfallback = False
def get_translation(lang: str, key: str):
global printedsystemfallback
if ENGLISH_MISSING:
return f"[VOLTA] {RED}No fallback available!{RESET}"
fallback_translations = translations.get(FALLBACK_LOCALE, {})
sys_lang = get_system_locale().split("_")[0] if get_system_locale() else None
sys_translations = translations.get(sys_lang, {}) if sys_lang else {}
lang_translations = translations.get(lang, {})
if key in lang_translations:
return lang_translations[key]
if sys_lang and sys_lang != lang and key in sys_translations:
if not printedsystemfallback:
print(f"[VOLTA] {YELLOW}Falling back to system language {sys_lang}!{RESET}")
printedsystemfallback = True
return sys_translations[key]
if key in fallback_translations:
print(f"[VOLTA] {YELLOW}Missing key: '{key}' in '{lang}', falling back to fallback locale '{FALLBACK_LOCALE}'{RESET}")
return fallback_translations[key]
return f"[VOLTA] {YELLOW}Missing key: '{key}' in all locales!{RESET}"
def _(key: str) -> str:
return get_translation(LOCALE, key)
load_translations()
watchdog_thread = threading.Thread(target=reload_if_changed, daemon=True)
watchdog_thread.start()
if __name__ == '__main__':
print("Volta should not be run directly! Please use it as a module..")