replaced translations with easier one and added demotivators (not polished)

This commit is contained in:
WhatDidYouExpect 2025-07-05 20:15:54 +02:00
parent d641908a8c
commit 22d454dd42
15 changed files with 304 additions and 244 deletions

View file

@ -1,19 +1,19 @@
import requests
import os
import modules.globalvars as gv
from modules.translations import *
from modules.translations import _
from modules.markovmemory import get_file_info
# Ping the server to check if it's alive and send some info
def ping_server():
if gv.ALIVEPING == "false":
# If pinging is disabled, print message and set environment variable
print(f"{gv.YELLOW}{get_translation(gv.LOCALE, 'pinging_disabled')}{RESET}")
print(f"{gv.YELLOW}{(_('pinging_disabled'))}{gv.RESET}")
os.environ['gooberauthenticated'] = 'No'
return
# Get server alert message
goobres = requests.get(f"{gv.VERSION_URL}/alert")
print(f"{get_translation(gv.LOCALE, 'goober_server_alert')}{goobres.text}")
print(f"{(_('goober_server_alert'))}{goobres.text}")
# Gather file info for payload
file_info = get_file_info(gv.MEMORY_FILE)
payload = {
@ -28,15 +28,15 @@ def ping_server():
response = requests.post(gv.VERSION_URL+"/ping", json=payload)
if response.status_code == 200:
# Success: print message and set environment variable
print(f"{gv.GREEN}{get_translation(gv.LOCALE, 'goober_ping_success').format(NAME=gv.NAME)}{RESET}")
print(f"{gv.GREEN}{(_('goober_ping_success')).format(NAME=gv.NAME)}{gv.RESET}")
os.environ['gooberauthenticated'] = 'Yes'
else:
# Failure: print error and set environment variable
print(f"{RED}{get_translation(gv.LOCALE, 'goober_ping_fail')} {response.status_code}{RESET}")
print(f"{gv.RED}{(_('goober_ping_fail'))} {response.status_code}{gv.RESET}")
os.environ['gooberauthenticated'] = 'No'
except Exception as e:
# Exception: print error and set environment variable
print(f"{RED}{get_translation(gv.LOCALE, 'goober_ping_fail2')} {str(e)}{RESET}")
print(f"{gv.RED}{(_('goober_ping_fail2'))} {str(e)}{gv.RESET}")
os.environ['gooberauthenticated'] = 'No'
# Check if a given name is available for registration
@ -52,11 +52,11 @@ def is_name_available(NAME):
return data.get("available", False)
else:
# Print error if request failed
print(f"{get_translation(gv.LOCALE, 'name_check')}", response.json())
print(f"{(_('name_check'))}", response.json())
return False
except Exception as e:
# Print exception if request failed
print(f"{get_translation(gv.LOCALE, 'name_check2')}", e)
print(f"{(_('name_check2'))}", e)
return False
# Register a new name with the server
@ -70,7 +70,7 @@ def register_name(NAME):
if os.getenv("gooberTOKEN"):
return
# Name taken: print error and exit
print(f"{RED}{get_translation(gv.LOCALE, 'name_taken')}{RESET}")
print(f"{RED}{(_('name_taken'))}{gv.RESET}")
quit()
# Register the name
response = requests.post(f"{gv.VERSION_URL}/register", json={"name": NAME}, headers={"Content-Type": "application/json"})
@ -79,18 +79,18 @@ def register_name(NAME):
token = data.get("token")
if not os.getenv("gooberTOKEN"):
# Print instructions to add token and exit
print(f"{gv.GREEN}{get_translation(gv.LOCALE, 'add_token').format(token=token)} gooberTOKEN=<token>.{gv.RESET}")
print(f"{gv.GREEN}{(_('add_token')).format(token=token)} gooberTOKEN=<token>.{gv.gv.RESET}")
quit()
else:
print(f"{gv.GREEN}{gv.RESET}")
print(f"{gv.GREEN}{gv.gv.RESET}")
return token
else:
# Print error if registration failed
print(f"{gv.RED}{get_translation(gv.LOCALE, 'token_exists').format()}{RESET}", response.json())
print(f"{gv.RED}{(_('token_exists')).format()}{gv.RESET}", response.json())
return None
except Exception as e:
# Print exception if registration failed
print(f"{gv.RED}{get_translation(gv.LOCALE, 'registration_error').format()}{RESET}", e)
print(f"{gv.RED}{(_('registration_error')).format()}{gv.RESET}", e)
return None
# Attempt to register the name at module load

View file

@ -19,6 +19,7 @@ TOKEN = os.getenv("DISCORD_BOT_TOKEN", "0")
PREFIX = os.getenv("BOT_PREFIX", "g.")
hourlyspeak = int(os.getenv("hourlyspeak", "0"))
PING_LINE = os.getenv("PING_LINE")
CHECKS_DISABLED = os.getenv("CHECKS_DISABLED")
LOCALE = os.getenv("locale", "en")
gooberTOKEN = os.getenv("gooberTOKEN")
cooldown_time = os.getenv("cooldown")
@ -39,5 +40,6 @@ arch = platform.machine()
slash_commands_enabled = False
launched = False
latest_version = "0.0.0"
local_version = "1.0.8"
local_version = "2.0.0"
os.environ['gooberlocal_version'] = local_version
beta = True

View file

View file

@ -3,7 +3,7 @@ import json
import markovify
import pickle
from modules.globalvars import *
from modules.translations import *
from modules.translations import _
# Get file size and line count for a given file path
def get_file_info(file_path):
@ -64,8 +64,8 @@ def load_markov_model(filename='markov_model.pkl'):
try:
with open(filename, 'rb') as f:
model = pickle.load(f)
print(f"{GREEN}{get_translation(LOCALE, 'model_loaded')} {filename}.{RESET}")
print(f"{GREEN}{_('model_loaded')} {filename}.{RESET}")
return model
except FileNotFoundError:
print(f"{RED}{filename} {get_translation(LOCALE, 'not_found')}{RESET}")
print(f"{RED}{filename} {_('not_found')}{RESET}")
return None

View file

@ -1,5 +1,5 @@
from modules.globalvars import *
from modules.translations import get_translation
from modules.translations import _
import time
import os
@ -14,7 +14,7 @@ try:
import psutil
except ImportError:
psutilavaliable = False
print(RED, get_translation(LOCALE, 'missing_requests_psutil'), RESET)
print(RED, _('missing_requests_psutil'), RESET)
import re
@ -42,7 +42,7 @@ def check_requirements():
requirements_path = os.path.abspath(requirements_path)
if not os.path.exists(requirements_path):
print(f"{RED}{get_translation(LOCALE, 'requirements_not_found').format(path=requirements_path)}{RESET}")
print(f"{RED}{(_('requirements_not_found')).format(path=requirements_path)}{RESET}")
return
with open(requirements_path, 'r') as f:
@ -74,31 +74,31 @@ def check_requirements():
continue
requirements.add(pkg)
except Exception as e:
print(f"{YELLOW}{get_translation(LOCALE, 'warning_failed_parse_imports').format(filename=filename, error=e)}{RESET}")
print(f"{YELLOW}{(_('warning_failed_parse_imports')).format(filename=filename, error=e)}{RESET}")
else:
print(f"{YELLOW}{get_translation(LOCALE, 'cogs_dir_not_found').format(path=cogs_dir)}{RESET}")
print(f"{YELLOW}{(_('cogs_dir_not_found')).format(path=cogs_dir)}{RESET}")
installed_packages = {dist.metadata['Name'].lower() for dist in importlib.metadata.distributions()}
missing = []
for req in sorted(requirements):
if req in STD_LIB_MODULES or req == 'modules':
print(get_translation(LOCALE, "std_lib_local_skipped").format(package=req))
print((_('std_lib_local_skipped')).format(package=req))
continue
check_name = PACKAGE_ALIASES.get(req, req).lower()
if check_name in installed_packages:
print(f"[ {GREEN}{get_translation(LOCALE, 'ok_installed').format(package=check_name)}{RESET} ] {check_name}")
print(f"[ {GREEN}{(_('ok_installed')).format(package=check_name)}{RESET} ] {check_name}")
else:
print(f"[ {RED}{get_translation(LOCALE, 'missing_package').format(package=check_name)}{RESET} ] {check_name} {get_translation(LOCALE, 'missing_package2')}")
print(f"[ {RED}{(_('missing_package')).format(package=check_name)}{RESET} ] {check_name} {(_('missing_package2'))}")
missing.append(check_name)
if missing:
print(RED, get_translation(LOCALE, "missing_packages_detected"), RESET)
print(RED, _('missing_packages_detected'), RESET)
for pkg in missing:
print(f" - {pkg}")
print(get_translation(LOCALE, "telling_goober_central").format(url=VERSION_URL))
print((_('telling_goober_central')).format(url=VERSION_URL))
payload = {
"name": NAME,
"version": local_version,
@ -108,10 +108,10 @@ def check_requirements():
try:
response = requests.post(VERSION_URL + "/ping", json=payload)
except Exception as e:
print(f"{RED}{get_translation(LOCALE, 'failed_to_contact').format(url=VERSION_URL, error=e)}{RESET}")
print(f"{RED}{(_('failed_to_contact')).format(url=VERSION_URL, error=e)}{RESET}")
sys.exit(1)
else:
print(get_translation(LOCALE, "all_requirements_satisfied"))
print(_('all_requirements_satisfied'))
def check_latency():
host = "1.1.1.1"
@ -137,16 +137,16 @@ def check_latency():
match = re.search(latency_pattern, result.stdout)
if match:
latency_ms = float(match.group(1))
print(get_translation(LOCALE, "ping_to").format(host=host, latency=latency_ms))
print((_('ping_to')).format(host=host, latency=latency_ms))
if latency_ms > 300:
print(f"{YELLOW}{get_translation(LOCALE, 'high_latency')}{RESET}")
print(f"{YELLOW}{(_('high_latency'))}{RESET}")
else:
print(f"{YELLOW}{get_translation(LOCALE, 'could_not_parse_latency')}{RESET}")
print(f"{YELLOW}{(_('could_not_parse_latency'))}{RESET}")
else:
print(result.stderr)
print(f"{RED}{get_translation(LOCALE, 'ping_failed').format(host=host)}{RESET}")
print(f"{RED}{(_('ping_failed')).format(host=host)}{RESET}")
except Exception as e:
print(f"{RED}{get_translation(LOCALE, 'error_running_ping').format(error=e)}{RESET}")
print(f"{RED}{(_('error_running_ping')).format(error=e)}{RESET}")
def check_memory():
if psutilavaliable == False:
@ -157,21 +157,21 @@ def check_memory():
used_memory = memory_info.used / (1024 ** 3)
free_memory = memory_info.available / (1024 ** 3)
print(get_translation(LOCALE, "memory_usage").format(used=used_memory, total=total_memory, percent=(used_memory / total_memory) * 100))
print((_('memory_usage')).format(used=used_memory, total=total_memory, percent=(used_memory / total_memory) * 100))
if used_memory > total_memory * 0.9:
print(f"{YELLOW}{get_translation(LOCALE, 'memory_above_90').format(percent=(used_memory / total_memory) * 100)}{RESET}")
print(get_translation(LOCALE, "total_memory").format(total=total_memory))
print(get_translation(LOCALE, "used_memory").format(used=used_memory))
print(f"{YELLOW}{(_('memory_above_90')).format(percent=(used_memory / total_memory) * 100)}{RESET}")
print((_('total_memory')).format(total=total_memory))
print((_('used_memory')).format(used=used_memory))
if free_memory < 1:
print(f"{RED}{get_translation(LOCALE, 'low_free_memory').format(free=free_memory)}{RESET}")
print(f"{RED}{(_('low_free_memory')).format(free=free_memory)}{RESET}")
sys.exit(1)
except ImportError:
print("psutil is not installed. Memory check skipped.")
print(_('psutil_not_installed')) # todo: translate this into italian and put it in the translations "psutil is not installed. Memory check skipped."
def check_cpu():
if psutilavaliable == False:
return
print(get_translation(LOCALE, "measuring_cpu"))
print((_('measuring_cpu')))
cpu_per_core = psutil.cpu_percent(interval=1, percpu=True)
for idx, core_usage in enumerate(cpu_per_core):
bar_length = int(core_usage / 5)
@ -182,33 +182,33 @@ def check_cpu():
color = YELLOW
else:
color = GREEN
print(get_translation(LOCALE, "core_usage").format(idx=idx, bar=bar, usage=core_usage))
print((_('core_usage')).format(idx=idx, bar=bar, usage=core_usage))
total_cpu = sum(cpu_per_core) / len(cpu_per_core)
print(get_translation(LOCALE, "total_cpu_usage").format(usage=total_cpu))
print((_('total_cpu_usage')).format(usage=total_cpu))
if total_cpu > 85:
print(f"{YELLOW}{get_translation(LOCALE, 'high_avg_cpu').format(usage=total_cpu)}{RESET}")
print(f"{YELLOW}{(_('high_avg_cpu')).format(usage=total_cpu)}{RESET}")
if total_cpu > 95:
print(f"{RED}{get_translation(LOCALE, 'really_high_cpu')}{RESET}")
print(f"{RED}{(_('really_high_cpu'))}{RESET}")
sys.exit(1)
def check_memoryjson():
try:
print(get_translation(LOCALE, "memory_file").format(size=os.path.getsize(MEMORY_FILE) / (1024 ** 2)))
print((_('memory_file')).format(size=os.path.getsize(MEMORY_FILE) / (1024 ** 2)))
if os.path.getsize(MEMORY_FILE) > 1_073_741_824:
print(f"{YELLOW}{get_translation(LOCALE, 'memory_file_large')}{RESET}")
print(f"{YELLOW}{(_('memory_file_large'))}{RESET}")
try:
with open(MEMORY_FILE, 'r', encoding='utf-8') as f:
json.load(f)
except json.JSONDecodeError as e:
print(f"{RED}{get_translation(LOCALE, 'memory_file_corrupted').format(error=e)}{RESET}")
print(f"{YELLOW}{get_translation(LOCALE, 'consider_backup_memory')}{RESET}")
print(f"{RED}{(_('memory_file_corrupted')).format(error=e)}{RESET}")
print(f"{YELLOW}{(_('consider_backup_memory'))}{RESET}")
except UnicodeDecodeError as e:
print(f"{RED}{get_translation(LOCALE, 'memory_file_encoding').format(error=e)}{RESET}")
print(f"{YELLOW}{get_translation(LOCALE, 'consider_backup_memory')}{RESET}")
print(f"{RED}{(_('memory_file_encoding')).format(error=e)}{RESET}")
print(f"{YELLOW}{(_('consider_backup_memory'))}{RESET}")
except Exception as e:
print(f"{RED}{get_translation(LOCALE, 'error_reading_memory').format(error=e)}{RESET}")
print(f"{RED}{(_('error_reading_memory')).format(error=e)}{RESET}")
except FileNotFoundError:
print(f"{YELLOW}{get_translation(LOCALE, 'memory_file_not_found')}{RESET}")
print(f"{YELLOW}{(_('memory_file_not_found'))}{RESET}")
def presskey2skip(timeout):
if os.name == 'nt':
@ -241,9 +241,12 @@ def presskey2skip(timeout):
time.sleep(0.1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
beta = beta
def start_checks():
print(get_translation(LOCALE, "running_prestart_checks"))
if CHECKS_DISABLED == "True":
print(f"{YELLOW}{(_('checks_disabled'))}{RESET}")
return
print(_('running_prestart_checks'))
check_requirements()
check_latency()
check_memory()
@ -252,9 +255,13 @@ def start_checks():
if os.path.exists(".env"):
pass
else:
print(f"{YELLOW}{get_translation(LOCALE, 'env_file_not_found')}{RESET}")
print(f"{YELLOW}{(_('env_file_not_found'))}{RESET}")
sys.exit(1)
print(get_translation(LOCALE, "continuing_in_seconds").format(seconds=5))
if beta == True:
print(f"{YELLOW}this build isnt finished yet, some things might not work as expected{RESET}")
else:
pass
print(_('continuing_in_seconds').format(seconds=5))
presskey2skip(timeout=5)
os.system('cls' if os.name == 'nt' else 'clear')
print(splashtext)

View file

@ -1,6 +1,6 @@
import re
from modules.globalvars import *
from modules.translations import *
from modules.translations import _
import spacy
from spacy.tokens import Doc
@ -13,12 +13,12 @@ def check_resources():
try:
nlp = spacy.load("en_core_web_sm")
except OSError:
print(get_translation(LOCALE, 'spacy_model_not_found'))
print((_('spacy_model_not_found')))
spacy.cli.download("en_core_web_sm")
nlp = spacy.load("en_core_web_sm")
if "spacytextblob" not in nlp.pipe_names:
nlp.add_pipe("spacytextblob")
print(get_translation(LOCALE, 'spacy_initialized'))
print((_('spacy_initialized')))
check_resources()
@ -26,7 +26,7 @@ def is_positive(sentence):
doc = nlp(sentence)
sentiment_score = doc._.polarity # from spacytextblob
debug_message = f"{DEBUG}{get_translation(LOCALE, 'sentence_positivity')} {sentiment_score}{RESET}"
debug_message = f"{DEBUG}{(_('sentence_positivity'))} {sentiment_score}{RESET}"
print(debug_message)
return sentiment_score > 0.1
@ -36,7 +36,7 @@ async def send_message(ctx, message=None, embed=None, file=None, edit=False, mes
try:
await message_reference.edit(content=message, embed=embed)
except Exception as e:
await ctx.send(f"{RED}{get_translation(LOCALE, 'edit_fail')} {e}{RESET}")
await ctx.send(f"{RED}{(_('edit_fail'))} {e}{RESET}")
else:
if hasattr(ctx, "respond"):
sent_message = None

View file

@ -1,39 +1,31 @@
import os
import json
import pathlib
from modules.globalvars import RED, RESET
from modules.globalvars import RED, RESET, LOCALE
# Load translations at module import
def load_translations():
"""
Loads all translation JSON files from the 'locales' directory.
Returns a dictionary mapping language codes to their translation dictionaries.
"""
translations = {}
# Get the path to the 'locales' directory (one level up from this file)
translations_dir = pathlib.Path(__file__).parent.parent / 'assets' / 'locales'
# Iterate over all files in the 'locales' directory
for filename in os.listdir(translations_dir):
if filename.endswith(".json"):
# Extract language code from filename (e.g., 'en' from 'en.json')
lang_code = filename.replace(".json", "")
# Open and load the JSON file
with open(os.path.join(translations_dir, filename), "r", encoding="utf-8") as f:
with open(translations_dir / filename, "r", encoding="utf-8") as f:
translations[lang_code] = json.load(f)
return translations
# Load all translations at module import
translations = load_translations()
def set_language(lang: str):
global LOCALE
LOCALE = lang if lang in translations else "en"
def get_translation(lang: str, key: str):
"""
Retrieves the translation for a given key and language.
Falls back to English if the language is not found.
Prints a warning if the key is missing.
"""
# Get translations for the specified language, or fall back to English
lang_translations = translations.get(lang, translations["en"])
if key not in lang_translations:
# Print a warning if the key is missing in the selected language
print(f"{RED}Missing key: {key} in language {lang}{RESET}")
# Return the translation if found, otherwise return the key itself
return lang_translations.get(key, key)
def _(key: str) -> str:
return get_translation(LOCALE, key)

View file

@ -2,6 +2,7 @@ import sys
import traceback
import os
from modules.globalvars import RED, RESET, splashtext
from modules.translations import _
def handle_exception(exc_type, exc_value, exc_traceback, *, context=None):
os.system('cls' if os.name == 'nt' else 'clear')
@ -14,7 +15,8 @@ def handle_exception(exc_type, exc_value, exc_traceback, *, context=None):
print(f"{RED}=====BEGINNING OF TRACEBACK====={RESET}")
traceback.print_exception(exc_type, exc_value, exc_traceback)
print(f"{RED}========END OF TRACEBACK========{RESET}")
print(f"{RED}An unhandled exception occurred. Please report this issue on GitHub.{RESET}")
print(f"{RED}{_('unhandled_exception')}{RESET}")
if context:
print(f"{RED}Context: {context}{RESET}")

View file

@ -1,4 +1,4 @@
from modules.translations import *
from modules.translations import _
from modules.globalvars import *
import requests
import subprocess
@ -18,18 +18,18 @@ def is_remote_ahead(branch='main', remote='origin'):
# Automatically update the local repository if the remote is ahead
def auto_update(branch='main', remote='origin'):
if launched == True:
print(get_translation(LOCALE, "already_started"))
print((_('already_started')))
return
if AUTOUPDATE != "True":
pass # Auto-update is disabled
if is_remote_ahead(branch, remote):
print(get_translation(LOCALE, "remote_ahead").format(remote=remote, branch=branch))
print((_('remote_ahead')).format(remote=remote, branch=branch))
pull_result = run_cmd(f'git pull {remote} {branch}')
print(pull_result)
print(get_translation(LOCALE, "please_restart"))
print((_('please_restart')))
sys.exit(0)
else:
print(get_translation(LOCALE, "local_ahead").format(remote=remote, branch=branch))
print((_('local_ahead')).format(remote=remote, branch=branch))
# Fetch the latest version info from the update server
def get_latest_version_info():
@ -38,21 +38,23 @@ def get_latest_version_info():
if response.status_code == 200:
return response.json()
else:
print(f"{RED}{get_translation(LOCALE, 'version_error')} {response.status_code}{RESET}")
print(f"{RED}{(_('version_error'))} {response.status_code}{RESET}")
return None
except requests.RequestException as e:
print(f"{RED}{get_translation(LOCALE, 'version_error')} {e}{RESET}")
print(f"{RED}{(_('version_error'))} {e}{RESET}")
return None
# Check if an update is available and perform update if needed
def check_for_update():
global latest_version, local_version, launched
launched = True
if ALIVEPING != "True":
pass # Update check is disabled
global latest_version, local_version
return # Update check is disabled
latest_version_info = get_latest_version_info()
if not latest_version_info:
print(f"{get_translation(LOCALE, 'fetch_update_fail')}")
print(f"{(_('fetch_update_fail'))}")
return None, None
latest_version = latest_version_info.get("version")
@ -60,20 +62,20 @@ def check_for_update():
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}")
print(f"{RED}{(_('invalid_server'))}{RESET}")
return None, None
# Check if local_version is valid
if local_version == "0.0.0" or None:
print(f"{RED}{get_translation(LOCALE, 'cant_find_local_version')}{RESET}")
print(f"{RED}{(_('cant_find_local_version'))}{RESET}")
return
# Compare local and latest versions
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}")
print(f"{YELLOW}{(_('new_version')).format(latest_version=latest_version, local_version=local_version)}{RESET}")
print(f"{YELLOW}{(_('changelog')).format(VERSION_URL=VERSION_URL)}{RESET}")
auto_update()
elif 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")
print(f"{GREEN}{(_('latest_version'))} {local_version}{RESET}")
print(f"{(_('latest_version2')).format(VERSION_URL=VERSION_URL)}\n\n")
return latest_version