Compare commits
12 commits
main
...
rewrite/se
Author | SHA1 | Date | |
---|---|---|---|
a0e2e39b65 | |||
![]() |
21b5107dd6 | ||
![]() |
3621a65481 | ||
![]() |
2c72a31a1a | ||
![]() |
607656bca0 | ||
![]() |
31dc82b368 | ||
![]() |
7877db4785 | ||
![]() |
ddfd67df5c | ||
![]() |
145587c81f | ||
![]() |
d0ae422233 | ||
![]() |
15e40e0325 | ||
![]() |
587d24d520 |
|
@ -1 +0,0 @@
|
|||
DISCORD_BOT_TOKEN=""
|
16
.gitignore
vendored
|
@ -4,15 +4,9 @@ current_version.txt
|
|||
MEMORY_LOADED
|
||||
memory.json
|
||||
*.pkl
|
||||
memory.json
|
||||
venv/
|
||||
output.png
|
||||
.vscode/
|
||||
received_memory.json
|
||||
translation_report.txt
|
||||
translationcompleteness.py
|
||||
modules/volta
|
||||
memories/
|
||||
models/
|
||||
log.txt
|
||||
settings/admin_logs.json
|
||||
settings/settings.json
|
||||
assets/images/cached/*
|
||||
translationcompleteness.py
|
||||
translation_report.txt
|
||||
output.png
|
||||
|
|
3
.gitmodules
vendored
|
@ -1,3 +0,0 @@
|
|||
[submodule "modules/volta"]
|
||||
path = modules/volta
|
||||
url = https://github.com/gooberinc/volta
|
14
README.md
|
@ -1,2 +1,12 @@
|
|||
Real repo: https://forgejo.expect.ovh/gooberinc/goober
|
||||
This is just a fork that was made the upstream
|
||||
Discord bot that learns from what people say!
|
||||
|
||||
Please see the [wiki](https://wiki.goober.whatdidyouexpect.eu)
|
||||
|
||||
keep in mind that most of the bot was written at 2am
|
||||
|
||||
special thanks to
|
||||
[Charlies Computers](https://github.com/PowerPCFan) for being the only one i know of thats actually hosting goober 24/7
|
||||
|
||||
[Goober Central](https://github.com/whatdidyouexpect/goober-central)
|
||||
|
||||

|
||||
|
|
|
@ -1,153 +0,0 @@
|
|||
from typing import List
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
import markovify
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
import os
|
||||
from modules.markovmemory import load_markov_model
|
||||
from textwrap import wrap
|
||||
import logging
|
||||
from modules.settings import instance as settings_manager
|
||||
import re
|
||||
import time
|
||||
from modules.sync_conenctor import instance as sync_hub
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
class BreakingNews(commands.Cog):
|
||||
def __init__(self, bot: commands.Bot):
|
||||
self.bot: commands.Bot = bot
|
||||
self.font_size = 90
|
||||
self.image_margin = -25
|
||||
self.font: ImageFont.FreeTypeFont = ImageFont.truetype(
|
||||
os.path.join("assets", "fonts", "SpecialGothic.ttf"), self.font_size
|
||||
)
|
||||
|
||||
self.model: markovify.NewlineText | None = load_markov_model()
|
||||
|
||||
@commands.command()
|
||||
async def auto_create(self, ctx: commands.Context, enabled: str | None):
|
||||
if enabled not in ["yes", "no"]:
|
||||
await ctx.send(
|
||||
f'Please use {settings["bot"]["prefix"]}auto_create <yes | no>'
|
||||
)
|
||||
return False
|
||||
|
||||
mode: bool = enabled == "yes"
|
||||
|
||||
settings_manager.set_plugin_setting(
|
||||
"breaking_news", {"create_from_message_content": mode}
|
||||
)
|
||||
|
||||
await ctx.send("Changed setting!")
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message: discord.Message):
|
||||
if not settings_manager.get_plugin_settings(
|
||||
"breaking_news", {"create_from_message_content": False}
|
||||
).get("create_from_message_content"):
|
||||
logger.debug("Ignoring message - create_from_message_content not enabled")
|
||||
return
|
||||
|
||||
if not message.content.lower().startswith("breaking news:"):
|
||||
logger.debug("Ignoring message - doesnt start with breaking news:")
|
||||
return
|
||||
|
||||
if not sync_hub.can_breaking_news(message.id):
|
||||
logger.debug("Sync hub denied breaking news request")
|
||||
return
|
||||
|
||||
|
||||
texts = re.split("breaking news:", message.content, flags=re.IGNORECASE)
|
||||
|
||||
logger.debug(texts)
|
||||
try:
|
||||
text = texts[1].strip()
|
||||
if not self.model:
|
||||
await message.reply("No news specified and model not found!")
|
||||
return False
|
||||
|
||||
text = text or self.model.make_sentence(max_chars=50, tries=50)
|
||||
path = self.__insert_text(text)
|
||||
except IndexError:
|
||||
if self.model is None:
|
||||
await message.reply("No model loaded and no breaking news specified")
|
||||
return False
|
||||
|
||||
path = self.__insert_text(
|
||||
self.model.make_sentence(max_chars=50, tries=50) or ""
|
||||
)
|
||||
await message.reply("You didn't specify any breaking news!")
|
||||
|
||||
with open(path, "rb") as f:
|
||||
await message.reply(file=discord.File(f))
|
||||
|
||||
@commands.command()
|
||||
async def breaking_news(self, ctx: commands.Context, *args):
|
||||
if not self.model:
|
||||
await ctx.send("Please supply a message!")
|
||||
return False
|
||||
|
||||
message = " ".join(args) or self.model.make_sentence(max_chars=50, tries=50)
|
||||
|
||||
if not message:
|
||||
await ctx.send("Please supply a message!")
|
||||
return False
|
||||
|
||||
with open(self.__insert_text(message), "rb") as f:
|
||||
await ctx.send(content="Breaking news!", file=discord.File(f))
|
||||
|
||||
def __insert_text(self, text):
|
||||
start = time.time()
|
||||
base_image_data: Image.ImageFile.ImageFile = Image.open(
|
||||
os.path.join("assets", "images", "breaking_news.png")
|
||||
)
|
||||
|
||||
base_image: ImageDraw.ImageDraw = ImageDraw.Draw(base_image_data)
|
||||
|
||||
MAX_IMAGE_WIDTH = base_image_data.width - self.image_margin
|
||||
|
||||
if len(text) * self.font_size > MAX_IMAGE_WIDTH:
|
||||
parts = wrap(text, MAX_IMAGE_WIDTH // self.font_size)
|
||||
logger.debug(parts)
|
||||
for index, part in enumerate(parts):
|
||||
text_size = base_image.textlength(part, self.font)
|
||||
|
||||
base_image.text(
|
||||
(
|
||||
self.image_margin / 2 + ((MAX_IMAGE_WIDTH - text_size) / 2),
|
||||
(base_image_data.height * 0.2) + index * self.font_size,
|
||||
),
|
||||
part,
|
||||
font=self.font,
|
||||
)
|
||||
else:
|
||||
text_size = base_image.textlength(text, self.font)
|
||||
|
||||
base_image.text(
|
||||
(
|
||||
self.image_margin / 2 + ((MAX_IMAGE_WIDTH - text_size) / 2),
|
||||
(base_image_data.height * 0.2),
|
||||
),
|
||||
text,
|
||||
font=self.font,
|
||||
)
|
||||
|
||||
path_folders = os.path.join("assets", "images", "cache")
|
||||
os.makedirs(path_folders, exist_ok=True)
|
||||
|
||||
path = os.path.join(path_folders, "breaking_news.png")
|
||||
|
||||
with open(path, "wb") as f:
|
||||
base_image_data.save(f)
|
||||
|
||||
logger.info(f"Generation took {time.time() - start}s")
|
||||
|
||||
return path
|
||||
|
||||
|
||||
async def setup(bot: commands.Bot):
|
||||
await bot.add_cog(BreakingNews(bot))
|
|
@ -1,41 +0,0 @@
|
|||
import random
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
|
||||
class eightball(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command()
|
||||
async def eightball(self, ctx):
|
||||
answer = random.choice(
|
||||
[
|
||||
"It is certain.",
|
||||
"It is decidedly so.",
|
||||
"Without a doubt.",
|
||||
"Yes definitely.",
|
||||
"You may rely on it.",
|
||||
"As I see it, yes.",
|
||||
"Most likely.",
|
||||
"Outlook good.",
|
||||
"Yes.",
|
||||
"Signs point to yes.",
|
||||
"Reply hazy, try again.",
|
||||
"Ask again later.",
|
||||
"Better not tell you now.",
|
||||
"Cannot predict now.",
|
||||
"Concentrate and ask again.",
|
||||
"Don't count on it.",
|
||||
"My reply is no.",
|
||||
"My sources say no.",
|
||||
"Outlook not so good.",
|
||||
"Very doubtful.",
|
||||
]
|
||||
)
|
||||
|
||||
await ctx.send(answer)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(eightball(bot))
|
|
@ -1,131 +0,0 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
from discord import app_commands
|
||||
|
||||
import discord.ext
|
||||
import discord.ext.commands
|
||||
|
||||
import random
|
||||
|
||||
from modules.permission import requires_admin
|
||||
from modules.sentenceprocessing import send_message
|
||||
from modules.settings import instance as settings_manager
|
||||
from typing import TypedDict
|
||||
|
||||
# Name according to your cog (e.g a random number generator -> RandomNumber)
|
||||
class Example(commands.Cog):
|
||||
# __init__ method is required with these exact parameters
|
||||
def __init__(self, bot: discord.ext.commands.Bot): # type hinting (aka : discord.ext.commands.Bot) isn't necessary, but provides better intellisense in code editors
|
||||
self.bot: discord.ext.commands.Bot = bot
|
||||
|
||||
|
||||
# a basic ping slash command which utilizes embeds
|
||||
@app_commands.command(name="ping", description="A command that sends a ping!")
|
||||
async def ping(self, interaction: discord.Interaction):
|
||||
await interaction.response.defer()
|
||||
|
||||
example_embed = discord.Embed(
|
||||
title="Pong!!",
|
||||
description="The Beretta fires fast and won't make you feel any better!",
|
||||
color=discord.Color.blue(),
|
||||
)
|
||||
example_embed.set_footer(
|
||||
text=f"Requested by {interaction.user.name}",
|
||||
icon_url=interaction.user.display_avatar,
|
||||
)
|
||||
|
||||
await interaction.followup.send(embed=example_embed)
|
||||
|
||||
# a basic command (aka prefix.random_number)
|
||||
# Shows how to get parameters, and how to send messages using goobers message thing
|
||||
@commands.command()
|
||||
async def random_number(self, ctx: commands.Context, minimum: int | None, maximum: int | None): # every argument after ctx is a part of the command, aka "g.random_number 0 5" would set minimum as 0 and maximum as 5
|
||||
# We should always assume that command parameters are None, since someone can gall g.randon_number.
|
||||
|
||||
if minimum is None:
|
||||
await send_message(ctx, message="Please specify the minimum number!")
|
||||
return # make sure we dont continue
|
||||
|
||||
if maximum is None:
|
||||
await send_message(ctx, message="Please specify the maximum number!")
|
||||
return # make sure we dont continue
|
||||
|
||||
|
||||
number = random.randint(minimum, maximum)
|
||||
|
||||
example_embed = discord.Embed(
|
||||
title="Random number generator",
|
||||
description=f"Random number: {number}",
|
||||
color=discord.Color.blue(),
|
||||
)
|
||||
example_embed.set_footer(
|
||||
text=f"Requested by {ctx.author.name}",
|
||||
icon_url=ctx.author.display_avatar,
|
||||
)
|
||||
|
||||
await send_message(ctx, embed=example_embed)
|
||||
|
||||
|
||||
# A command which requires the executor to be an admin, and takes a discord user as an argument
|
||||
@requires_admin() # from modules.permission import requires_admin
|
||||
@commands.command()
|
||||
async def ban_user(self, ctx: commands.Context, target: discord.Member | None, reason: str | None):
|
||||
if target is None:
|
||||
await send_message(ctx, "Please specify a user by pinging them!")
|
||||
return
|
||||
|
||||
await target.ban(reason=reason)
|
||||
await send_message(ctx, message=f"Banned user {target.name}!")
|
||||
|
||||
|
||||
# Changing and getting plugin settings, defining a settings schmea
|
||||
@commands.command()
|
||||
async def change_hello_message(self, ctx: commands.Context, new_message: str | None):
|
||||
COG_NAME = "example" # change this to whatever you want, but keep it the same accross your cog
|
||||
|
||||
if new_message is None:
|
||||
await send_message(ctx, "Please specify a new message!")
|
||||
return
|
||||
|
||||
# Generating a settings schema (optional)
|
||||
# from typing import TypedDict
|
||||
class IntroSettings(TypedDict):
|
||||
message: str
|
||||
|
||||
class SettingsType(TypedDict):
|
||||
intro: IntroSettings
|
||||
leave_message: str
|
||||
|
||||
# End of optional typing
|
||||
# Note: if you decide to do this, please place these at the top of the file! (but after imports)
|
||||
|
||||
default_settings: SettingsType = { # use default_settings = { if you didnt define the types
|
||||
"intro": {
|
||||
"message": "Hello user!"
|
||||
},
|
||||
"leave_message": "Goodbye user!"
|
||||
}
|
||||
|
||||
|
||||
# from modules.settings import instance as settings_manager
|
||||
# get current plugin settings
|
||||
# change "example" to your cog name
|
||||
settings: SettingsType = settings_manager.get_plugin_settings(COG_NAME, default=default_settings) #type: ignore[assignment]
|
||||
|
||||
# Now you can use settings easily!
|
||||
|
||||
current_message = settings["intro"]["message"]
|
||||
await send_message(ctx, message=f"Current message: {current_message}")
|
||||
|
||||
# Changing plugin settings
|
||||
settings["intro"]["message"] = "brand new message!"
|
||||
|
||||
settings_manager.set_plugin_setting(COG_NAME, settings)
|
||||
|
||||
new_message = settings["intro"]["message"]
|
||||
await send_message(ctx, message=f"New message: {new_message}")
|
||||
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(Example(bot))
|
|
@ -1,70 +0,0 @@
|
|||
import discord
|
||||
import discord.context_managers
|
||||
from discord.ext import commands
|
||||
import logging
|
||||
from typing import Literal, get_args, cast
|
||||
from modules.permission import requires_admin
|
||||
from modules.settings import instance as settings_manager
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
AvailableModes = Literal["r", "s"]
|
||||
|
||||
|
||||
class FileSync(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot: discord.Client = bot
|
||||
self.mode: AvailableModes | None = None
|
||||
self.peer_id = None
|
||||
self.awaiting_file = False
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def syncfile(self, ctx: commands.Context, mode: str, peer: discord.User):
|
||||
if self.mode not in get_args(AvailableModes):
|
||||
await ctx.send("Invalid mode, use 's' or 'r'.")
|
||||
return
|
||||
|
||||
self.mode = cast(AvailableModes, mode.lower())
|
||||
self.peer_id = peer.id
|
||||
|
||||
if self.mode == "s":
|
||||
await ctx.send(f"<@{self.peer_id}> FILE_TRANSFER_REQUEST")
|
||||
await ctx.send(file=discord.File(settings["bot"]["active_memory"]))
|
||||
await ctx.send("File sent in this channel.")
|
||||
|
||||
elif self.mode == "r":
|
||||
await ctx.send("Waiting for incoming file...")
|
||||
self.awaiting_file = True
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message: discord.Message):
|
||||
if message.author == self.bot.user or not self.awaiting_file:
|
||||
return
|
||||
|
||||
if message.author.id != self.peer_id:
|
||||
return
|
||||
|
||||
if message.content == "FILE_TRANSFER_REQUEST":
|
||||
logger.info("Ping received. Awaiting file...")
|
||||
if not message.attachments:
|
||||
return
|
||||
|
||||
for attachment in message.attachments:
|
||||
if not attachment.filename.endswith(".json"):
|
||||
continue
|
||||
|
||||
filename = "received_memory.json"
|
||||
with open(filename, "wb") as f:
|
||||
await attachment.save(f)
|
||||
|
||||
logger.info(f"File saved as {filename}")
|
||||
await message.channel.send("File received and saved.")
|
||||
self.awaiting_file = False
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(FileSync(bot))
|
|
@ -1,103 +0,0 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
from modules.image import *
|
||||
from PIL import Image, ImageEnhance, ImageFilter, ImageOps, ImageChops, ImageColor
|
||||
import os, random, shutil, tempfile
|
||||
import modules.keys as k
|
||||
|
||||
|
||||
async def deepfryimage(path):
|
||||
with Image.open(path).convert("RGB") as im:
|
||||
# make it burn
|
||||
for _ in range(3):
|
||||
im = im.resize((int(im.width * 0.7), int(im.height * 0.7)))
|
||||
im = im.resize((int(im.width * 1.5), int(im.height * 1.5)))
|
||||
im = ImageEnhance.Contrast(im).enhance(random.uniform(5, 10))
|
||||
im = ImageEnhance.Sharpness(im).enhance(random.uniform(10, 50))
|
||||
im = ImageEnhance.Brightness(im).enhance(random.uniform(1.5, 3))
|
||||
r, g, b = im.split()
|
||||
r = r.point(lambda i: min(255, i * random.uniform(1.2, 2.0)))
|
||||
g = g.point(lambda i: min(255, i * random.uniform(0.5, 1.5)))
|
||||
b = b.point(lambda i: min(255, i * random.uniform(0.5, 2.0)))
|
||||
channels = [r, g, b]
|
||||
random.shuffle(channels)
|
||||
im = Image.merge("RGB", tuple(channels))
|
||||
overlay_color = tuple(random.randint(0, 255) for _ in range(3))
|
||||
overlay = Image.new("RGB", im.size, overlay_color)
|
||||
im = ImageChops.add(im, overlay, scale=2.0, offset=random.randint(-64, 64))
|
||||
|
||||
im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
|
||||
im = im.filter(ImageFilter.GaussianBlur(radius=random.uniform(0.5, 2)))
|
||||
for _ in range(3):
|
||||
tmp_path = tempfile.mktemp(suffix=".jpg")
|
||||
im.save(tmp_path, format="JPEG", quality=random.randint(5, 15))
|
||||
im = Image.open(tmp_path)
|
||||
if random.random() < 0.3:
|
||||
im = ImageOps.posterize(im, bits=random.choice([2, 3, 4]))
|
||||
if random.random() < 0.2:
|
||||
im = ImageOps.invert(im)
|
||||
out_path = tempfile.mktemp(suffix=".jpg")
|
||||
im.save(out_path, format="JPEG", quality=5)
|
||||
return out_path
|
||||
|
||||
|
||||
class whami(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command()
|
||||
async def fuckup(self, ctx):
|
||||
assets_folder = "assets/images"
|
||||
temp_input = None
|
||||
|
||||
def get_random_asset_image():
|
||||
files = [
|
||||
f
|
||||
for f in os.listdir(assets_folder)
|
||||
if f.lower().endswith((".png", ".jpg", ".jpeg", ".webp"))
|
||||
]
|
||||
if not files:
|
||||
return None
|
||||
return os.path.join(assets_folder, random.choice(files))
|
||||
|
||||
if ctx.message.attachments:
|
||||
attachment = ctx.message.attachments[0]
|
||||
if attachment.content_type and attachment.content_type.startswith("image/"):
|
||||
ext = os.path.splitext(attachment.filename)[1]
|
||||
temp_input = f"tempy{ext}"
|
||||
await attachment.save(temp_input)
|
||||
input_path = temp_input
|
||||
else:
|
||||
fallback_image = get_random_asset_image()
|
||||
if fallback_image is None:
|
||||
await ctx.reply(k.no_image_available())
|
||||
return
|
||||
temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1])
|
||||
shutil.copy(fallback_image, temp_input)
|
||||
input_path = temp_input
|
||||
else:
|
||||
fallback_image = get_random_asset_image()
|
||||
if fallback_image is None:
|
||||
await ctx.reply(k.no_image_available())
|
||||
return
|
||||
temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1])
|
||||
shutil.copy(fallback_image, temp_input)
|
||||
input_path = temp_input
|
||||
|
||||
output_path = await gen_meme(input_path)
|
||||
|
||||
if output_path is None or not os.path.isfile(output_path):
|
||||
if temp_input and os.path.exists(temp_input):
|
||||
os.remove(temp_input)
|
||||
await ctx.reply(k.failed_generate_image())
|
||||
return
|
||||
|
||||
deepfried_path = await deepfryimage(output_path)
|
||||
await ctx.send(file=discord.File(deepfried_path))
|
||||
|
||||
if temp_input and os.path.exists(temp_input):
|
||||
os.remove(temp_input)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(whami(bot))
|
|
@ -1,231 +0,0 @@
|
|||
import os
|
||||
from typing import Dict, List
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
import discord.ext
|
||||
import discord.ext.commands
|
||||
import modules.keys as k
|
||||
from modules.permission import requires_admin
|
||||
from modules.sentenceprocessing import send_message
|
||||
from modules.settings import instance as settings_manager
|
||||
import requests
|
||||
import psutil
|
||||
import cpuinfo
|
||||
import sys
|
||||
import subprocess
|
||||
import updater
|
||||
from modules.sync_conenctor import instance as sync_connector
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
class BaseCommands(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot: discord.ext.commands.Bot = bot
|
||||
|
||||
@commands.command()
|
||||
async def help(self, ctx: commands.Context) -> None:
|
||||
embed: discord.Embed = discord.Embed(
|
||||
title=f"{k.command_help_embed_title()}",
|
||||
description=f"{k.command_help_embed_desc()}",
|
||||
color=discord.Colour(0x000000),
|
||||
)
|
||||
|
||||
command_categories = {
|
||||
f"{k.command_help_categories_general()}": [
|
||||
"mem",
|
||||
"talk",
|
||||
"about",
|
||||
"ping",
|
||||
"impact",
|
||||
"demotivator",
|
||||
"help",
|
||||
],
|
||||
f"{k.command_help_categories_admin()}": ["stats", "retrain", "setlanguage"],
|
||||
}
|
||||
|
||||
custom_commands: List[str] = []
|
||||
for cog_name, cog in self.bot.cogs.items():
|
||||
for command in cog.get_commands():
|
||||
if (
|
||||
command.name
|
||||
not in command_categories[f"{k.command_help_categories_general()}"]
|
||||
and command.name
|
||||
not in command_categories[f"{k.command_help_categories_admin()}"]
|
||||
):
|
||||
custom_commands.append(command.name)
|
||||
|
||||
if custom_commands:
|
||||
embed.add_field(
|
||||
name=f"{k.command_help_categories_custom()}",
|
||||
value="\n".join(
|
||||
[
|
||||
f"{settings['bot']['prefix']}{command}"
|
||||
for command in custom_commands
|
||||
]
|
||||
),
|
||||
inline=False,
|
||||
)
|
||||
|
||||
for category, commands_list in command_categories.items():
|
||||
commands_in_category: str = "\n".join(
|
||||
[f"{settings['bot']['prefix']}{command}" for command in commands_list]
|
||||
)
|
||||
embed.add_field(name=category, value=commands_in_category, inline=False)
|
||||
|
||||
await send_message(ctx, embed=embed)
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def setlanguage(self, ctx: commands.Context, locale: str) -> None:
|
||||
await ctx.defer()
|
||||
k.change_language(locale)
|
||||
|
||||
settings["locale"] = locale # type: ignore
|
||||
settings_manager.commit()
|
||||
|
||||
await ctx.send(":thumbsup:")
|
||||
|
||||
@commands.command()
|
||||
async def ping(self, ctx: commands.Context) -> None:
|
||||
await ctx.defer()
|
||||
latency: int = round(self.bot.latency * 1000)
|
||||
|
||||
embed: discord.Embed = discord.Embed(
|
||||
title="Pong!!",
|
||||
description=(
|
||||
settings["bot"]["misc"]["ping_line"],
|
||||
f"`{k.command_ping_embed_desc()}: {latency}ms`\n",
|
||||
),
|
||||
color=discord.Colour(0x000000),
|
||||
)
|
||||
embed.set_footer(
|
||||
text=f"{k.command_ping_footer()} {ctx.author.name}",
|
||||
icon_url=ctx.author.display_avatar.url,
|
||||
)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@commands.command()
|
||||
async def about(self, ctx: commands.Context) -> None:
|
||||
embed: discord.Embed = discord.Embed(
|
||||
title=k.command_about_embed_title(),
|
||||
description="",
|
||||
color=discord.Colour(0x000000),
|
||||
)
|
||||
|
||||
embed.add_field(
|
||||
name=k.command_about_embed_field1(),
|
||||
value=settings['name'],
|
||||
inline=False,
|
||||
)
|
||||
|
||||
embed.add_field(name="Github", value=f"https://github.com/gooberinc/goober")
|
||||
await send_message(ctx, embed=embed)
|
||||
|
||||
@commands.command()
|
||||
async def stats(self, ctx: commands.Context) -> None:
|
||||
memory_file: str = settings["bot"]["active_memory"]
|
||||
file_size: int = os.path.getsize(memory_file)
|
||||
|
||||
memory_info = psutil.virtual_memory() # type: ignore
|
||||
total_memory = memory_info.total / (1024**3)
|
||||
used_memory = memory_info.used / (1024**3)
|
||||
|
||||
|
||||
cpu_name = cpuinfo.get_cpu_info()["brand_raw"]
|
||||
|
||||
|
||||
with open(memory_file, "r") as file:
|
||||
line_count: int = sum(1 for _ in file)
|
||||
|
||||
embed: discord.Embed = discord.Embed(
|
||||
title=f"{k.command_stats_embed_title()}",
|
||||
description=f"{k.command_stats_embed_desc()}",
|
||||
color=discord.Colour(0x000000),
|
||||
)
|
||||
embed.add_field(
|
||||
name=f"{k.command_stats_embed_field1name()}",
|
||||
value=f"{k.command_stats_embed_field1value(file_size=file_size, line_count=line_count)}",
|
||||
inline=False,
|
||||
)
|
||||
|
||||
embed.add_field(
|
||||
name=k.system_info(),
|
||||
value=f"""
|
||||
{k.memory_usage(used=round(used_memory,2), total=round(total_memory,2), percent=round(used_memory/total_memory * 100))}
|
||||
{k.cpu_info(cpu_name)}
|
||||
"""
|
||||
)
|
||||
|
||||
with open(settings["splash_text_loc"], "r") as f:
|
||||
splash_text = "".join(f.readlines())
|
||||
|
||||
embed.add_field(
|
||||
name=f"{k.command_stats_embed_field3name()}",
|
||||
value=f"""{k.command_stats_embed_field3value(
|
||||
NAME=settings["name"], PREFIX=settings["bot"]["prefix"], ownerid=settings["bot"]["owner_ids"][0],
|
||||
PING_LINE=settings["bot"]["misc"]["ping_line"], showmemenabled=settings["bot"]["allow_show_mem_command"],
|
||||
USERTRAIN_ENABLED=settings["bot"]["user_training"], song=settings["bot"]["misc"]["activity"]["content"],
|
||||
splashtext=splash_text
|
||||
)}""",
|
||||
inline=False,
|
||||
)
|
||||
|
||||
await send_message(ctx, embed=embed)
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def restart(self, ctx: commands.Context):
|
||||
await ctx.send("Restarting...")
|
||||
os.execv(sys.executable, [sys.executable] + sys.argv)
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def force_update(self, ctx: commands.Context):
|
||||
await ctx.send("Forcefully updating...")
|
||||
updater.force_update()
|
||||
os.execv(sys.executable, [sys.executable] + sys.argv)
|
||||
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def mem(self, ctx: commands.Context) -> None:
|
||||
if not settings["bot"]["allow_show_mem_command"]:
|
||||
return
|
||||
|
||||
with open(settings["bot"]["active_memory"], "rb") as f:
|
||||
data: bytes = f.read()
|
||||
|
||||
response = requests.post(
|
||||
"https://litterbox.catbox.moe/resources/internals/api.php",
|
||||
data={"reqtype": "fileupload", "time": "1h"},
|
||||
files={"fileToUpload": data},
|
||||
)
|
||||
|
||||
await send_message(ctx, response.text)
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def test_synchub(self, ctx: commands.Context, message_id: str | None) -> None:
|
||||
message_id = message_id or "0"
|
||||
status = sync_connector.can_react(int(message_id))
|
||||
|
||||
await send_message(ctx, f"Is allowed to react to message id {message_id}? {status} (connection active? {sync_connector.connected})")
|
||||
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def connect_synchub(self, ctx: commands.Context) -> None:
|
||||
await send_message(ctx, "Trying to connect...")
|
||||
|
||||
connected = sync_connector.try_to_connect()
|
||||
if connected:
|
||||
await send_message(ctx, "Succesfully connected to sync hub!")
|
||||
else:
|
||||
await send_message(ctx, "Failed to connect to sync hub")
|
||||
|
||||
async def setup(bot: discord.ext.commands.Bot):
|
||||
print("Setting up base_commands")
|
||||
bot.remove_command("help")
|
||||
await bot.add_cog(BaseCommands(bot))
|
|
@ -1,129 +0,0 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
import discord.ext
|
||||
import discord.ext.commands
|
||||
from modules.permission import requires_admin
|
||||
from modules.settings import instance as settings_manager
|
||||
from modules.globalvars import available_cogs
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
COG_PREFIX = "assets.cogs."
|
||||
|
||||
|
||||
class CogManager(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def enable(self, ctx, cog_name: str):
|
||||
try:
|
||||
await self.bot.load_extension(COG_PREFIX + cog_name)
|
||||
await ctx.send(f"Loaded cog `{cog_name}` successfully.")
|
||||
settings["bot"]["enabled_cogs"].append(cog_name)
|
||||
settings_manager.add_admin_log_event(
|
||||
{
|
||||
"action": "add",
|
||||
"author": ctx.author.id,
|
||||
"change": "enabled_cogs",
|
||||
"messageId": ctx.message.id,
|
||||
"target": cog_name,
|
||||
}
|
||||
)
|
||||
settings_manager.commit()
|
||||
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error enabling cog `{cog_name}`: {e}")
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def load(self, ctx, cog_name: str | None = None):
|
||||
if cog_name is None:
|
||||
await ctx.send("Give cog_name")
|
||||
return
|
||||
|
||||
if cog_name[:-3] not in settings["bot"]["enabled_cogs"]:
|
||||
await ctx.send("Please enable the cog first!")
|
||||
return
|
||||
if cog_name is None:
|
||||
await ctx.send("Please provide the cog name to load.")
|
||||
return
|
||||
try:
|
||||
await self.bot.load_extension(COG_PREFIX + cog_name)
|
||||
await ctx.send(f"Loaded cog `{cog_name}` successfully.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error loading cog `{cog_name}`: {e}")
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def unload(self, ctx, cog_name: str | None = None):
|
||||
if cog_name is None:
|
||||
await ctx.send("Please provide the cog name to unload.")
|
||||
return
|
||||
try:
|
||||
await self.bot.unload_extension(COG_PREFIX + cog_name)
|
||||
await ctx.send(f"Unloaded cog `{cog_name}` successfully.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error unloading cog `{cog_name}`: {e}")
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def disable(self, ctx, cog_name: str | None = None):
|
||||
if cog_name is None:
|
||||
await ctx.send("Please provide the cog name to disable.")
|
||||
return
|
||||
try:
|
||||
await self.bot.unload_extension(COG_PREFIX + cog_name)
|
||||
await ctx.send(f"Unloaded cog `{cog_name}` successfully.")
|
||||
settings["bot"]["enabled_cogs"].remove(cog_name)
|
||||
settings_manager.add_admin_log_event(
|
||||
{
|
||||
"action": "del",
|
||||
"author": ctx.author.id,
|
||||
"change": "enabled_cogs",
|
||||
"messageId": ctx.message.id,
|
||||
"target": cog_name,
|
||||
}
|
||||
)
|
||||
settings_manager.commit()
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error unloading cog `{cog_name}`: {e}")
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def reload(self, ctx, cog_name: str | None = None):
|
||||
if cog_name is None:
|
||||
await ctx.send("Please provide the cog name to reload.")
|
||||
return
|
||||
|
||||
if cog_name[:-3] not in settings["bot"]["enabled_cogs"]:
|
||||
await ctx.send("Please enable the cog first!")
|
||||
return
|
||||
try:
|
||||
await self.bot.unload_extension(COG_PREFIX + cog_name)
|
||||
await self.bot.load_extension(COG_PREFIX + cog_name)
|
||||
await ctx.send(f"Reloaded cog `{cog_name}` successfully.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error reloading cog `{cog_name}`: {e}")
|
||||
|
||||
@commands.command()
|
||||
async def listcogs(self, ctx):
|
||||
"""Lists all currently loaded cogs in an embed."""
|
||||
cogs = list(self.bot.cogs.keys())
|
||||
if not cogs:
|
||||
await ctx.send("No cogs are currently loaded.")
|
||||
return
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Loaded Cogs",
|
||||
description="Here is a list of all currently loaded cogs:",
|
||||
)
|
||||
embed.add_field(name="Loaded cogs", value="\n".join(cogs), inline=False)
|
||||
embed.add_field(name="Available cogs", value="\n".join(available_cogs()))
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(CogManager(bot))
|
|
@ -1,123 +0,0 @@
|
|||
import os
|
||||
import random
|
||||
import re
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
import discord.ext
|
||||
import discord.ext.commands
|
||||
|
||||
from modules.markovmemory import (
|
||||
load_markov_model,
|
||||
save_markov_model,
|
||||
train_markov_model,
|
||||
)
|
||||
from modules.permission import requires_admin
|
||||
from modules.sentenceprocessing import (
|
||||
improve_sentence_coherence,
|
||||
is_positive,
|
||||
rephrase_for_coherence,
|
||||
send_message,
|
||||
)
|
||||
import modules.keys as k
|
||||
import logging
|
||||
from typing import List, Optional, Set
|
||||
import json
|
||||
import time
|
||||
import markovify
|
||||
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
from modules.settings import instance as settings_manager
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
class Markov(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot: discord.ext.commands.Bot = bot
|
||||
|
||||
self.model: markovify.NewlineText | None = load_markov_model()
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def retrain(self, ctx: discord.ext.commands.Context):
|
||||
message_ref: discord.Message | None = await send_message(
|
||||
ctx, f"{k.command_markov_retrain()}"
|
||||
)
|
||||
|
||||
if message_ref is None:
|
||||
logger.error("Failed to send message!")
|
||||
return
|
||||
|
||||
try:
|
||||
with open(settings["bot"]["active_memory"], "r") as f:
|
||||
memory: List[str] = json.load(f)
|
||||
except FileNotFoundError:
|
||||
await send_message(ctx, f"{k.command_markov_memory_not_found()}")
|
||||
return
|
||||
except json.JSONDecodeError:
|
||||
await send_message(ctx, f"{k.command_markov_memory_is_corrupt()}")
|
||||
return
|
||||
|
||||
data_size: int = len(memory)
|
||||
|
||||
processing_message_ref: discord.Message | None = await send_message(
|
||||
ctx, f"{k.command_markov_retraining(data_size)}"
|
||||
)
|
||||
if processing_message_ref is None:
|
||||
logger.error("Couldnt find message processing message!")
|
||||
|
||||
start_time: float = time.time()
|
||||
|
||||
model = train_markov_model(memory)
|
||||
if not model:
|
||||
logger.error("Failed to train markov model")
|
||||
await ctx.send("Failed to retrain!")
|
||||
return False
|
||||
|
||||
self.model = model
|
||||
save_markov_model(self.model)
|
||||
|
||||
logger.debug(f"Completed retraining in {round(time.time() - start_time,3)}s")
|
||||
|
||||
await send_message(
|
||||
ctx,
|
||||
f"{k.command_markov_retrain_successful(data_size)}",
|
||||
edit=True,
|
||||
message_reference=processing_message_ref,
|
||||
)
|
||||
|
||||
@commands.command()
|
||||
async def talk(self, ctx: commands.Context, sentence_size: int = 5) -> None:
|
||||
if not self.model:
|
||||
await send_message(ctx, f"{k.command_talk_insufficent_text()}")
|
||||
return
|
||||
|
||||
response: str = ""
|
||||
if sentence_size == 1:
|
||||
response = (
|
||||
self.model.make_short_sentence(max_chars=200, tries=700)
|
||||
or k.command_talk_generation_fail()
|
||||
)
|
||||
|
||||
else:
|
||||
response = improve_sentence_coherence(
|
||||
self.model.make_sentence(tries=100, max_words=sentence_size)
|
||||
or k.command_talk_generation_fail()
|
||||
)
|
||||
|
||||
cleaned_response: str = re.sub(r"[^\w\s]", "", response).lower()
|
||||
coherent_response: str = rephrase_for_coherence(cleaned_response)
|
||||
|
||||
if random.random() < 0.9 and is_positive(coherent_response):
|
||||
gif_url: str = random.choice(settings["bot"]["misc"]["positive_gifs"])
|
||||
|
||||
coherent_response = f"{coherent_response}\n[jif]({gif_url})"
|
||||
|
||||
os.environ["gooberlatestgen"] = coherent_response
|
||||
await send_message(ctx, coherent_response)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(Markov(bot))
|
|
@ -1,118 +0,0 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
from modules.permission import requires_admin
|
||||
from modules.settings import instance as settings_manager
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
class PermissionManager(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def add_owner(self, ctx: commands.Context, member: discord.Member):
|
||||
settings["bot"]["owner_ids"].append(member.id)
|
||||
settings_manager.add_admin_log_event(
|
||||
{
|
||||
"action": "add",
|
||||
"author": ctx.author.id,
|
||||
"change": "owner_ids",
|
||||
"messageId": ctx.message.id,
|
||||
"target": member.id,
|
||||
}
|
||||
)
|
||||
|
||||
settings_manager.commit()
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Permissions",
|
||||
description=f"Set {member.name} as an owner",
|
||||
color=discord.Color.blue(),
|
||||
)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def remove_owner(self, ctx: commands.Context, member: discord.Member):
|
||||
try:
|
||||
settings["bot"]["owner_ids"].remove(member.id)
|
||||
settings_manager.add_admin_log_event(
|
||||
{
|
||||
"action": "del",
|
||||
"author": ctx.author.id,
|
||||
"change": "owner_ids",
|
||||
"messageId": ctx.message.id,
|
||||
"target": member.id,
|
||||
}
|
||||
)
|
||||
settings_manager.commit()
|
||||
except ValueError:
|
||||
await ctx.send("User is not an owner!")
|
||||
return
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Permissions",
|
||||
description=f"Removed {member.name} from being an owner",
|
||||
color=discord.Color.blue(),
|
||||
)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def blacklist_user(self, ctx: commands.Context, member: discord.Member):
|
||||
settings["bot"]["blacklisted_users"].append(member.id)
|
||||
settings_manager.add_admin_log_event(
|
||||
{
|
||||
"action": "add",
|
||||
"author": ctx.author.id,
|
||||
"change": "blacklisted_users",
|
||||
"messageId": ctx.message.id,
|
||||
"target": member.id,
|
||||
}
|
||||
)
|
||||
settings_manager.commit()
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Blacklist",
|
||||
description=f"Added {member.name} to the blacklist",
|
||||
color=discord.Color.blue(),
|
||||
)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def unblacklist_user(self, ctx: commands.Context, member: discord.Member):
|
||||
try:
|
||||
settings["bot"]["blacklisted_users"].remove(member.id)
|
||||
settings_manager.add_admin_log_event(
|
||||
{
|
||||
"action": "del",
|
||||
"author": ctx.author.id,
|
||||
"change": "blacklisted_users",
|
||||
"messageId": ctx.message.id,
|
||||
"target": member.id,
|
||||
}
|
||||
)
|
||||
settings_manager.commit()
|
||||
|
||||
except ValueError:
|
||||
await ctx.send("User is not on the blacklist!")
|
||||
return
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Blacklist",
|
||||
description=f"Removed {member.name} from blacklist",
|
||||
color=discord.Color.blue(),
|
||||
)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(PermissionManager(bot))
|
|
@ -1,94 +0,0 @@
|
|||
import os
|
||||
import discord
|
||||
from discord.ext import commands, tasks
|
||||
import aiohttp
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# stole most of this code from my old expect bot so dont be suprised if its poorly made
|
||||
|
||||
LASTFM_API_KEY = os.getenv("LASTFM_API_KEY")
|
||||
LASTFM_USERNAME = os.getenv("LASTFM_USERNAME")
|
||||
|
||||
|
||||
class LastFmCog(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.current_track = None
|
||||
self.update_presence_task = None
|
||||
self.ready = False
|
||||
bot.loop.create_task(self.wait_until_ready())
|
||||
|
||||
async def wait_until_ready(self):
|
||||
await self.bot.wait_until_ready()
|
||||
self.ready = True
|
||||
self.update_presence.start()
|
||||
|
||||
@tasks.loop(seconds=60)
|
||||
async def update_presence(self):
|
||||
print("Looped!")
|
||||
if not self.ready:
|
||||
return
|
||||
track = await self.fetch_current_track()
|
||||
if track and track != self.current_track:
|
||||
self.current_track = track
|
||||
artist, song = track
|
||||
activity_name = f"{artist} - {song}"
|
||||
await self.bot.change_presence(
|
||||
activity=discord.Activity(
|
||||
type=discord.ActivityType.listening, name=activity_name
|
||||
)
|
||||
)
|
||||
print(f"Updated song to {artist} - {song}")
|
||||
else:
|
||||
print("LastFM gave me the same track! not updating...")
|
||||
|
||||
@update_presence.before_loop
|
||||
async def before_update_presence(self):
|
||||
await self.bot.wait_until_ready()
|
||||
|
||||
@commands.command(name="lastfm")
|
||||
async def lastfm_command(self, ctx):
|
||||
track = await self.fetch_current_track()
|
||||
if not track:
|
||||
await ctx.send("No track currently playing or could not fetch data")
|
||||
return
|
||||
self.current_track = track
|
||||
artist, song = track
|
||||
activity_name = f"{artist} - {song}"
|
||||
await self.bot.change_presence(
|
||||
activity=discord.Activity(
|
||||
type=discord.ActivityType.listening, name=activity_name
|
||||
)
|
||||
)
|
||||
await ctx.send(f"Updated presence to: Listening to {activity_name}")
|
||||
|
||||
async def fetch_current_track(self):
|
||||
url = (
|
||||
f"http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks"
|
||||
f"&user={LASTFM_USERNAME}&api_key={LASTFM_API_KEY}&format=json&limit=1"
|
||||
)
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as resp:
|
||||
if resp.status != 200:
|
||||
return None
|
||||
data = await resp.json()
|
||||
|
||||
recenttracks = data.get("recenttracks", {}).get("track", [])
|
||||
if not recenttracks:
|
||||
return None
|
||||
|
||||
track = recenttracks[0]
|
||||
if "@attr" in track and track["@attr"].get("nowplaying") == "true":
|
||||
artist = track.get("artist", {}).get("#text", "Unknown Artist")
|
||||
song = track.get("name", "Unknown Song")
|
||||
return artist, song
|
||||
return None
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
if not LASTFM_API_KEY or not LASTFM_USERNAME:
|
||||
return
|
||||
else:
|
||||
await bot.add_cog(LastFmCog(bot))
|
|
@ -1,87 +0,0 @@
|
|||
from discord.ext import commands
|
||||
import discord
|
||||
from collections import defaultdict, Counter
|
||||
import datetime
|
||||
from modules.permission import requires_admin
|
||||
from modules.settings import instance as settings_manager
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
class StatsCog(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.start_time = datetime.datetime.utcnow()
|
||||
self.active_users = set()
|
||||
self.total_messages = 0
|
||||
self.command_usage = Counter()
|
||||
self.user_message_counts = Counter()
|
||||
self.messages_per_hour = defaultdict(int)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message):
|
||||
if message.author.bot:
|
||||
return
|
||||
self.active_users.add(message.author.id)
|
||||
self.total_messages += 1
|
||||
self.user_message_counts[message.author.id] += 1
|
||||
|
||||
now = datetime.datetime.utcnow()
|
||||
hour_key = now.strftime("%Y-%m-%d %H")
|
||||
self.messages_per_hour[hour_key] += 1
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_command(self, ctx):
|
||||
self.command_usage[ctx.command.qualified_name] += 1
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def spyware(self, ctx):
|
||||
uptime = datetime.datetime.utcnow() - self.start_time
|
||||
hours_elapsed = max((uptime.total_seconds() / 3600), 1)
|
||||
avg_per_hour = self.total_messages / hours_elapsed
|
||||
if self.messages_per_hour:
|
||||
peak_hour, peak_count = max(
|
||||
self.messages_per_hour.items(), key=lambda x: x[1]
|
||||
)
|
||||
else:
|
||||
peak_hour, peak_count = "N/A", 0
|
||||
|
||||
top_users = self.user_message_counts.most_common(5)
|
||||
|
||||
embed = discord.Embed(title="Community Stats", color=discord.Color.blue())
|
||||
embed.add_field(name="Uptime", value=str(uptime).split(".")[0], inline=False)
|
||||
embed.add_field(
|
||||
name="Total Messages", value=str(self.total_messages), inline=True
|
||||
)
|
||||
embed.add_field(
|
||||
name="Active Users", value=str(len(self.active_users)), inline=True
|
||||
)
|
||||
embed.add_field(
|
||||
name="Avg Messages/Hour", value=f"{avg_per_hour:.2f}", inline=True
|
||||
)
|
||||
embed.add_field(
|
||||
name="Peak Hour (UTC)",
|
||||
value=f"{peak_hour}: {peak_count} messages",
|
||||
inline=True,
|
||||
)
|
||||
|
||||
top_str = (
|
||||
"\n".join(f"<@{user_id}>: {count} messages" for user_id, count in top_users)
|
||||
or "No data"
|
||||
)
|
||||
embed.add_field(name="Top Chatters", value=top_str, inline=False)
|
||||
|
||||
cmd_str = (
|
||||
"\n".join(
|
||||
f"{cmd}: {count}" for cmd, count in self.command_usage.most_common(5)
|
||||
)
|
||||
or "No commands used yet"
|
||||
)
|
||||
embed.add_field(name="Top Commands", value=cmd_str, inline=False)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(StatsCog(bot))
|
Before Width: | Height: | Size: 114 KiB |
Before Width: | Height: | Size: 295 KiB |
Before Width: | Height: | Size: 2.2 MiB |
BIN
assets/images/cache/breaking_news.png
vendored
Before Width: | Height: | Size: 2.3 MiB |
Before Width: | Height: | Size: 155 KiB |
Before Width: | Height: | Size: 746 KiB |
Before Width: | Height: | Size: 355 KiB |
Before Width: | Height: | Size: 275 KiB |
Before Width: | Height: | Size: 1.7 MiB |
|
@ -1,8 +0,0 @@
|
|||
# Locales Directory
|
||||
|
||||
This folder contains localization files for the project.
|
||||
|
||||
**Notice:**
|
||||
The Spanish and French locales currently do not have maintainers. If you are interested in helping maintain or improve these translations, please consider contributing!
|
||||
|
||||
Thank you for supporting localization efforts!
|
|
@ -1,3 +0,0 @@
|
|||
{
|
||||
|
||||
}
|
|
@ -1,144 +0,0 @@
|
|||
{
|
||||
"memory_file_valid": "The memory.json file is valid!",
|
||||
"file_aint_uft8": "File is not valid UTF-8 text. Might be binary or corrupted.",
|
||||
"psutil_not_installed": "Memory check skipped.",
|
||||
"not_cloned": "Goober is not cloned! Please clone it from GitHub.",
|
||||
"checks_disabled": "Checks are disabled!",
|
||||
"unhandled_exception": "An unhandled exception occurred. Please report this issue on GitHub.",
|
||||
"active_users:": "Active users:",
|
||||
"spacy_initialized": "spaCy and spacytextblob are ready.",
|
||||
"spacy_model_not_found": "The spaCy model was not found! Downloading it....`",
|
||||
"env_file_not_found": "The .env file was not found! Please create one with the required variables.",
|
||||
"error_fetching_active_users": "Error fetching active users: {error}",
|
||||
"error_sending_alive_ping": "Error sending alive ping: {error}",
|
||||
"already_started": "I've already started! I'm not updating...",
|
||||
"please_restart": "Please Restart goober!",
|
||||
"local_ahead": "Local {remote}/{branch} is ahead and/or up to par. Not Updating...",
|
||||
"remote_ahead": "Remote {remote}/{branch} is ahead. Updating...",
|
||||
"cant_find_local_version": "I can't find the local_version variable! Or it's been tampered with and it's not an integer!",
|
||||
"running_prestart_checks": "Running pre-start checks...",
|
||||
"continuing_in_seconds": "Continuing in {seconds} seconds... Press any key to skip.",
|
||||
"missing_requests_psutil": "Missing requests and psutil! Please install them using pip: `pip install requests psutil`",
|
||||
"requirements_not_found": "requirements.txt not found at {path} was it tampered with?",
|
||||
"warning_failed_parse_imports": "Warning: Failed to parse imports from {filename}: {error}",
|
||||
"cogs_dir_not_found": "Cogs directory not found at {path}, skipping scan.",
|
||||
"std_lib_local_skipped": "STD LIB / LOCAL {package} (skipped check)",
|
||||
"ok_installed": "OK",
|
||||
"missing_package": "MISSING",
|
||||
"missing_package2": "is not installed",
|
||||
"missing_packages_detected": "Missing packages detected:",
|
||||
"telling_goober_central": "Telling goober central at {url}",
|
||||
"failed_to_contact": "Failed to contact {url}: {error}",
|
||||
"all_requirements_satisfied": "All requirements are satisfied.",
|
||||
"ping_to": "Ping to {host}: {latency} ms",
|
||||
"high_latency": "High latency detected! You may experience delays in response times.",
|
||||
"could_not_parse_latency": "Could not parse latency.",
|
||||
"ping_failed": "Ping to {host} failed.",
|
||||
"error_running_ping": "Error running ping: {error}",
|
||||
"memory_usage": "Memory Usage: {used} GB / {total} GB ({percent}%)",
|
||||
"memory_above_90": "Memory usage is above 90% ({percent}%). Consider freeing up memory.",
|
||||
"total_memory": "Total Memory: {total} GB",
|
||||
"used_memory": "Used Memory: {used} GB",
|
||||
"low_free_memory": "Low free memory detected! Only {free} GB available.",
|
||||
"measuring_cpu": "Measuring CPU usage per core...",
|
||||
"core_usage": "Core {idx}: [{bar}] {usage}%",
|
||||
"total_cpu_usage": "Total CPU Usage: {usage}%",
|
||||
"high_avg_cpu": "High average CPU usage: {usage}%",
|
||||
"really_high_cpu": "Really high CPU load! System may throttle or hang.",
|
||||
"memory_file": "Memory file: {size} MB",
|
||||
"memory_file_large": "Memory file is 1GB or higher, consider clearing it to free up space.",
|
||||
"memory_file_corrupted": "Memory file is corrupted! JSON decode error: {error}",
|
||||
"consider_backup_memory": "Consider backing up and recreating the memory file.",
|
||||
"memory_file_encoding": "Memory file has encoding issues: {error}",
|
||||
"error_reading_memory": "Error reading memory file: {error}",
|
||||
"memory_file_not_found": "Memory file not found.",
|
||||
"modification_warning": "Goober has been modified! Any changes will be lost in an update!",
|
||||
"reported_version": "Reported Version:",
|
||||
"current_hash": "Current Hash:",
|
||||
"not_found": "is not found!",
|
||||
"version_error": "Unable to fetch version info. Status code",
|
||||
"loaded_cog": "Loaded cog:",
|
||||
"loaded_cog2": "Loaded module:",
|
||||
"cog_fail": "Failed to load cog:",
|
||||
"cog_fail2": "Failed to load module:",
|
||||
"no_model": "No saved Markov model found. Starting from scratch.",
|
||||
"folder_created": "Folder '{folder_name}' created.",
|
||||
"folder_exists": "Folder '{folder_name}' already exists. skipping...",
|
||||
"logged_in": "Logged in as",
|
||||
"synced_commands": "Synced",
|
||||
"synced_commands2": "commands!",
|
||||
"fail_commands_sync": "Failed to sync commands:",
|
||||
"started": "{name} has started!\nYou're the star of the show now baby!",
|
||||
"name_check": "Error checking name availability:",
|
||||
"name_taken": "Name is already taken. Please choose a different name.",
|
||||
"name_check2": "Error during name availability check:",
|
||||
"add_token": "Token: {token}\nPlease add this token to your .env file as",
|
||||
"token_exists": "Token already exists in .env. Continuing with the existing token.",
|
||||
"registration_error": "Error during registration:",
|
||||
"version_backup": "Backup created:",
|
||||
"backup_error": "Error: {LOCAL_VERSION_FILE} not found for backup.",
|
||||
"model_loaded": "Markov model loaded from",
|
||||
"fetch_update_fail": "Could not fetch update information.",
|
||||
"invalid_server": "Error: Invalid version information received from server.",
|
||||
"goober_server_alert": "Alert from goober central!\n",
|
||||
"new_version": "New version available: {latest_version} (Current: {local_version})",
|
||||
"changelog": "Check {VERSION_URL}/goob/changes.txt to check out the changelog\n\n",
|
||||
"invalid_version": "The version: {local_version} isnt valid!",
|
||||
"invalid_version2": "If this is intended then ignore this message, else press Y to pull a valid version from the server regardless of the version of goober currently running",
|
||||
"invalid_version3": "The current version will be backed up to current_version.bak..",
|
||||
"input": "(Y or any other key to ignore....)",
|
||||
"modification_ignored": "You've modified",
|
||||
"modification_ignored2": "IGNOREWARNING is set to false..",
|
||||
"latest_version": "You're using the latest version:",
|
||||
"latest_version2": "Check {VERSION_URL}/goob/changes.txt to check out the changelog",
|
||||
"pinging_disabled": "Pinging is disabled! Not telling the server im on...",
|
||||
"goober_ping_success": "Logged into goober central as {NAME}",
|
||||
"goober_ping_fail": "Failed to send data. Server returned status code:",
|
||||
"goober_ping_fail2": "An error occurred while sending data:",
|
||||
"sentence_positivity": "Positivity of sentence is:",
|
||||
"command_edit_fail": "Failed to edit message:",
|
||||
"command_desc_retrain": "Retrains the Markov model manually.",
|
||||
"command_markov_retrain": "Retraining the Markov model... Please wait.",
|
||||
"command_markov_memory_not_found": "Error: memory file not found!",
|
||||
"command_markov_memory_is_corrupt": "Error: memory file is corrupt!",
|
||||
"command_markov_retraining": "Processing {data_size} data points...",
|
||||
"command_markov_retrain_successful": "Markov model retrained successfully using {data_size} data points!",
|
||||
"command_desc_talk":"talks n like stuf",
|
||||
"command_talk_insufficent_text": "I need to learn more from messages before I can talk.",
|
||||
"command_talk_generation_fail": "I have nothing to say right now!",
|
||||
"command_desc_help": "help",
|
||||
"command_help_embed_title": "Bot Help",
|
||||
"command_help_embed_desc": "List of commands grouped by category.",
|
||||
"command_help_categories_general": "General",
|
||||
"command_help_categories_admin": "Administration",
|
||||
"command_help_categories_custom": "Custom Commands",
|
||||
"command_ran": "Info: {message.author.name} ran {message.content}",
|
||||
"command_ran_s": "Info: {interaction.user} ran ",
|
||||
"command_desc_ping": "ping",
|
||||
"command_desc_setlang": "Set a new language for the bot (temporarily)",
|
||||
"command_ping_embed_desc": "Bot Latency:",
|
||||
"command_ping_footer": "Requested by",
|
||||
"command_about_desc": "about",
|
||||
"command_about_embed_title": "About me",
|
||||
"command_about_embed_field1": "Name",
|
||||
"command_about_embed_field2name": "Version",
|
||||
"command_about_embed_field2value": "Local: {local_version} \nLatest: {latest_version}",
|
||||
"command_desc_stats": "stats",
|
||||
"command_stats_embed_title": "Bot stats",
|
||||
"command_stats_embed_desc": "Data about the the bot's memory.",
|
||||
"command_stats_embed_field1name": "File Stats",
|
||||
"command_stats_embed_field1value": "Size: {file_size} bytes\nLines: {line_count}",
|
||||
"command_stats_embed_field2name": "Version",
|
||||
"command_stats_embed_field2value": "Local: {local_version} \nLatest: {latest_version}",
|
||||
"command_stats_embed_field3name": "Variable Info",
|
||||
"command_stats_embed_field3value": "Name: {NAME} \nPrefix: {PREFIX} \nOwner ID: {ownerid}\nPing line: {PING_LINE} \nMemory Sharing Enabled: {showmemenabled} \nUser Training Enabled: {USERTRAIN_ENABLED}\nSong: {song} \nSplashtext: ```{splashtext}```",
|
||||
"no_image_available": "No images available!",
|
||||
"failed_generate_image": "Failed to generate an image",
|
||||
"markov_model_not_found": "Markov model not found!",
|
||||
"blacklisted": "blacklisted",
|
||||
"blacklisted_user": "Blacklisted user",
|
||||
"edit_fail": "Failed to edit message",
|
||||
"system_info": "System information",
|
||||
"cpu_info": "CPU: {cpu}"
|
||||
}
|
||||
|
|
@ -1,130 +0,0 @@
|
|||
{
|
||||
"checks_disabled": "Les vérifications sont désactivées !",
|
||||
"unhandled_exception": "Une exception non gérée est survenue. Merci de rapporter ce problème sur GitHub.",
|
||||
"active_users:": "Utilisateurs actifs :",
|
||||
"spacy_initialized": "spaCy et spacytextblob sont prêts.",
|
||||
"spacy_model_not_found": "Le modèle spaCy est introuvable ! Téléchargement en cours...",
|
||||
"env_file_not_found": "Le fichier .env est introuvable ! Créez-en un avec les variables nécessaires.",
|
||||
"error_fetching_active_users": "Erreur lors de la récupération des utilisateurs actifs : {error}",
|
||||
"error_sending_alive_ping": "Erreur lors de l’envoi du ping actif : {error}",
|
||||
"already_started": "J’ai déjà démarré ! Je ne me mets pas à jour...",
|
||||
"please_restart": "Redémarre, stp !",
|
||||
"local_ahead": "Local {remote}/{branch} est en avance ou à jour. Pas de mise à jour...",
|
||||
"remote_ahead": "Remote {remote}/{branch} est en avance. Mise à jour en cours...",
|
||||
"cant_find_local_version": "Je ne trouve pas la variable local_version ! Ou elle a été modifiée et ce n’est pas un entier !",
|
||||
"running_prestart_checks": "Exécution des vérifications préalables au démarrage...",
|
||||
"continuing_in_seconds": "Reprise dans {seconds} secondes... Appuie sur une touche pour passer.",
|
||||
"missing_requests_psutil": "requests et psutil manquants ! Installe-les avec pip : `pip install requests psutil`",
|
||||
"requirements_not_found": "requirements.txt introuvable à {path}, a-t-il été modifié ?",
|
||||
"warning_failed_parse_imports": "Avertissement : Échec du parsing des imports depuis {filename} : {error}",
|
||||
"cogs_dir_not_found": "Répertoire des cogs introuvable à {path}, scan ignoré.",
|
||||
"std_lib_local_skipped": "LIB STD / LOCAL {package} (vérification sautée)",
|
||||
"ok_installed": "OK",
|
||||
"missing_package": "MANQUANT",
|
||||
"missing_package2": "n’est pas installé",
|
||||
"missing_packages_detected": "Packages manquants détectés :",
|
||||
"telling_goober_central": "Envoi à goober central à {url}",
|
||||
"failed_to_contact": "Impossible de contacter {url} : {error}",
|
||||
"all_requirements_satisfied": "Toutes les dépendances sont satisfaites.",
|
||||
"ping_to": "Ping vers {host} : {latency} ms",
|
||||
"high_latency": "Latence élevée détectée ! Tu pourrais avoir des délais de réponse.",
|
||||
"could_not_parse_latency": "Impossible d’analyser la latence.",
|
||||
"ping_failed": "Ping vers {host} échoué.",
|
||||
"error_running_ping": "Erreur lors du ping : {error}",
|
||||
"memory_usage": "Utilisation mémoire : {used} Go / {total} Go ({percent}%)",
|
||||
"memory_above_90": "Usage mémoire au-dessus de 90% ({percent}%). Pense à libérer de la mémoire.",
|
||||
"total_memory": "Mémoire totale : {total} Go",
|
||||
"used_memory": "Mémoire utilisée : {used} Go",
|
||||
"low_free_memory": "Mémoire libre faible détectée ! Seulement {free} Go disponibles.",
|
||||
"measuring_cpu": "Mesure de l’usage CPU par cœur...",
|
||||
"core_usage": "Cœur {idx} : [{bar}] {usage}%",
|
||||
"total_cpu_usage": "Usage total CPU : {usage}%",
|
||||
"high_avg_cpu": "Moyenne CPU élevée : {usage}%",
|
||||
"really_high_cpu": "Charge CPU vraiment élevée ! Le système pourrait ralentir ou planter.",
|
||||
"memory_file": "Fichier mémoire : {size} Mo",
|
||||
"memory_file_large": "Fichier mémoire de 1 Go ou plus, pense à le nettoyer pour libérer de l’espace.",
|
||||
"memory_file_corrupted": "Fichier mémoire corrompu ! Erreur JSON : {error}",
|
||||
"consider_backup_memory": "Pense à sauvegarder et recréer le fichier mémoire.",
|
||||
"memory_file_encoding": "Problèmes d’encodage du fichier mémoire : {error}",
|
||||
"error_reading_memory": "Erreur lecture fichier mémoire : {error}",
|
||||
"memory_file_not_found": "Fichier mémoire introuvable.",
|
||||
"modification_warning": "Goober a été modifié ! Toutes les modifications seront perdues lors d'une mise à jour !",
|
||||
"reported_version": "Version rapportée :",
|
||||
"current_hash": "Hachage actuel :",
|
||||
"not_found": "n'est pas trouvé !",
|
||||
"version_error": "Impossible de récupérer les informations de version. Code d'état",
|
||||
"loaded_cog": "Cog chargé :",
|
||||
"loaded_cog2": "Module chargé :",
|
||||
"cog_fail": "Échec du chargement du cog :",
|
||||
"cog_fail2": "Échec du chargement du module :",
|
||||
"no_model": "Aucun modèle Markov sauvegardé trouvé. Démarrage à partir de zéro.",
|
||||
"folder_created": "Dossier '{folder_name}' créé.",
|
||||
"folder_exists": "Le dossier '{folder_name}' existe déjà. Ignorons...",
|
||||
"logged_in": "Connecté en tant que",
|
||||
"synced_commands": "Synchronisé",
|
||||
"synced_commands2": "commandes !",
|
||||
"fail_commands_sync": "Échec de la synchronisation des commandes :",
|
||||
"started": "{name} a démarré !",
|
||||
"name_check": "Erreur lors de la vérification de la disponibilité du nom :",
|
||||
"name_taken": "Le nom est déjà pris. Veuillez choisir un autre nom.",
|
||||
"name_check2": "Erreur lors de la vérification de la disponibilité du nom :",
|
||||
"add_token": "Token : {token}\nVeuillez ajouter ce token à votre fichier .env comme",
|
||||
"token_exists": "Le token existe déjà dans .env. Utilisation du token existant.",
|
||||
"registration_error": "Erreur lors de l'enregistrement :",
|
||||
"version_backup": "Sauvegarde créée :",
|
||||
"backup_error": "Erreur : {LOCAL_VERSION_FILE} introuvable pour la sauvegarde.",
|
||||
"model_loaded": "Modèle Markov chargé depuis",
|
||||
"fetch_update_fail": "Impossible de récupérer les informations de mise à jour.",
|
||||
"invalid_server": "Erreur : Informations de version invalides reçues du serveur.",
|
||||
"goober_server_alert": "Alerte du serveur Goober central !\n",
|
||||
"new_version": "Nouvelle version disponible : {latest_version} (Actuelle : {local_version})",
|
||||
"changelog": "Consultez {VERSION_URL}/goob/changes.txt pour voir les modifications\n\n",
|
||||
"invalid_version": "La version : {local_version} n'est pas valide !",
|
||||
"invalid_version2": "Si c'est intentionnel, ignorez ce message. Sinon, appuyez sur Y pour récupérer une version valide depuis le serveur, quelle que soit la version actuelle de Goober.",
|
||||
"invalid_version3": "La version actuelle sera sauvegardée dans current_version.bak..",
|
||||
"input": "(Y ou toute autre touche pour ignorer...)",
|
||||
"modification_ignored": "Vous avez modifié",
|
||||
"modification_ignored2": "IGNOREWARNING est désactivé..",
|
||||
"latest_version": "Vous utilisez la dernière version :",
|
||||
"latest_version2": "Consultez {VERSION_URL}/goob/changes.txt pour voir les modifications",
|
||||
"pinging_disabled": "Le ping est désactivé ! Je ne préviens pas le serveur que je suis en ligne...",
|
||||
"goober_ping_success": "Connecté à Goober central en tant que {NAME}",
|
||||
"goober_ping_fail": "Échec de l'envoi des données. Le serveur a retourné le code d'état :",
|
||||
"goober_ping_fail2": "Une erreur est survenue lors de l'envoi des données :",
|
||||
"sentence_positivity": "La positivité de la phrase est :",
|
||||
"command_edit_fail": "Échec de la modification du message :",
|
||||
"command_desc_retrain": "Réentraîne manuellement le modèle Markov.",
|
||||
"command_markov_retrain": "Réentraînement du modèle Markov... Veuillez patienter.",
|
||||
"command_markov_memory_not_found": "Erreur : fichier de mémoire introuvable !",
|
||||
"command_markov_memory_is_corrupt": "Erreur : le fichier de mémoire est corrompu !",
|
||||
"command_markov_retraining": "Traitement de {processed_data}/{data_size} points de données...",
|
||||
"command_markov_retrain_successful": "Modèle Markov réentraîné avec succès en utilisant {data_size} points de données !",
|
||||
"command_desc_talk": "parle et tout ça",
|
||||
"command_talk_insufficent_text": "Je dois apprendre plus de messages avant de pouvoir parler.",
|
||||
"command_talk_generation_fail": "Je n'ai rien à dire pour le moment !",
|
||||
"command_desc_help": "aide",
|
||||
"command_help_embed_title": "Aide du bot",
|
||||
"command_help_embed_desc": "Liste des commandes regroupées par catégorie.",
|
||||
"command_help_categories_general": "Général",
|
||||
"command_help_categories_admin": "Administration",
|
||||
"command_help_categories_custom": "Commandes personnalisées",
|
||||
"command_ran": "Info : {message.author.name} a exécuté {message.content}",
|
||||
"command_ran_s": "Info : {interaction.user} a exécuté ",
|
||||
"command_desc_ping": "ping",
|
||||
"command_ping_embed_desc": "Latence du bot :",
|
||||
"command_ping_footer": "Demandé par",
|
||||
"command_about_desc": "à propos",
|
||||
"command_about_embed_title": "À propos de moi",
|
||||
"command_about_embed_field1": "Nom",
|
||||
"command_about_embed_field2name": "Version",
|
||||
"command_about_embed_field2value": "Locale : {local_version} \nDernière : {latest_version}",
|
||||
"command_desc_stats": "statistiques",
|
||||
"command_stats_embed_title": "Statistiques du bot",
|
||||
"command_stats_embed_desc": "Données sur la mémoire du bot.",
|
||||
"command_stats_embed_field1name": "Statistiques du fichier",
|
||||
"command_stats_embed_field1value": "Taille : {file_size} octets\nLignes : {line_count}",
|
||||
"command_stats_embed_field2name": "Version",
|
||||
"command_stats_embed_field2value": "Locale : {local_version} \nDernière : {latest_version}",
|
||||
"command_stats_embed_field3name": "Informations variables",
|
||||
"command_stats_embed_field3value": "Nom : {NAME} \nPréfixe : {PREFIX} \nID du propriétaire : {ownerid}\nLigne de ping : {PING_LINE} \nPartage de mémoire activé : {showmemenabled} \nEntraînement utilisateur activé : {USERTRAIN_ENABLED} \nChanson : {song} \nTexte de démarrage : ```{splashtext}```"
|
||||
}
|
|
@ -22,7 +22,3 @@ by expect (requires goober version 0.11.8 or higher)
|
|||
|
||||
[webUI](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/webserver.py)
|
||||
by expect (requires goober version 0.11.8 or higher)
|
||||
|
||||
[LastFM](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/webserver.py)
|
||||
by expect (no idea what version it needs i've only tried it on 1.0.3)
|
||||
- you have to add LASTFM_USERNAME and LASTFM_API_KEY to your .env
|
66
cogs/cogmanager.py
Normal file
|
@ -0,0 +1,66 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
import os
|
||||
from config import ownerid
|
||||
|
||||
class CogManager(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command()
|
||||
async def load(self, ctx, cog_name: str = None):
|
||||
if ctx.author.id != ownerid:
|
||||
await ctx.send("You do not have permission to use this command.")
|
||||
return
|
||||
if cog_name is None:
|
||||
await ctx.send("Please provide the cog name to load.")
|
||||
return
|
||||
try:
|
||||
await self.bot.load_extension(f"cogs.{cog_name}")
|
||||
await ctx.send(f"Loaded cog `{cog_name}` successfully.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error loading cog `{cog_name}`: {e}")
|
||||
|
||||
@commands.command()
|
||||
async def unload(self, ctx, cog_name: str = None):
|
||||
if ctx.author.id != ownerid:
|
||||
await ctx.send("You do not have permission to use this command.")
|
||||
return
|
||||
if cog_name is None:
|
||||
await ctx.send("Please provide the cog name to unload.")
|
||||
return
|
||||
try:
|
||||
await self.bot.unload_extension(f"cogs.{cog_name}")
|
||||
await ctx.send(f"Unloaded cog `{cog_name}` successfully.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error unloading cog `{cog_name}`: {e}")
|
||||
|
||||
@commands.command()
|
||||
async def reload(self, ctx, cog_name: str = None):
|
||||
if ctx.author.id != ownerid:
|
||||
await ctx.send("You do not have permission to use this command.")
|
||||
return
|
||||
if cog_name is None:
|
||||
await ctx.send("Please provide the cog name to reload.")
|
||||
return
|
||||
try:
|
||||
await self.bot.unload_extension(f"cogs.{cog_name}")
|
||||
await self.bot.load_extension(f"cogs.{cog_name}")
|
||||
await ctx.send(f"Reloaded cog `{cog_name}` successfully.")
|
||||
except Exception as e:
|
||||
await ctx.send(f"Error reloading cog `{cog_name}`: {e}")
|
||||
|
||||
@commands.command()
|
||||
async def listcogs(self, ctx):
|
||||
"""Lists all currently loaded cogs in an embed."""
|
||||
cogs = list(self.bot.cogs.keys())
|
||||
if not cogs:
|
||||
await ctx.send("No cogs are currently loaded.")
|
||||
return
|
||||
|
||||
embed = discord.Embed(title="Loaded Cogs", description="Here is a list of all currently loaded cogs:")
|
||||
embed.add_field(name="Cogs", value="\n".join(cogs), inline=False)
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(CogManager(bot))
|
13
cogs/hello.py
Normal file
|
@ -0,0 +1,13 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
class Hello(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command()
|
||||
async def hello(self, ctx):
|
||||
await ctx.send("Hello, world!")
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(Hello(bot))
|
22
cogs/slashcomandexample.py
Normal file
|
@ -0,0 +1,22 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
from discord import app_commands
|
||||
|
||||
class Ping(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@app_commands.command(name="slashcommand", description="slashcommandexample")
|
||||
async def ping(self, interaction: discord.Interaction):
|
||||
await interaction.response.defer()
|
||||
exampleembed = discord.Embed(
|
||||
title="Pong!!",
|
||||
description="The Beretta fires fast and won't make you feel any better!",
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
exampleembed.set_footer(text=f"Requested by {interaction.user.name}", icon_url=interaction.user.avatar.url)
|
||||
|
||||
await interaction.followup.send(embed=exampleembed)
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(Ping(bot))
|
|
@ -1,11 +1,8 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
from modules.globalvars import RED, GREEN, RESET, LOCAL_VERSION_FILE
|
||||
from config import RED, GREEN, RESET, LOCAL_VERSION_FILE
|
||||
import os
|
||||
|
||||
from modules.permission import requires_admin
|
||||
|
||||
|
||||
class songchange(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
@ -19,20 +16,18 @@ class songchange(commands.Cog):
|
|||
global local_version
|
||||
local_version = get_local_version()
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def changesong(self, ctx, song: str):
|
||||
await ctx.send(f"Changed song to {song}")
|
||||
async def changesong(self, ctx):
|
||||
if LOCAL_VERSION_FILE > "0.11.8":
|
||||
await ctx.send(f"Goober is too old! you must have version 0.11.8 you have {local_version}")
|
||||
return
|
||||
await ctx.send("Check the terminal! (this does not persist across restarts)")
|
||||
song = input("\nEnter a song:\n")
|
||||
try:
|
||||
await self.bot.change_presence(
|
||||
activity=discord.Activity(
|
||||
type=discord.ActivityType.listening, name=f"{song}"
|
||||
)
|
||||
)
|
||||
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{song}"))
|
||||
print(f"{GREEN}Changed song to {song}{RESET}")
|
||||
except Exception as e:
|
||||
print(f"{RED}An error occurred while changing songs..: {str(e)}{RESET}")
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(songchange(bot))
|
|
@ -13,22 +13,20 @@ ready = True
|
|||
MODEL_MATCH_STRING = r"[0-9]{2}_[0-9]{2}_[0-9]{4}-[0-9]{2}_[0-9]{2}"
|
||||
|
||||
try:
|
||||
import tensorflow as tf
|
||||
import keras
|
||||
from keras.preprocessing.text import Tokenizer
|
||||
from keras.preprocessing.sequence import pad_sequences
|
||||
from keras.models import Sequential, load_model
|
||||
from keras.layers import Embedding, LSTM, Dense
|
||||
from keras.backend import clear_session
|
||||
|
||||
if tf.config.list_physical_devices("GPU"):
|
||||
import tensorflow as tf
|
||||
from tensorflow import keras
|
||||
from tensorflow.keras.preprocessing.text import Tokenizer
|
||||
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
||||
from tensorflow.keras.models import Sequential, load_model
|
||||
from tensorflow.keras.layers import Embedding, LSTM, Dense
|
||||
from tensorflow.keras.backend import clear_session
|
||||
|
||||
if tf.config.list_physical_devices('GPU'):
|
||||
print("Using GPU acceleration")
|
||||
elif tf.config.list_physical_devices("Metal"):
|
||||
elif tf.config.list_physical_devices('Metal'):
|
||||
print("Using Metal for macOS acceleration")
|
||||
except ImportError:
|
||||
print(
|
||||
"ERROR: Failed to import TensorFlow. Ensure you have the correct dependencies:"
|
||||
)
|
||||
print("ERROR: Failed to import TensorFlow. Ensure you have the correct dependencies:")
|
||||
print("tensorflow>=2.15.0")
|
||||
print("For macOS (Apple Silicon): tensorflow-metal")
|
||||
ready = False
|
||||
|
@ -40,39 +38,24 @@ class TFCallback(keras.callbacks.Callback):
|
|||
self.bot = bot
|
||||
self.message = message
|
||||
self.times = [time.time()]
|
||||
|
||||
|
||||
async def send_message(self, message: str, description: str, **kwargs):
|
||||
if "epoch" in kwargs:
|
||||
self.times.append(time.time())
|
||||
avg_epoch_time = np.mean(np.diff(self.times))
|
||||
description = f"ETA: {round(avg_epoch_time)}s"
|
||||
self.embed.add_field(
|
||||
name=f"<t:{round(time.time())}:t> - {message}",
|
||||
value=description,
|
||||
inline=False,
|
||||
)
|
||||
self.embed.add_field(name=f"<t:{round(time.time())}:t> - {message}", value=description, inline=False)
|
||||
await self.message.edit(embed=self.embed)
|
||||
|
||||
|
||||
def on_train_end(self, logs=None):
|
||||
self.bot.loop.create_task(
|
||||
self.send_message("Training stopped", "Training has been stopped.")
|
||||
)
|
||||
|
||||
self.bot.loop.create_task(self.send_message("Training stopped", "Training has been stopped."))
|
||||
|
||||
def on_epoch_begin(self, epoch, logs=None):
|
||||
self.bot.loop.create_task(
|
||||
self.send_message(
|
||||
f"Starting epoch {epoch}", "This might take a while", epoch=True
|
||||
)
|
||||
)
|
||||
|
||||
self.bot.loop.create_task(self.send_message(f"Starting epoch {epoch}", "This might take a while", epoch=True))
|
||||
|
||||
def on_epoch_end(self, epoch, logs=None):
|
||||
self.bot.loop.create_task(
|
||||
self.send_message(
|
||||
f"Epoch {epoch} ended",
|
||||
f"Accuracy: {round(logs.get('accuracy', 0.0), 4)}",
|
||||
)
|
||||
)
|
||||
|
||||
self.bot.loop.create_task(self.send_message(f"Epoch {epoch} ended", f"Accuracy: {round(logs.get('accuracy', 0.0), 4)}"))
|
||||
|
||||
|
||||
class Ai:
|
||||
def __init__(self):
|
||||
|
@ -80,11 +63,11 @@ class Ai:
|
|||
if model_path:
|
||||
self.__load_model(model_path)
|
||||
self.is_loaded = model_path is not None
|
||||
self.batch_size = 64
|
||||
|
||||
self.batch_size = 64
|
||||
|
||||
def generate_model_name(self):
|
||||
return time.strftime("%d_%m_%Y-%H_%M", time.localtime())
|
||||
|
||||
return time.strftime('%d_%m_%Y-%H_%M', time.localtime())
|
||||
|
||||
def __load_model(self, model_path):
|
||||
clear_session()
|
||||
self.model = load_model(os.path.join(model_path, "model.h5"))
|
||||
|
@ -98,7 +81,7 @@ class Ai:
|
|||
with open("memory.json", "r") as f:
|
||||
self.tokenizer.fit_on_texts(json.load(f))
|
||||
self.is_loaded = True
|
||||
|
||||
|
||||
def reload_model(self):
|
||||
clear_session()
|
||||
model_path = settings.get("model_path")
|
||||
|
@ -107,11 +90,9 @@ class Ai:
|
|||
self.is_loaded = True
|
||||
|
||||
async def run_async(self, func, bot, *args, **kwargs):
|
||||
return await bot.loop.run_in_executor(
|
||||
None, functools.partial(func, *args, **kwargs)
|
||||
)
|
||||
|
||||
return await bot.loop.run_in_executor(None, functools.partial(func, *args, **kwargs))
|
||||
|
||||
|
||||
class Learning(Ai):
|
||||
def create_model(self, memory, epochs=2):
|
||||
memory = memory[:2000]
|
||||
|
@ -126,58 +107,41 @@ class Learning(Ai):
|
|||
maxlen = max(map(len, X))
|
||||
X = pad_sequences(X, maxlen=maxlen, padding="pre")
|
||||
y = np.array(y)
|
||||
|
||||
model = Sequential(
|
||||
[
|
||||
Embedding(input_dim=VOCAB_SIZE, output_dim=128, input_length=maxlen),
|
||||
LSTM(64),
|
||||
Dense(VOCAB_SIZE, activation="softmax"),
|
||||
]
|
||||
)
|
||||
|
||||
model.compile(
|
||||
optimizer="adam",
|
||||
loss="sparse_categorical_crossentropy",
|
||||
metrics=["accuracy"],
|
||||
)
|
||||
|
||||
model = Sequential([
|
||||
Embedding(input_dim=VOCAB_SIZE, output_dim=128, input_length=maxlen),
|
||||
LSTM(64),
|
||||
Dense(VOCAB_SIZE, activation="softmax")
|
||||
])
|
||||
|
||||
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
|
||||
history = model.fit(X, y, epochs=epochs, batch_size=64, callbacks=[tf_callback])
|
||||
self.save_model(model, tokenizer, history)
|
||||
|
||||
|
||||
def save_model(self, model, tokenizer, history, name=None):
|
||||
name = name or self.generate_model_name()
|
||||
model_dir = os.path.join("models", name)
|
||||
os.makedirs(model_dir, exist_ok=True)
|
||||
|
||||
|
||||
with open(os.path.join(model_dir, "info.json"), "w") as f:
|
||||
json.dump(history.history, f)
|
||||
with open(os.path.join(model_dir, "tokenizer.pkl"), "wb") as f:
|
||||
pickle.dump(tokenizer, f)
|
||||
model.save(os.path.join(model_dir, "model.h5"))
|
||||
|
||||
|
||||
|
||||
class Generation(Ai):
|
||||
def generate_sentence(self, word_amount, seed):
|
||||
if not self.is_loaded:
|
||||
return False
|
||||
for _ in range(word_amount):
|
||||
token_list = self.tokenizer.texts_to_sequences([seed])[0]
|
||||
token_list = pad_sequences(
|
||||
[token_list], maxlen=self.model.input_shape[1], padding="pre"
|
||||
)
|
||||
predicted_word_index = np.argmax(
|
||||
self.model.predict(token_list, verbose=0), axis=-1
|
||||
)[0]
|
||||
output_word = next(
|
||||
(
|
||||
w
|
||||
for w, i in self.tokenizer.word_index.items()
|
||||
if i == predicted_word_index
|
||||
),
|
||||
"",
|
||||
)
|
||||
token_list = pad_sequences([token_list], maxlen=self.model.input_shape[1], padding="pre")
|
||||
predicted_word_index = np.argmax(self.model.predict(token_list, verbose=0), axis=-1)[0]
|
||||
output_word = next((w for w, i in self.tokenizer.word_index.items() if i == predicted_word_index), "")
|
||||
seed += " " + output_word
|
||||
return seed
|
||||
|
||||
|
||||
|
||||
VOCAB_SIZE = 100_000
|
||||
settings = {}
|
||||
|
@ -188,4 +152,4 @@ tf_callback = None
|
|||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(Tf(bot))
|
||||
await bot.add_cog(Tf(bot))
|
|
@ -5,12 +5,7 @@ from bs4 import BeautifulSoup
|
|||
import json
|
||||
import asyncio
|
||||
from urllib.parse import urljoin
|
||||
from modules.permission import requires_admin
|
||||
from modules.settings import instance as settings_manager
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
from config import ownerid
|
||||
class WebScraper(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
@ -27,7 +22,7 @@ class WebScraper(commands.Cog):
|
|||
|
||||
def extract_sentences(self, text):
|
||||
"""Extract sentences from text."""
|
||||
sentences = text.split(".")
|
||||
sentences = text.split('.')
|
||||
return [sentence.strip() for sentence in sentences if sentence.strip()]
|
||||
|
||||
def save_to_json(self, sentences):
|
||||
|
@ -54,6 +49,7 @@ class WebScraper(commands.Cog):
|
|||
print("No data to undo.")
|
||||
return False
|
||||
|
||||
|
||||
data = data[:-1]
|
||||
|
||||
with open("memory.json", "w") as file:
|
||||
|
@ -77,14 +73,18 @@ class WebScraper(commands.Cog):
|
|||
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
|
||||
for paragraph in soup.find_all("p"):
|
||||
for paragraph in soup.find_all('p'):
|
||||
sentences = self.extract_sentences(paragraph.get_text())
|
||||
self.save_to_json(sentences)
|
||||
|
||||
@requires_admin()
|
||||
|
||||
@commands.command()
|
||||
async def start_scrape(self, ctx, start_url: str):
|
||||
"""Command to start the scraping process."""
|
||||
if ctx.author.id != ownerid:
|
||||
await ctx.send("You do not have permission to use this command.")
|
||||
return
|
||||
|
||||
if not start_url.startswith("http"):
|
||||
await ctx.send("Please provide a valid URL.")
|
||||
return
|
||||
|
@ -96,16 +96,18 @@ class WebScraper(commands.Cog):
|
|||
|
||||
await ctx.send("Scraping complete! Sentences saved to memory.json.")
|
||||
|
||||
@requires_admin()
|
||||
@commands.command()
|
||||
async def undo_scrape(self, ctx):
|
||||
"""Command to undo the last scrape."""
|
||||
if ctx.author.id != ownerid:
|
||||
await ctx.send("You do not have permission to use this command.")
|
||||
return
|
||||
|
||||
success = self.undo_last_scrape()
|
||||
if success:
|
||||
await ctx.send("Last scrape undone successfully.")
|
||||
else:
|
||||
await ctx.send("No data to undo or an error occurred.")
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(WebScraper(bot))
|
|
@ -10,11 +10,10 @@ import time
|
|||
import aiohttp
|
||||
import re
|
||||
from aiohttp import WSMsgType
|
||||
from modules.globalvars import VERSION_URL
|
||||
from config import VERSION_URL
|
||||
import sys
|
||||
import subprocess
|
||||
|
||||
|
||||
class GooberWeb(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
@ -25,20 +24,18 @@ class GooberWeb(commands.Cog):
|
|||
self.last_command_time = "Never"
|
||||
self.start_time = time.time()
|
||||
self.websockets = set()
|
||||
|
||||
self.app.add_routes(
|
||||
[
|
||||
web.get("/", self.handle_index),
|
||||
web.get("/changesong", self.handle_changesong),
|
||||
web.get("/stats", self.handle_stats),
|
||||
web.get("/data", self.handle_json_data),
|
||||
web.get("/ws", self.handle_websocket),
|
||||
web.get("/styles.css", self.handle_css),
|
||||
web.get("/settings", self.handle_settings),
|
||||
web.post("/update_settings", self.handle_update_settings),
|
||||
web.post("/restart_bot", self.handle_restart_bot),
|
||||
]
|
||||
)
|
||||
|
||||
self.app.add_routes([
|
||||
web.get('/', self.handle_index),
|
||||
web.get('/changesong', self.handle_changesong),
|
||||
web.get('/stats', self.handle_stats),
|
||||
web.get('/data', self.handle_json_data),
|
||||
web.get('/ws', self.handle_websocket),
|
||||
web.get('/styles.css', self.handle_css),
|
||||
web.get('/settings', self.handle_settings),
|
||||
web.post('/update_settings', self.handle_update_settings),
|
||||
web.post('/restart_bot', self.handle_restart_bot),
|
||||
])
|
||||
|
||||
self.bot.loop.create_task(self.start_web_server())
|
||||
self.update_clients.start()
|
||||
|
@ -55,82 +52,69 @@ class GooberWeb(commands.Cog):
|
|||
async def get_blacklisted_users(self):
|
||||
blacklisted_ids = os.getenv("BLACKLISTED_USERS", "").split(",")
|
||||
blacklisted_users = []
|
||||
|
||||
|
||||
for user_id in blacklisted_ids:
|
||||
if not user_id.strip():
|
||||
continue
|
||||
|
||||
|
||||
try:
|
||||
user = await self.bot.fetch_user(int(user_id))
|
||||
blacklisted_users.append(
|
||||
{
|
||||
"name": f"{user.name}",
|
||||
"avatar_url": (
|
||||
str(user.avatar.url)
|
||||
if user.avatar
|
||||
else str(user.default_avatar.url)
|
||||
),
|
||||
"id": user.id,
|
||||
}
|
||||
)
|
||||
blacklisted_users.append({
|
||||
"name": f"{user.name}#{user.discriminator}",
|
||||
"avatar_url": str(user.avatar.url) if user.avatar else str(user.default_avatar.url),
|
||||
"id": user.id
|
||||
})
|
||||
except discord.NotFound:
|
||||
blacklisted_users.append(
|
||||
{
|
||||
"name": f"Unknown User ({user_id})",
|
||||
"avatar_url": "",
|
||||
"id": user_id,
|
||||
}
|
||||
)
|
||||
blacklisted_users.append({
|
||||
"name": f"Unknown User ({user_id})",
|
||||
"avatar_url": "",
|
||||
"id": user_id
|
||||
})
|
||||
except discord.HTTPException as e:
|
||||
print(f"Error fetching user {user_id}: {e}")
|
||||
continue
|
||||
|
||||
|
||||
return blacklisted_users
|
||||
|
||||
|
||||
async def get_enhanced_guild_info(self):
|
||||
guilds = sorted(self.bot.guilds, key=lambda g: g.member_count, reverse=True)
|
||||
guild_info = []
|
||||
|
||||
|
||||
for guild in guilds:
|
||||
icon_url = str(guild.icon.url) if guild.icon else ""
|
||||
guild_info.append(
|
||||
{
|
||||
"name": guild.name,
|
||||
"member_count": guild.member_count,
|
||||
"icon_url": icon_url,
|
||||
"id": guild.id,
|
||||
}
|
||||
)
|
||||
|
||||
guild_info.append({
|
||||
"name": guild.name,
|
||||
"member_count": guild.member_count,
|
||||
"icon_url": icon_url,
|
||||
"id": guild.id
|
||||
})
|
||||
|
||||
return guild_info
|
||||
|
||||
|
||||
async def start_web_server(self):
|
||||
self.runner = web.AppRunner(self.app)
|
||||
await self.runner.setup()
|
||||
self.site = web.TCPSite(self.runner, "0.0.0.0", 8080)
|
||||
self.site = web.TCPSite(self.runner, '0.0.0.0', 8080)
|
||||
await self.site.start()
|
||||
print("Goober web server started on port 8080")
|
||||
|
||||
|
||||
async def stop_web_server(self):
|
||||
if self.site is None or self.runner is None:
|
||||
return
|
||||
|
||||
await self.site.stop()
|
||||
await self.runner.cleanup()
|
||||
print("Web server stopped")
|
||||
|
||||
|
||||
def cog_unload(self):
|
||||
self.update_clients.cancel()
|
||||
self.bot.loop.create_task(self.stop_web_server())
|
||||
|
||||
|
||||
@tasks.loop(seconds=5)
|
||||
async def update_clients(self):
|
||||
if not self.websockets:
|
||||
return
|
||||
|
||||
|
||||
stats = await self.get_bot_stats()
|
||||
message = json.dumps(stats)
|
||||
|
||||
|
||||
for ws in set(self.websockets):
|
||||
try:
|
||||
await ws.send_str(message)
|
||||
|
@ -139,62 +123,62 @@ class GooberWeb(commands.Cog):
|
|||
except Exception as e:
|
||||
print(f"Error sending to websocket: {e}")
|
||||
self.websockets.remove(ws)
|
||||
|
||||
|
||||
async def handle_websocket(self, request):
|
||||
ws = web.WebSocketResponse()
|
||||
await ws.prepare(request)
|
||||
self.websockets.add(ws)
|
||||
|
||||
|
||||
try:
|
||||
async for msg in ws:
|
||||
if msg.type == WSMsgType.ERROR:
|
||||
print(f"WebSocket error: {ws.exception()}")
|
||||
finally:
|
||||
self.websockets.remove(ws)
|
||||
|
||||
|
||||
return ws
|
||||
|
||||
|
||||
async def handle_css(self, request):
|
||||
css_path = os.path.join(os.path.dirname(__file__), "styles.css")
|
||||
css_path = os.path.join(os.path.dirname(__file__), 'styles.css')
|
||||
if os.path.exists(css_path):
|
||||
return web.FileResponse(css_path)
|
||||
return web.Response(text="CSS file not found", status=404)
|
||||
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message):
|
||||
if message.author.bot:
|
||||
return
|
||||
|
||||
|
||||
ctx = await self.bot.get_context(message)
|
||||
if ctx.valid and ctx.command:
|
||||
self._update_command_stats(ctx.command.name, ctx.author)
|
||||
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_app_command_completion(self, interaction, command):
|
||||
self._update_command_stats(command.name, interaction.user)
|
||||
|
||||
|
||||
def _update_command_stats(self, command_name, user):
|
||||
self.last_command = f"{command_name} (by {user.name})"
|
||||
self.last_command = f"{command_name} (by {user.name}#{user.discriminator})"
|
||||
self.last_command_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
if self.websockets:
|
||||
asyncio.create_task(self.update_clients())
|
||||
|
||||
|
||||
async def get_bot_stats(self):
|
||||
process = psutil.Process(os.getpid())
|
||||
mem_info = process.memory_full_info()
|
||||
cpu_percent = psutil.cpu_percent()
|
||||
process_cpu = process.cpu_percent()
|
||||
|
||||
|
||||
memory_json_size = "N/A"
|
||||
if os.path.exists("memory.json"):
|
||||
memory_json_size = f"{os.path.getsize('memory.json') / 1024:.2f} KB"
|
||||
|
||||
|
||||
guild_info = await self.get_enhanced_guild_info()
|
||||
blacklisted_users = await self.get_blacklisted_users()
|
||||
|
||||
|
||||
uptime_seconds = int(time.time() - self.start_time)
|
||||
uptime_str = f"{uptime_seconds // 86400}d {(uptime_seconds % 86400) // 3600}h {(uptime_seconds % 3600) // 60}m {uptime_seconds % 60}s"
|
||||
|
||||
|
||||
return {
|
||||
"ram_usage": f"{mem_info.rss / 1024 / 1024:.2f} MB",
|
||||
"cpu_usage": f"{process_cpu}%",
|
||||
|
@ -209,29 +193,23 @@ class GooberWeb(commands.Cog):
|
|||
"bot_uptime": uptime_str,
|
||||
"latency": f"{self.bot.latency * 1000:.2f} ms",
|
||||
"bot_name": self.bot.user.name,
|
||||
"bot_avatar_url": (
|
||||
str(self.bot.user.avatar.url) if self.bot.user.avatar else ""
|
||||
),
|
||||
"bot_avatar_url": str(self.bot.user.avatar.url) if self.bot.user.avatar else "",
|
||||
"authenticated": os.getenv("gooberauthenticated"),
|
||||
"lastmsg": os.getenv("gooberlatestgen"),
|
||||
"localversion": os.getenv("gooberlocal_version"),
|
||||
"latestversion": os.getenv("gooberlatest_version"),
|
||||
"owner": os.getenv("ownerid"),
|
||||
"owner": os.getenv("ownerid")
|
||||
}
|
||||
|
||||
|
||||
async def handle_update(self, request):
|
||||
if os.path.exists("goob/update.py"):
|
||||
return web.FileResponse("goob/update.py")
|
||||
return web.Response(text="Update file not found", status=404)
|
||||
|
||||
async def handle_changesong(self, request):
|
||||
song = request.query.get("song", "")
|
||||
song = request.query.get('song', '')
|
||||
if song:
|
||||
await self.bot.change_presence(
|
||||
activity=discord.Activity(
|
||||
type=discord.ActivityType.listening, name=song
|
||||
)
|
||||
)
|
||||
await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=song))
|
||||
return web.Response(text=f"Changed song to: {song}")
|
||||
return web.Response(text="Please provide a song parameter", status=400)
|
||||
|
||||
|
@ -243,37 +221,36 @@ class GooberWeb(commands.Cog):
|
|||
async def read_env_file(self):
|
||||
env_vars = {}
|
||||
try:
|
||||
with open(".env", "r") as f:
|
||||
with open('.env', 'r') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
if not line or line.startswith('#') or '=' not in line:
|
||||
continue
|
||||
|
||||
key, value = line.split("=", 1)
|
||||
key, value = line.split('=', 1)
|
||||
key = key.strip()
|
||||
if key in ["splashtext", "DISCORD_BOT_TOKEN"]:
|
||||
if key in ['splashtext', 'DISCORD_BOT_TOKEN']:
|
||||
continue
|
||||
|
||||
env_vars[key] = value.strip("\"'")
|
||||
env_vars[key] = value.strip('"\'')
|
||||
except FileNotFoundError:
|
||||
print(".env file not found")
|
||||
return env_vars
|
||||
|
||||
|
||||
async def handle_settings(self, request):
|
||||
env_vars = await self.read_env_file()
|
||||
|
||||
|
||||
# Get config.py variables
|
||||
config_vars = {}
|
||||
try:
|
||||
with open("config.py", "r") as f:
|
||||
with open('config.py', 'r') as f:
|
||||
for line in f:
|
||||
if line.startswith("VERSION_URL"):
|
||||
config_vars["VERSION_URL"] = (
|
||||
line.split("=", 1)[1].strip().strip('"')
|
||||
)
|
||||
if line.startswith('VERSION_URL'):
|
||||
config_vars['VERSION_URL'] = line.split('=', 1)[1].strip().strip('"')
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
settings_html = """
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
@ -295,7 +272,7 @@ class GooberWeb(commands.Cog):
|
|||
<h1>Goober Settings</h1>
|
||||
<form id='settingsForm' action='/update_settings' method='post'>
|
||||
"""
|
||||
|
||||
|
||||
for key, value in env_vars.items():
|
||||
settings_html += f"""
|
||||
<div class='form-group'>
|
||||
|
@ -303,7 +280,7 @@ class GooberWeb(commands.Cog):
|
|||
<input type='text' id='{key}' name='{key}' value='{value}'>
|
||||
</div>
|
||||
"""
|
||||
|
||||
|
||||
for key, value in config_vars.items():
|
||||
settings_html += f"""
|
||||
<div class='form-group'>
|
||||
|
@ -311,7 +288,7 @@ class GooberWeb(commands.Cog):
|
|||
<input type='text' id='{key}' name='{key}' value='{value}'>
|
||||
</div>
|
||||
"""
|
||||
|
||||
|
||||
settings_html += """
|
||||
<button type='submit'>Save Settings</button>
|
||||
</form>
|
||||
|
@ -322,15 +299,15 @@ class GooberWeb(commands.Cog):
|
|||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
return web.Response(text=settings_html, content_type="text/html")
|
||||
|
||||
|
||||
return web.Response(text=settings_html, content_type='text/html')
|
||||
|
||||
async def handle_update_settings(self, request):
|
||||
data = await request.post()
|
||||
env_text = ""
|
||||
|
||||
try:
|
||||
with open(".env", "r") as f:
|
||||
with open('.env', 'r') as f:
|
||||
env_text = f.read()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
@ -338,42 +315,32 @@ class GooberWeb(commands.Cog):
|
|||
def replace_match(match):
|
||||
key = match.group(1)
|
||||
value = match.group(2)
|
||||
if key in ["splashtext", "DISCORD_BOT_TOKEN"]:
|
||||
if key in ['splashtext', 'DISCORD_BOT_TOKEN']:
|
||||
return match.group(0)
|
||||
if key in data:
|
||||
new_value = data[key]
|
||||
if not (new_value.startswith('"') and new_value.endswith('"')):
|
||||
new_value = f'"{new_value}"'
|
||||
return f"{key}={new_value}"
|
||||
return f'{key}={new_value}'
|
||||
return match.group(0)
|
||||
|
||||
env_text = re.sub(
|
||||
r"^(\w+)=([\s\S]+?)(?=\n\w+=|\Z)",
|
||||
replace_match,
|
||||
env_text,
|
||||
flags=re.MULTILINE,
|
||||
)
|
||||
env_text = re.sub(r'^(\w+)=([\s\S]+?)(?=\n\w+=|\Z)', replace_match, env_text, flags=re.MULTILINE)
|
||||
|
||||
with open(".env", "w") as f:
|
||||
f.write(env_text.strip() + "\n")
|
||||
with open('.env', 'w') as f:
|
||||
f.write(env_text.strip() + '\n')
|
||||
|
||||
if "VERSION_URL" in data:
|
||||
if 'VERSION_URL' in data:
|
||||
config_text = ""
|
||||
try:
|
||||
with open("config.py", "r") as f:
|
||||
with open('config.py', 'r') as f:
|
||||
config_text = f.read()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
config_text = re.sub(
|
||||
r'^(VERSION_URL\s*=\s*").+?"',
|
||||
f'\\1{data["VERSION_URL"]}"',
|
||||
config_text,
|
||||
flags=re.MULTILINE,
|
||||
)
|
||||
config_text = re.sub(r'^(VERSION_URL\s*=\s*").+?"', f'\\1{data["VERSION_URL"]}"', config_text, flags=re.MULTILINE)
|
||||
|
||||
with open("config.py", "w") as f:
|
||||
f.write(config_text.strip() + "\n")
|
||||
with open('config.py', 'w') as f:
|
||||
f.write(config_text.strip() + '\n')
|
||||
|
||||
return aiohttp.web.Response(text="Settings updated successfully!")
|
||||
|
||||
|
@ -381,12 +348,8 @@ class GooberWeb(commands.Cog):
|
|||
stats = await self.get_bot_stats()
|
||||
|
||||
guild_list_html = ""
|
||||
for guild in stats["guilds"]:
|
||||
icon_html = (
|
||||
f'<img src="{guild["icon_url"]}" alt="guild icon" class="guild-icon">'
|
||||
if guild["icon_url"]
|
||||
else '<div class="guild-icon-placeholder"></div>'
|
||||
)
|
||||
for guild in stats['guilds']:
|
||||
icon_html = f'<img src="{guild["icon_url"]}" alt="guild icon" class="guild-icon">' if guild["icon_url"] else '<div class="guild-icon-placeholder"></div>'
|
||||
guild_list_html += f"""
|
||||
<div class="guild-item">
|
||||
{icon_html}
|
||||
|
@ -397,12 +360,8 @@ class GooberWeb(commands.Cog):
|
|||
</div>
|
||||
"""
|
||||
blacklisted_users_html = ""
|
||||
for user in stats["blacklisted_users"]:
|
||||
avatar_html = (
|
||||
f'<img src="{user["avatar_url"]}" alt="user avatar" class="user-avatar">'
|
||||
if user["avatar_url"]
|
||||
else '<div class="user-avatar-placeholder"></div>'
|
||||
)
|
||||
for user in stats['blacklisted_users']:
|
||||
avatar_html = f'<img src="{user["avatar_url"]}" alt="user avatar" class="user-avatar">' if user["avatar_url"] else '<div class="user-avatar-placeholder"></div>'
|
||||
blacklisted_users_html += f"""
|
||||
<div class="blacklisted-user">
|
||||
{avatar_html}
|
||||
|
@ -413,19 +372,20 @@ class GooberWeb(commands.Cog):
|
|||
</div>
|
||||
"""
|
||||
|
||||
owner_id = stats.get("owner")
|
||||
owner_id = stats.get('owner')
|
||||
owner = None
|
||||
owner_username = "Owner"
|
||||
owner_pfp = ""
|
||||
|
||||
|
||||
if owner_id:
|
||||
try:
|
||||
owner = await self.bot.fetch_user(int(owner_id))
|
||||
owner_username = f"{owner.name}"
|
||||
owner_username = f"{owner.name}#{owner.discriminator}"
|
||||
owner_pfp = str(owner.avatar.url) if owner and owner.avatar else ""
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
html_content = f"""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
@ -906,16 +866,15 @@ class GooberWeb(commands.Cog):
|
|||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
return web.Response(text=html_content, content_type="text/html")
|
||||
|
||||
|
||||
return web.Response(text=html_content, content_type='text/html')
|
||||
|
||||
async def handle_stats(self, request):
|
||||
return await self.handle_index(request)
|
||||
|
||||
|
||||
async def handle_json_data(self, request):
|
||||
stats = await self.get_bot_stats()
|
||||
return web.json_response(stats)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(GooberWeb(bot))
|
||||
await bot.add_cog(GooberWeb(bot))
|
|
@ -1,7 +1,6 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
|
||||
|
||||
class whoami(commands.Cog):
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
@ -14,13 +13,12 @@ class whoami(commands.Cog):
|
|||
embed = discord.Embed(
|
||||
title="User Information",
|
||||
description=f"Your User ID is: {user_id}\n"
|
||||
f"Your username is: {username}\n"
|
||||
f"Your nickname in this server is: <@{user_id}>",
|
||||
color=discord.Color.blue(),
|
||||
f"Your username is: {username}\n"
|
||||
f"Your nickname in this server is: <@{user_id}>",
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(whoami(bot))
|
33
config.py
Normal file
|
@ -0,0 +1,33 @@
|
|||
import os
|
||||
from dotenv import load_dotenv
|
||||
import platform
|
||||
import random
|
||||
|
||||
load_dotenv()
|
||||
VERSION_URL = "https://goober.expect.ovh"
|
||||
UPDATE_URL = VERSION_URL+"/latest_version.json"
|
||||
LOCAL_VERSION_FILE = "current_version.txt"
|
||||
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"
|
||||
DEFAULT_DATASET_FILE = "defaultdataset.json"
|
||||
MEMORY_LOADED_FILE = "MEMORY_LOADED"
|
||||
ALIVEPING = os.getenv("ALIVEPING")
|
||||
IGNOREWARNING = False
|
||||
song = os.getenv("SONG")
|
||||
arch = platform.machine()
|
||||
RED = "\033[31m"
|
||||
GREEN = "\033[32m"
|
||||
YELLOW = "\033[33m"
|
||||
DEBUG = "\033[1;30m"
|
||||
RESET = "\033[0m"
|
29
example.env
Normal file
|
@ -0,0 +1,29 @@
|
|||
DISCORD_BOT_TOKEN=token
|
||||
BOT_PREFIX="g."
|
||||
PING_LINE="The Beretta fires fast and won't make you feel any better!"
|
||||
BLACKLISTED_USERS=
|
||||
rnd_talk_channel1=1319593363997589614
|
||||
rnd_talk_channel2=1318263176134918246
|
||||
cooldown=10800
|
||||
hourlyspeak=1318263176134918246
|
||||
ownerid=542701119948849163
|
||||
USERTRAIN_ENABLED="true"
|
||||
showmemenabled="true"
|
||||
NAME="an instance of goober"
|
||||
locale=fi
|
||||
ALIVEPING="true"
|
||||
gooberTOKEN=
|
||||
song="War Without Reason"
|
||||
POSITIVE_GIFS="https://media.discordapp.net/attachments/821047460151427135/1181371808566493184/jjpQGeno.gif, https://tenor.com/view/chill-guy-my-new-character-gif-2777893510283028272,https://tenor.com/view/goodnight-goodnight-friends-weezer-weezer-goodnight-gif-7322052181075806988"
|
||||
splashtext="
|
||||
d8b
|
||||
?88
|
||||
88b
|
||||
d888b8b d8888b d8888b 888888b d8888b 88bd88b
|
||||
d8P' ?88 d8P' ?88d8P' ?88 88P `?8bd8b_,dP 88P' `
|
||||
88b ,88b 88b d8888b d88 d88, d8888b d88
|
||||
`?88P'`88b`?8888P'`?8888P'd88'`?88P'`?888P'd88'
|
||||
)88
|
||||
,88P
|
||||
`?8888P
|
||||
"
|
79
locales/en.json
Normal file
|
@ -0,0 +1,79 @@
|
|||
{
|
||||
"modification_warning": "Goober has been modified! Skipping server checks entirely...",
|
||||
"reported_version": "Reported Version:",
|
||||
"current_hash": "Current Hash:",
|
||||
"not_found": "is not found!",
|
||||
"version_error": "Unable to fetch version info. Status code",
|
||||
"loaded_cog": "Loaded cog:",
|
||||
"cog_fail": "Failed to load cog:",
|
||||
"no_model": "No saved Markov model found. Starting from scratch.",
|
||||
"folder_created": "Folder '{folder_name}' created.",
|
||||
"folder_exists": "Folder '{folder_name}' already exists. skipping...",
|
||||
"logged_in": "Logged in as",
|
||||
"synced_commands": "Synced",
|
||||
"synced_commands2": "commands!",
|
||||
"fail_commands_sync": "Failed to sync commands:",
|
||||
"started": "Goober has started!",
|
||||
"name_check": "Error checking name availability:",
|
||||
"name_taken": "Name is already taken. Please choose a different name.",
|
||||
"name_check2": "Error during name availability check:",
|
||||
"add_token": "Token: {token}\nPlease add this token to your .env file as",
|
||||
"token_exists": "Token already exists in .env. Continuing with the existing token.",
|
||||
"registration_error": "Error during registration:",
|
||||
"version_backup": "Backup created:",
|
||||
"backup_error": "Error: {LOCAL_VERSION_FILE} not found for backup.",
|
||||
"model_loaded": "Markov model loaded from",
|
||||
"fetch_update_fail": "Could not fetch update information.",
|
||||
"invalid_server": "Error: Invalid version information received from server.",
|
||||
"new_version": "New version available: {latest_version} (Current: {local_version})",
|
||||
"changelog": "Check {VERSION_URL}/goob/changes.txt to check out the changelog\n\n",
|
||||
"invalid_version": "The version: {local_version} isnt valid!",
|
||||
"invalid_version2": "If this is intended then ignore this message, else press Y to pull a valid version from the server regardless of the version of goober currently running",
|
||||
"invalid_version3": "The current version will be backed up to current_version.bak..",
|
||||
"input": "(Y or any other key to ignore....)",
|
||||
"modification_ignored": "You've modified",
|
||||
"modification_ignored2": "IGNOREWARNING is set to false..",
|
||||
"latest_version": "You're using the latest version:",
|
||||
"latest_version2": "Check {VERSION_URL}/goob/changes.txt to check out the changelog",
|
||||
"pinging_disabled": "Pinging is disabled! Not telling the server im on...",
|
||||
"goober_ping_success": "Logged into goober central as {NAME}",
|
||||
"goober_ping_fail": "Failed to send data. Server returned status code:",
|
||||
"goober_ping_fail2": "An error occurred while sending data:",
|
||||
"sentence_positivity": "Positivity of sentence is:",
|
||||
"command_edit_fail": "Failed to edit message:",
|
||||
"command_desc_retrain": "Retrains the Markov model manually.",
|
||||
"command_markov_retrain": "Retraining the Markov model... Please wait.",
|
||||
"command_markov_memory_not_found": "Error: memory file not found!",
|
||||
"command_markov_memory_is_corrupt": "Error: memory file is corrupt!",
|
||||
"command_markov_retraining": "Processing {processed_data}/{data_size} data points...",
|
||||
"command_markov_retrain_successful": "Markov model retrained successfully using {data_size} data points!",
|
||||
"command_desc_talk":"talks n like stuf",
|
||||
"command_talk_insufficent_text": "I need to learn more from messages before I can talk.",
|
||||
"command_talk_generation_fail": "I have nothing to say right now!",
|
||||
"command_desc_help": "help",
|
||||
"command_help_embed_title": "Bot Help",
|
||||
"command_help_embed_desc": "List of commands grouped by category.",
|
||||
"command_help_categories_general": "General",
|
||||
"command_help_categories_admin": "Administration",
|
||||
"command_help_categories_custom": "Custom Commands",
|
||||
"command_ran": "Info: {message.author.name} ran {message.content}",
|
||||
"command_ran_s": "Info: {interaction.user} ran ",
|
||||
"command_desc_ping": "ping",
|
||||
"command_ping_embed_desc": "Bot Latency:",
|
||||
"command_ping_footer": "Requested by",
|
||||
"command_about_desc": "about",
|
||||
"command_about_embed_title": "About me",
|
||||
"command_about_embed_field1": "Name",
|
||||
"command_about_embed_field2name": "Version",
|
||||
"command_about_embed_field2value": "Local: {local_version} \nLatest: {latest_version}",
|
||||
"command_desc_stats": "stats",
|
||||
"command_stats_embed_title": "Bot stats",
|
||||
"command_stats_embed_desc": "Data about the the bot's memory.",
|
||||
"command_stats_embed_field1name": "File Stats",
|
||||
"command_stats_embed_field1value": "Size: {file_size} bytes\nLines: {line_count}",
|
||||
"command_stats_embed_field2name": "Version",
|
||||
"command_stats_embed_field2value": "Local: {local_version} \nLatest: {latest_version}",
|
||||
"command_stats_embed_field3name": "Variable Info",
|
||||
"command_stats_embed_field3value": "Name: {NAME} \nPrefix: {PREFIX} \nOwner ID: {ownerid} \nCooldown: {cooldown_time} \nPing line: {PING_LINE} \nMemory Sharing Enabled: {showmemenabled} \nUser Training Enabled: {USERTRAIN_ENABLED} \nLast Random TT: {last_random_talk_time} \nSong: {song} \nSplashtext: ```{splashtext}```"
|
||||
}
|
||||
|
|
@ -13,7 +13,7 @@
|
|||
"synced_commands": "Sincronizado",
|
||||
"synced_commands2": "comandos!",
|
||||
"fail_commands_sync": "Error al sincronizar comandos:",
|
||||
"started": "{name} ha empezado!",
|
||||
"started": "Goober ha empezado!",
|
||||
"name_check": "Error al comprobar la disponibilidad del nombre:",
|
||||
"name_taken": "El nombre ya está en uso. Elija otro.",
|
||||
"name_check2": "Error durante la comprobacion de disponibilidad del nombre:",
|
||||
|
@ -73,5 +73,5 @@
|
|||
"command_stats_embed_field2name": "Version",
|
||||
"command_stats_embed_field2value": "Version local: {local_version} \nUltima version: {latest_version}",
|
||||
"command_stats_embed_field3name": "informacion sobre las variables",
|
||||
"command_stats_embed_field3value": "Nombre: {NAME} \nPrefijo: {PREFIX} \nID del propietario: {ownerid}\nLinea de ping: {PING_LINE} \nCompartir memoria habilitada: {showmemenabled} \nEntrenamiento de usuario habilitado: {USERTRAIN_ENABLED} \nCancion: {song} \nTexto de bienvenida: ```{splashtext}```"
|
||||
"command_stats_embed_field3value": "Nombre: {NAME} \nPrefijo: {PREFIX} \nID del propietario: {ownerid} \nTiempo de reutilizacion: {cooldown_time} \nLinea de ping: {PING_LINE} \nCompartir memoria habilitada: {showmemenabled} \nEntrenamiento de usuario habilitado: {USERTRAIN_ENABLED} \nUltima conversacion aleatoria: {last_random_talk_time} \nCancion: {song} \nTexto de bienvenida: ```{splashtext}```"
|
||||
}
|
|
@ -1,136 +1,78 @@
|
|||
{
|
||||
"memory_file_valid": "memory.json on toimiva!",
|
||||
"file_aint_uft8": "Tiedosto ei ole UTF-8 tekstiä. Saattaa olla binääriä tai korruptoitunut.",
|
||||
"active_users:": "Aktiiviset käyttäjät:",
|
||||
"cog_fail2": "Moduulin lataaminen epäonnistui:",
|
||||
"command_ran_s": "Info: {interaction.user} suoritti",
|
||||
"error_fetching_active_users": "Aktiivisten käyttäjien hankkimisessa tapahtui ongelma: {error}",
|
||||
"error_sending_alive_ping": "Pingin lähettäminen goober centraliin epäonnistui: {error}",
|
||||
"goober_server_alert": "Viesti goober centralista!\n",
|
||||
"loaded_cog2": "Ladattiin moduuli:",
|
||||
"spacy_initialized": "spaCy ja spacytextblob ovat valmiita.",
|
||||
"spacy_model_not_found": "spaCy mallia ei löytynyt! Ladataan se....`",
|
||||
"checks_disabled": "Tarkistukset on poistettu käytöstä!",
|
||||
"unhandled_exception": "Käsittelemätön virhe tapahtui. Ilmoita tästä GitHubissa.",
|
||||
"active_users": "Aktiiviset käyttäjät",
|
||||
"env_file_not_found": ".env-tiedostoa ei löytnyt! Luo tiedosto jossa on tarvittavat muuttujat",
|
||||
"already_started": "Olen jo käynnistynyt! Ei päivitetä...",
|
||||
"please_restart": "Käynnistä uudelleen, hölmö!",
|
||||
"local_ahead": "Paikallinen {remote}/{branch} on edellä ja/tai ajan tasalla. Ohitetaan päivitys...",
|
||||
"remote_ahead": "Etärepositorio {remote}/{branch} on edellä. Päivitetään...",
|
||||
"cant_find_local_version": "Muuttujaa local_version ei löytynyt, tai sitä on muokattu eikä ole kokonaisluku!",
|
||||
"running_prestart_checks": "Suoritetaan esikäynnistystarkistuksia...",
|
||||
"continuing_in_seconds": "Jatketaan {seconds} sekunnin kuluttua... Paina mitä tahansa näppäintä ohittaaksesi.",
|
||||
"missing_requests_psutil": "Kirjastot requests ja psutil puuttuvat! Asenna ne komennolla: `pip install requests psutil`",
|
||||
"requirements_not_found": "Tiedostoa requirements.txt ei löytynyt polusta {path} – onko sitä muokattu?",
|
||||
"warning_failed_parse_imports": "Varoitus: tuontien jäsentäminen epäonnistui tiedostossa {filename}: {error}",
|
||||
"cogs_dir_not_found": "Cogs-kansiota ei löytynyt polusta {path}, ohitetaan tarkistus.",
|
||||
"std_lib_local_skipped": "STD LIB / PAIKALLINEN {package} (tarkistus ohitettu)",
|
||||
"ok_installed": "OK",
|
||||
"missing_package": "PUUTTUU",
|
||||
"missing_package2": "ei ole asennettu",
|
||||
"missing_packages_detected": "Puuttuvia kirjastoja havaittu:",
|
||||
"telling_goober_central": "Ilmoitetaan goober-centralille osoitteessa {url}",
|
||||
"failed_to_contact": "Yhteyden muodostus epäonnistui osoitteeseen {url}: {error}",
|
||||
"all_requirements_satisfied": "Kaikki vaatimukset täyttyvät.",
|
||||
"ping_to": "Ping osoitteeseen {host}: {latency} ms",
|
||||
"high_latency": "Korkea viive havaittu! Vastaukset saattavat hidastua.",
|
||||
"could_not_parse_latency": "Viivettä ei voitu tulkita.",
|
||||
"ping_failed": "Ping osoitteeseen {host} epäonnistui.",
|
||||
"error_running_ping": "Virhe ping-komennon suorittamisessa: {error}",
|
||||
"memory_usage": "Muistin käyttö: {used} Gt / {total} Gt ({percent}%)",
|
||||
"memory_above_90": "Muistin käyttö ylittää 90 % ({percent}%). Harkitse muistin vapauttamista.",
|
||||
"total_memory": "Kokonaismuisti: {total} Gt",
|
||||
"used_memory": "Käytetty muisti: {used} Gt",
|
||||
"low_free_memory": "Vapaa muisti vähissä! Vain {free} Gt jäljellä.",
|
||||
"measuring_cpu": "Mitataan suorittimen käyttöä ytimittäin...",
|
||||
"core_usage": "Ydin {idx}: [{bar}] {usage}%",
|
||||
"total_cpu_usage": "Kokonaisprosessorin käyttö: {usage}%",
|
||||
"high_avg_cpu": "Korkea keskimääräinen prosessorin käyttö: {usage}%",
|
||||
"really_high_cpu": "Erittäin korkea prosessorikuorma! Järjestelmä saattaa hidastua tai jumittua.",
|
||||
"memory_file": "Muistitiedosto: {size} Mt",
|
||||
"memory_file_large": "Muistitiedosto on enemmän kuin 1 Gt – harkitse sen tyhjentämistä tilan vapauttamiseksi.",
|
||||
"memory_file_corrupted": "Muistitiedosto on vioittunut! JSON purkuvirhe: {error}",
|
||||
"consider_backup_memory": "Harkitse muistitiedoston varmuuskopioimista ja uudelleenluontia.",
|
||||
"memory_file_encoding": "Muistitiedostossa on koodausongelmia: {error}",
|
||||
"error_reading_memory": "Virhe muistitiedoston lukemisessa: {error}",
|
||||
"memory_file_not_found": "Muistitiedostoa ei löytynyt.",
|
||||
|
||||
"modification_warning": "Gooberia on muokattu! Ohitetaan palvelimen tarkistus kokonaan...",
|
||||
"reported_version": "Ilmoitettu versio:",
|
||||
"current_hash": "Tämänhetkinen hash:",
|
||||
"not_found": "ei löytynyt!",
|
||||
"version_error": "Versiotietojen saanti epäonnistui.. Tilakoodi:",
|
||||
"loaded_cog": "Ladatut cogit:",
|
||||
"cog_fail": "Cogin lataus epäonnistui kohteelle:",
|
||||
"no_model": "Olemassaolevaa markov-mallia ei löydetty. Aloitetaan alusta.",
|
||||
"folder_created": "Kansio '{folder_name}' luotu.",
|
||||
"folder_exists": "Kansio '{folder_name}' on jo olemassa...",
|
||||
"logged_in": "Kirjauduttiin sisään käyttäjänä",
|
||||
"synced_commands": "Synkronoitiin",
|
||||
"synced_commands2": "komennot!",
|
||||
"fail_commands_sync": "Komentojen synkronointi epäonnistui:",
|
||||
"started": "{name} on käynnistynyt!\nOlet nyt sarjan tähti, beibi!",
|
||||
"name_check": "Nimen saatavuuden tarkistus epäonnistui:",
|
||||
"name_taken": "Nimi on jo käytössä. Valitse toinen nimi.",
|
||||
"name_check2": "Virhe tapahtui nimen saatavuuden tarkistamisessa:",
|
||||
"add_token": "Token: {token}\nLisää tämä .env-tiedostoosi nimellä",
|
||||
"token_exists": "Token on jo olemassa .env-tiedostossa. Jatketaan määritetyllä tokenilla.",
|
||||
"registration_error": "Virhe rekisteröinnissä:",
|
||||
"version_backup": "Varmuuskopio luotu:",
|
||||
"backup_error": "Virhe: {LOCAL_VERSION_FILE}-tiedostoa ei löytynyt varmuuskopiota varten.",
|
||||
"model_loaded": "Markov-malli ladattu",
|
||||
"fetch_update_fail": "Päivitystietojen hankkiminen epäonnistui.",
|
||||
"invalid_server": "Virhe: Palvelin antoi virheellisen versiotietoraportin.",
|
||||
"new_version": "Uusi versio saatavilla: {latest_version} (Tämänhetkinen: {local_version})",
|
||||
"changelog": "Mene osoitteeseen {VERSION_URL}/goob/changes.txt katsotakseen muutoslokin\n\n",
|
||||
"invalid_version": "Versio: {local_version} on virheellinen!",
|
||||
"invalid_version2": "Jos tämä on tahallista, voit jättää tämän viestin huomiotta. Jos tämä ei ole tahallista, paina Y-näppäintä hankkiaksesi kelvollisen version, riippumatta Gooberin tämänhetkisestä versiosta.",
|
||||
"invalid_version3": "Tämänhetkinen versio varmuuskopioidaan kohteeseen current_version.bak..",
|
||||
"input": "(Y:tä tai mitä vaan muuta näppäintä jättää tämän huomioimatta....)",
|
||||
"modification_ignored": "Olet muokannut",
|
||||
"modification_ignored2": "IGNOREWARNING on asetettu false:ksi..",
|
||||
"latest_version": "Käytät uusinta versiota:",
|
||||
"latest_version2": "Tarkista {VERSION_URL}/goob/changes.txt katsotakseen muutosloki",
|
||||
"pinging_disabled": "Pingaus on poistettu käytöstä! En kerro palvelimelle, että olen päällä...",
|
||||
"goober_ping_success": "Lähetettiin olemassaolo ping goober centraliin!",
|
||||
"goober_ping_fail": "Tiedon lähetys epäonnistui. Palvelin antoi tilakoodin:",
|
||||
"goober_ping_fail2": "Tiedon lähettämisen aikana tapahtui virhe:",
|
||||
"sentence_positivity": "Lauseen positiivisuus on:",
|
||||
"command_edit_fail": "Viestin muokkaus epäonnistui:",
|
||||
"command_desc_retrain": "Uudelleenkouluttaa markov-mallin manuaalisesti.",
|
||||
"command_markov_retrain": "Uudelleenkoulutetaan markov-mallia... Odota.",
|
||||
"command_markov_memory_not_found": "Virhe: muistitiedostoa ei löytynyt!",
|
||||
"command_markov_memory_is_corrupt": "Virhe: muistitiedosto on korruptoitu!",
|
||||
"command_markov_retraining": "Käsitellään {processed_data}/{data_size} datapistettä...",
|
||||
"command_markov_retrain_successful": "Markov-malli koulutettiin uudestaan {data_size} datapisteellä!",
|
||||
"command_desc_talk":"puhuu ja sillei",
|
||||
"command_talk_insufficent_text": "Minun pitää oppia lisää viesteistä ennen kun puhun.",
|
||||
"command_talk_generation_fail": "Minulla ei ole mitään sanottavaa!",
|
||||
"command_desc_help": "auta",
|
||||
"command_help_embed_title": "Botin apu",
|
||||
"command_help_embed_desc": "Komennot ryhmitelty kategorioilla",
|
||||
"command_help_categories_general": "Yleiset",
|
||||
"command_help_categories_admin": "Ylläpito",
|
||||
"command_help_categories_custom": "Mukautetut komennot",
|
||||
"command_ran": "Tietoa: {message.author.name} suoritti {message.content}",
|
||||
"command_desc_ping": "ping",
|
||||
"command_ping_embed_desc": "Botin viive:",
|
||||
"command_ping_footer": "Pyytäjä: ",
|
||||
"command_about_desc": "tietoa",
|
||||
"command_about_embed_title": "Tietoa minusta",
|
||||
"command_about_embed_field1": "Nimi",
|
||||
"command_about_embed_field2name": "Versio",
|
||||
"command_about_embed_field2value": "Paikallinen: {local_version} \nUusin: {latest_version}",
|
||||
"command_desc_stats": "statistiikat",
|
||||
"command_stats_embed_title": "Botin statistiikat",
|
||||
"command_stats_embed_desc": "Tietoa botin muistista.",
|
||||
"command_stats_embed_field1name": "Tiedostostatistiikat",
|
||||
"command_stats_embed_field1value": "Koko: {file_size} tavua\nLinjoja: {line_count}",
|
||||
"command_stats_embed_field2name": "Versio",
|
||||
"command_stats_embed_field2value": "Paikallinen: {local_version} \nUusin: {latest_version}",
|
||||
"command_stats_embed_field3name": "Muuttajainformaatio",
|
||||
"command_stats_embed_field3value": "Nimi: {NAME} \nEtuliite: {PREFIX} \nOmistajan ID: {ownerid}\nPing-linja: {PING_LINE} \nMuistin jako päällä: {showmemenabled} \nOppiminen käyttäjistä: {USERTRAIN_ENABLED}\nLaulu: {song} \nRoisketeksti: ```{splashtext}```"
|
||||
|
||||
}
|
||||
|
||||
{
|
||||
"modification_warning": "Gooberia on muokattu! Ohitetaan palvelimen tarkistus kokonaan...",
|
||||
"reported_version": "Ilmoitettu versio:",
|
||||
"current_hash": "Tämänhetkinen hash:",
|
||||
"not_found": "ei löytynyt!",
|
||||
"version_error": "Versiotietojen saanti epäonnistui.. Tilakoodi:",
|
||||
"loaded_cog": "Ladatut cogit:",
|
||||
"cog_fail": "Cogin lataus epäonnistui kohteelle:",
|
||||
"no_model": "Olemassaolevaa markov-mallia ei löydetty. Aloitetaan alusta.",
|
||||
"folder_created": "Kansio '{folder_name}' luotu.",
|
||||
"folder_exists": "Kansio '{folder_name}' on jo olemassa...",
|
||||
"logged_in": "Kirjauduttiin sisään käyttäjänä",
|
||||
"synced_commands": "Synkronoitiin",
|
||||
"synced_commands2": "komennot!",
|
||||
"fail_commands_sync": "Komentojen synkronointi epäonnistui:",
|
||||
"started": "Goober on käynnistynyt!",
|
||||
"name_check": "Nimen saatavuuden tarkistus epäonnistui:",
|
||||
"name_taken": "Nimi on jo käytössä. Valitse toinen nimi.",
|
||||
"name_check2": "Virhe tapahtui nimen saatavuuden tarkistamisessa:",
|
||||
"add_token": "Token: {token}\nLisää tämä .env-tiedostoosi nimellä",
|
||||
"token_exists": "Token on jo olemassa .env-tiedostossa. Jatketaan määritetyllä tokenilla.",
|
||||
"registration_error": "Virhe rekisteröinnissä:",
|
||||
"version_backup": "Varmuuskopio luotu:",
|
||||
"backup_error": "Virhe: {LOCAL_VERSION_FILE}-tiedostoa ei löytynyt varmuuskopiota varten.",
|
||||
"model_loaded": "Markov-malli ladattu",
|
||||
"fetch_update_fail": "Päivitystietojen hankkiminen epäonnistui.",
|
||||
"invalid_server": "Virhe: Palvelin antoi virheellisen versiotietoraportin.",
|
||||
"new_version": "Uusi versio saatavilla: {latest_version} (Tämänhetkinen: {local_version})",
|
||||
"changelog": "Mene osoitteeseen {VERSION_URL}/goob/changes.txt katsotakseen muutoslokin\n\n",
|
||||
"invalid_version": "Versio: {local_version} on virheellinen!",
|
||||
"invalid_version2": "Jos tämä on tahallista, voit jättää tämän viestin huomiotta. Jos tämä ei ole tahallista, paina Y-näppäintä hankkiaksesi kelvollisen version, riippumatta Gooberin tämänhetkisestä versiosta.",
|
||||
"invalid_version3": "Tämänhetkinen versio varmuuskopioidaan kohteeseen current_version.bak..",
|
||||
"input": "(Y:tä tai mitä vaan muuta näppäintä jättää tämän huomioimatta....)",
|
||||
"modification_ignored": "Olet muokannut",
|
||||
"modification_ignored2": "IGNOREWARNING on asetettu false:ksi..",
|
||||
"latest_version": "Käytät uusinta versiota:",
|
||||
"latest_version2": "Tarkista {VERSION_URL}/goob/changes.txt katsotakseen muutosloki",
|
||||
"pinging_disabled": "Pingaus on poistettu käytöstä! En kerro palvelimelle, että olen päällä...",
|
||||
"goober_ping_success": "Lähetettiin olemassaolo ping goober centraliin!",
|
||||
"goober_ping_fail": "Tiedon lähetys epäonnistui. Palvelin antoi tilakoodin:",
|
||||
"goober_ping_fail2": "Tiedon lähettämisen aikana tapahtui virhe:",
|
||||
"sentence_positivity": "Lauseen positiivisuus on:",
|
||||
"command_edit_fail": "Viestin muokkaus epäonnistui:",
|
||||
"command_desc_retrain": "Uudelleenkouluttaa markov-mallin manuaalisesti.",
|
||||
"command_markov_retrain": "Uudelleenkoulutetaan markov-mallia... Odota.",
|
||||
"command_markov_memory_not_found": "Virhe: muistitiedostoa ei löytynyt!",
|
||||
"command_markov_memory_is_corrupt": "Virhe: muistitiedosto on korruptoitu!",
|
||||
"command_markov_retraining": "Käsitellään {processed_data}/{data_size} datapisteestä...",
|
||||
"command_markov_retrain_successful": "Markov-malli koulutettiin uudestaan {data_size} datapisteellä!",
|
||||
"command_desc_talk":"puhuu ja sillei",
|
||||
"command_talk_insufficent_text": "Minun pitää oppia lisää viesteistä ennen kun puhun.",
|
||||
"command_talk_generation_fail": "Minulla ei ole mitään sanottavaa!",
|
||||
"command_desc_help": "auta",
|
||||
"command_help_embed_title": "Botin apu",
|
||||
"command_help_embed_desc": "Komennot ryhmitelty kategorioilla",
|
||||
"command_help_categories_general": "Yleiset",
|
||||
"command_help_categories_admin": "Ylläpito",
|
||||
"command_help_categories_custom": "Mukautetut komennot",
|
||||
"command_ran": "Tietoa: {message.author.name} suoritti {message.content}",
|
||||
"command_desc_ping": "ping",
|
||||
"command_ping_embed_desc": "Botin viive:",
|
||||
"command_ping_footer": "Pyytäjä: ",
|
||||
"command_about_desc": "tietoa",
|
||||
"command_about_embed_title": "Tietoa minusta",
|
||||
"command_about_embed_field1": "Nimi",
|
||||
"command_about_embed_field2name": "Versio",
|
||||
"command_about_embed_field2value": "Paikallinen: {local_version} \nUusin: {latest_version}",
|
||||
"command_desc_stats": "statistiikat",
|
||||
"command_stats_embed_title": "Botin statistiikat",
|
||||
"command_stats_embed_desc": "Tietoa botin muistista.",
|
||||
"command_stats_embed_field1name": "Tiedostostatistiikat",
|
||||
"command_stats_embed_field1value": "Koko: {file_size} tavua\nLinjoja: {line_count}",
|
||||
"command_stats_embed_field2name": "Versio",
|
||||
"command_stats_embed_field2value": "Paikallinen: {local_version} \nUusin: {latest_version}",
|
||||
"command_stats_embed_field3name": "Muuttajainformaatio",
|
||||
"command_stats_embed_field3value": "Nimi: {NAME} \nEtuliite: {PREFIX} \nOmistajan ID: {ownerid} \nJäähtymisaika: {cooldown_time} \nPing-linja: {PING_LINE} \nMuistin jako päällä: {showmemenabled} \nOppiminen käyttäjistä: {USERTRAIN_ENABLED} \nViimeisin satunnainen TT: {last_random_talk_time} \nLaulu: {song} \nRoisketeksti: ```{splashtext}```"
|
||||
}
|
||||
|
|
@ -1,58 +1,4 @@
|
|||
{
|
||||
"memory_file_valid": "Il file JSON è valido!",
|
||||
"file_aint_utf8": "Il file non è un UTF-8 valido. Forse è binario?",
|
||||
"psutil_not_installed": "Controllo memoria saltato.",
|
||||
"not_cloned": "Goober non è stato clonato! Clonalo da GitHub.",
|
||||
"checks_disabled": "I controlli sono disabilitati!",
|
||||
"unhandled_exception": "Si è verificata un'eccezione non gestita. Segnala questo problema su GitHub, per favore.",
|
||||
"active_users:": "Utenti attivi:",
|
||||
"spacy_initialized": "spaCy e spacytextblob sono pronti.",
|
||||
"error_fetching_active_users": "Errore nel recupero degli utenti attivi: {error}",
|
||||
"spacy_model_not_found": "Il modello spaCy non è stato trovato! Lo sto scaricando...",
|
||||
"env_file_not_found": "Il file .env non è stato trovato! Crea un file con le variabili richieste.",
|
||||
"error fetching_active_users": "Errore nel recupero degli utenti attivi:",
|
||||
"error_sending_alive_ping": "Errore nell'invio di aliveping:",
|
||||
"already_started": "Sono già avviato! Non aggiorno...",
|
||||
"please_restart": "Riavvia goober!",
|
||||
"local_ahead": "Il ramo locale {remote}/{branch} è aggiornato o avanti. Nessun aggiornamento...",
|
||||
"remote_ahead": "Il ramo remoto {remote}/{branch} è avanti. Aggiornamento in corso...",
|
||||
"cant_find_local_version": "Impossibile trovare la variabile local_version! O è stata manomessa e non è un intero!",
|
||||
"running_prestart_checks": "Esecuzione dei controlli pre-avvio...",
|
||||
"continuing_in_seconds": "Continuo tra {seconds} secondi... Premi un tasto per saltare.",
|
||||
"missing_requests_psutil": "Mancano requests e psutil! Installali con pip: `pip install requests psutil`",
|
||||
"requirements_not_found": "requirements.txt non trovato in {path} è stato manomesso?",
|
||||
"warning_failed_parse_imports": "Attenzione: impossibile analizzare le importazioni da {filename}: {error}",
|
||||
"cogs_dir_not_found": "Cartella cogs non trovata in {path}, scansione saltata.",
|
||||
"std_lib_local_skipped": "LIB STD / LOCALE {package} (controllo saltato)",
|
||||
"ok_installed": "OK",
|
||||
"missing_package": "REQUISITO MANCANTE",
|
||||
"missing_package2": "non è installato",
|
||||
"missing_packages_detected": "Pacchetti mancanti rilevati:",
|
||||
"telling_goober_central": "Segnalazione a goober central su {url}",
|
||||
"failed_to_contact": "Impossibile contattare {url}: {error}",
|
||||
"all_requirements_satisfied": "Tutti i requisiti sono soddisfatti.",
|
||||
"ping_to": "Ping a {host}: {latency} ms",
|
||||
"high_latency": "Latenza elevata rilevata! Potresti riscontrare ritardi nelle risposte.",
|
||||
"could_not_parse_latency": "Impossibile analizzare la latenza.",
|
||||
"ping_failed": "Ping a {host} fallito.",
|
||||
"error_running_ping": "Errore durante l'esecuzione del ping: {error}",
|
||||
"memory_usage": "Utilizzo memoria: {used} GB / {total} GB ({percent}%)",
|
||||
"memory_above_90": "Utilizzo memoria sopra il 90% ({percent}%). Considera di liberare memoria.",
|
||||
"total_memory": "Memoria totale: {total} GB",
|
||||
"used_memory": "Memoria usata: {used} GB",
|
||||
"low_free_memory": "Poca memoria libera! Solo {free} GB disponibili.",
|
||||
"measuring_cpu": "Misurazione utilizzo CPU per core...",
|
||||
"core_usage": "Core {idx}: [{bar}] {usage}%",
|
||||
"total_cpu_usage": "Utilizzo totale CPU: {usage}%",
|
||||
"high_avg_cpu": "Utilizzo medio CPU elevato: {usage}%",
|
||||
"really_high_cpu": "Carico CPU molto alto! Il sistema potrebbe rallentare o bloccarsi.",
|
||||
"memory_file": "File memoria: {size} MB",
|
||||
"memory_file_large": "Il file di memoria è 1GB o più, valuta di svuotarlo.",
|
||||
"memory_file_corrupted": "File memoria corrotto! Errore JSON decode: {error}",
|
||||
"consider_backup_memory": "Valuta di fare un backup e ricreare il file di memoria.",
|
||||
"memory_file_encoding": "Problemi di codifica nel file memoria: {error}",
|
||||
"error_reading_memory": "Errore nella lettura del file memoria: {error}",
|
||||
"memory_file_not_found": "File memoria non trovato.",
|
||||
"modification_warning": "Goober è stato modificato! Verifiche del server saltate completamente...",
|
||||
"reported_version": "Versione segnalata:",
|
||||
"current_hash": "Hash attuale:",
|
||||
|
@ -60,8 +6,6 @@
|
|||
"version_error": "Impossibile recuperare le informazioni sulla versione. Codice di stato",
|
||||
"loaded_cog": "Cog caricato:",
|
||||
"cog_fail": "Impossibile caricare il cog:",
|
||||
"loaded_cog2": "Module caricato:",
|
||||
"cog_fail2": "Impossibile caricare il module:",
|
||||
"no_model": "Nessun modello Markov salvato trovato. Iniziamo da zero.",
|
||||
"folder_created": "Cartella '{folder_name}' creata.",
|
||||
"folder_exists": "La cartella '{folder_name}' esiste già. Saltando...",
|
||||
|
@ -69,13 +13,12 @@
|
|||
"synced_commands": "Sincronizzati",
|
||||
"synced_commands2": "comandi!",
|
||||
"fail_commands_sync": "Impossibile sincronizzare i comandi:",
|
||||
"started": "{name} è stato avviato!\nIl palco è tuo!",
|
||||
"started": "Goober è stato avviato!",
|
||||
"name_check": "Errore nel controllo disponibilità del nome:",
|
||||
"name_taken": "Il nome è già preso. Scegli un nome diverso.",
|
||||
"name_check2": "Errore durante il controllo della disponibilità del nome:",
|
||||
"add_token": "Token: {token}\nAggiungi questo token al tuo file .env come",
|
||||
"token_exists": "Il token esiste già in .env. Continuando con il token esistente.",
|
||||
"goober_server_alert": "Avviso da goober central!\n",
|
||||
"registration_error": "Errore durante la registrazione:",
|
||||
"version_backup": "Backup creato:",
|
||||
"backup_error": "Errore: {LOCAL_VERSION_FILE} non trovato per il backup.",
|
||||
|
@ -102,7 +45,7 @@
|
|||
"command_markov_retrain": "Rafforzamento del modello Markov in corso... Attendere.",
|
||||
"command_markov_memory_not_found": "Errore: file di memoria non trovato!",
|
||||
"command_markov_memory_is_corrupt": "Errore: file di memoria corrotto!",
|
||||
"command_markov_retraining": "Elaborazione di {data_size} punti dati...",
|
||||
"command_markov_retraining": "Elaborazione di {processed_data}/{data_size} punti dati...",
|
||||
"command_markov_retrain_successful": "Modello Markov rafforzato con successo utilizzando {data_size} punti dati!",
|
||||
"command_desc_talk": "parla n come stuf",
|
||||
"command_talk_insufficent_text": "Ho bisogno di imparare di più dai messaggi prima di poter parlare.",
|
||||
|
@ -114,9 +57,7 @@
|
|||
"command_help_categories_admin": "Amministrazione",
|
||||
"command_help_categories_custom": "Comandi personalizzati",
|
||||
"command_ran": "Info: {message.author.name} ha eseguito {message.content}",
|
||||
"command_ran_s": "Info: {interaction.user} ha eseguito ",
|
||||
"command_desc_ping": "ping",
|
||||
"command_desc_setlang": "Imposta una nuova lingua per il bot (temporaneamente)",
|
||||
"command_ping_embed_desc": "Latenza del bot:",
|
||||
"command_ping_footer": "Richiesto da",
|
||||
"command_about_desc": "informazioni",
|
||||
|
@ -132,6 +73,6 @@
|
|||
"command_stats_embed_field2name": "Versione",
|
||||
"command_stats_embed_field2value": "Locale: {local_version} \nUltima: {latest_version}",
|
||||
"command_stats_embed_field3name": "Informazioni sulle variabili",
|
||||
"command_stats_embed_field3value": "Nome: {NAME} \nPrefisso: {PREFIX} \nID Proprietario: {ownerid}\nLinea ping: {PING_LINE} \nMemoria Condivisa Abilitata: {showmemenabled} \nAddestramento Utente Abilitato: {USERTRAIN_ENABLED}\nCanzone: {song} \nSplashtext: ```{splashtext}```"
|
||||
"command_stats_embed_field3value": "Nome: {NAME} \nPrefisso: {PREFIX} \nID Proprietario: {ownerid} \nCooldown: {cooldown_time} \nLinea ping: {PING_LINE} \nMemoria Condivisa Abilitata: {showmemenabled} \nAddestramento Utente Abilitato: {USERTRAIN_ENABLED} \nUltima TT Casuale: {last_random_talk_time} \nCanzone: {song} \nSplashtext: ```{splashtext}```"
|
||||
}
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
# Modules Directory
|
||||
|
||||
This folder contains core module files for the project.
|
||||
|
||||
**Important:**
|
||||
Do **not** modify the files in this directory if you plan to update the project in the future. Any changes made here may be overwritten during updates, or may cause Git to detect modifications and refuse to update properly.
|
||||
|
||||
If you need to make changes, consider contributing upstream or using extension mechanisms provided by the project.
|
|
@ -1,71 +0,0 @@
|
|||
import os
|
||||
import platform
|
||||
from typing import Callable, List
|
||||
from dotenv import load_dotenv
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
|
||||
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)
|
||||
|
||||
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}90m"
|
||||
RESET = f"{ANSI}0m"
|
||||
|
||||
VERSION_URL = "https://raw.githubusercontent.com/gooberinc/version/main"
|
||||
UPDATE_URL = VERSION_URL + "/latest_version.json"
|
||||
print(UPDATE_URL)
|
||||
LOCAL_VERSION_FILE = "current_version.txt"
|
||||
|
||||
# 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")
|
||||
|
||||
# gooberTOKEN = os.getenv("GOOBERTOKEN")
|
||||
# splashtext = os.getenv("SPLASHTEXT")
|
||||
# ownerid = int(os.getenv("OWNERID", "0"))
|
||||
# showmemenabled = os.getenv("SHOWMEMENABLED")
|
||||
|
||||
|
||||
# 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 = "2.3.3"
|
||||
os.environ["gooberlocal_version"] = local_version
|
||||
beta = get_git_branch() == "dev"
|
217
modules/image.py
|
@ -1,217 +0,0 @@
|
|||
import os
|
||||
import re
|
||||
import random
|
||||
import shutil
|
||||
import tempfile
|
||||
from typing import Optional, List
|
||||
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
||||
from modules.markovmemory import load_markov_model
|
||||
from modules.sentenceprocessing import (
|
||||
improve_sentence_coherence,
|
||||
rephrase_for_coherence,
|
||||
)
|
||||
|
||||
generated_sentences = set()
|
||||
|
||||
|
||||
def load_font(size):
|
||||
return ImageFont.truetype("assets/fonts/Impact.ttf", size=size)
|
||||
|
||||
|
||||
def load_tnr(size):
|
||||
return ImageFont.truetype("assets/fonts/TNR.ttf", size=size)
|
||||
|
||||
|
||||
def draw_text_with_outline(draw, text, x, y, font):
|
||||
outline_offsets = [
|
||||
(-2, -2),
|
||||
(-2, 2),
|
||||
(2, -2),
|
||||
(2, 2),
|
||||
(0, -2),
|
||||
(0, 2),
|
||||
(-2, 0),
|
||||
(2, 0),
|
||||
]
|
||||
for ox, oy in outline_offsets:
|
||||
draw.text((x + ox, y + oy), text, font=font, fill="black")
|
||||
draw.text((x, y), text, font=font, fill="white")
|
||||
|
||||
|
||||
def fits_in_width(text, font, max_width, draw):
|
||||
bbox = draw.textbbox((0, 0), text, font=font)
|
||||
text_width = bbox[2] - bbox[0]
|
||||
return text_width <= max_width
|
||||
|
||||
|
||||
def split_text_to_fit(text, font, max_width, draw):
|
||||
words = text.split()
|
||||
for i in range(len(words), 0, -1):
|
||||
top_text = " ".join(words[:i])
|
||||
bottom_text = " ".join(words[i:])
|
||||
if fits_in_width(top_text, font, max_width, draw) and fits_in_width(
|
||||
bottom_text, font, max_width, draw
|
||||
):
|
||||
return top_text, bottom_text
|
||||
midpoint = len(words) // 2
|
||||
return " ".join(words[:midpoint]), " ".join(words[midpoint:])
|
||||
|
||||
|
||||
async def gen_meme(input_image_path, sentence_size=5, max_attempts=10):
|
||||
markov_model = load_markov_model()
|
||||
if not markov_model or not os.path.isfile(input_image_path):
|
||||
return None
|
||||
|
||||
attempt = 0
|
||||
while attempt < max_attempts:
|
||||
with Image.open(input_image_path).convert("RGBA") as img:
|
||||
draw = ImageDraw.Draw(img)
|
||||
width, height = img.size
|
||||
|
||||
font_size = int(height / 10)
|
||||
font = load_font(font_size)
|
||||
|
||||
response = None
|
||||
for _ in range(20):
|
||||
if sentence_size == 1:
|
||||
candidate = markov_model.make_short_sentence(
|
||||
max_chars=100, tries=100
|
||||
)
|
||||
if candidate:
|
||||
candidate = candidate.split()[0]
|
||||
else:
|
||||
candidate = markov_model.make_sentence(
|
||||
tries=100, max_words=sentence_size
|
||||
)
|
||||
|
||||
if candidate and candidate not in generated_sentences:
|
||||
if sentence_size > 1:
|
||||
candidate = improve_sentence_coherence(candidate)
|
||||
generated_sentences.add(candidate)
|
||||
response = candidate
|
||||
break
|
||||
|
||||
if not response:
|
||||
response = "NO TEXT GENERATED"
|
||||
|
||||
cleaned_response = re.sub(r"[^\w\s]", "", response).lower()
|
||||
coherent_response = rephrase_for_coherence(cleaned_response).upper()
|
||||
|
||||
bbox = draw.textbbox((0, 0), coherent_response, font=font)
|
||||
text_width = bbox[2] - bbox[0]
|
||||
text_height_px = bbox[3] - bbox[1]
|
||||
max_text_height = height // 4
|
||||
|
||||
if text_width <= width and text_height_px <= max_text_height:
|
||||
draw_text_with_outline(
|
||||
draw, coherent_response, (width - text_width) / 2, 0, font
|
||||
)
|
||||
img.save(input_image_path)
|
||||
return input_image_path
|
||||
else:
|
||||
top_text, bottom_text = split_text_to_fit(
|
||||
coherent_response, font, width, draw
|
||||
)
|
||||
|
||||
top_bbox = draw.textbbox((0, 0), top_text, font=font)
|
||||
bottom_bbox = draw.textbbox((0, 0), bottom_text, font=font)
|
||||
|
||||
top_height = top_bbox[3] - top_bbox[1]
|
||||
bottom_height = bottom_bbox[3] - bottom_bbox[1]
|
||||
|
||||
if top_height <= max_text_height and bottom_height <= max_text_height:
|
||||
draw_text_with_outline(
|
||||
draw,
|
||||
top_text,
|
||||
(width - (top_bbox[2] - top_bbox[0])) / 2,
|
||||
0,
|
||||
font,
|
||||
)
|
||||
y_bottom = height - bottom_height - int(height * 0.04)
|
||||
draw_text_with_outline(
|
||||
draw,
|
||||
bottom_text,
|
||||
(width - (bottom_bbox[2] - bottom_bbox[0])) / 2,
|
||||
y_bottom,
|
||||
font,
|
||||
)
|
||||
img.save(input_image_path)
|
||||
return input_image_path
|
||||
|
||||
attempt += 1
|
||||
|
||||
with Image.open(input_image_path).convert("RGBA") as img:
|
||||
draw = ImageDraw.Draw(img)
|
||||
width, height = img.size
|
||||
font_size = int(height / 10)
|
||||
font = load_font(font_size)
|
||||
|
||||
truncated = coherent_response[:100]
|
||||
bbox = draw.textbbox((0, 0), truncated, font=font)
|
||||
text_width = bbox[2] - bbox[0]
|
||||
draw_text_with_outline(draw, truncated, (width - text_width) / 2, 0, font)
|
||||
img.save(input_image_path)
|
||||
return input_image_path
|
||||
|
||||
|
||||
async def gen_demotivator(input_image_path, max_attempts=5):
|
||||
markov_model = load_markov_model()
|
||||
if not markov_model or not os.path.isfile(input_image_path):
|
||||
return None
|
||||
|
||||
attempt = 0
|
||||
while attempt < max_attempts:
|
||||
with Image.open(input_image_path).convert("RGB") as img:
|
||||
size = max(img.width, img.height)
|
||||
frame_thick = int(size * 0.0054)
|
||||
inner_size = size - 2 * frame_thick
|
||||
resized_img = img.resize((inner_size, inner_size), Image.LANCZOS)
|
||||
framed = Image.new("RGB", (size, size), "white")
|
||||
framed.paste(resized_img, (frame_thick, frame_thick))
|
||||
landscape_w = int(size * 1.5)
|
||||
caption_h = int(size * 0.3)
|
||||
canvas_h = framed.height + caption_h
|
||||
canvas = Image.new("RGB", (landscape_w, canvas_h), "black")
|
||||
# the above logic didnt even work, fml
|
||||
fx = (landscape_w - framed.width) // 2
|
||||
canvas.paste(framed, (fx, 0))
|
||||
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
|
||||
title = subtitle = None
|
||||
for _ in range(20):
|
||||
t = markov_model.make_sentence(tries=100, max_words=4)
|
||||
s = markov_model.make_sentence(tries=100, max_words=5)
|
||||
if t and s and t != s:
|
||||
title = t.upper()
|
||||
subtitle = s.capitalize()
|
||||
break
|
||||
if not title:
|
||||
title = "DEMOTIVATOR"
|
||||
if not subtitle:
|
||||
subtitle = "no text generated"
|
||||
|
||||
title_sz = int(caption_h * 0.4)
|
||||
sub_sz = int(caption_h * 0.25)
|
||||
title_font = load_tnr(title_sz)
|
||||
sub_font = load_tnr(sub_sz)
|
||||
|
||||
bbox = draw.textbbox((0, 0), title, font=title_font)
|
||||
txw, txh = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
||||
tx = (landscape_w - txw) // 2
|
||||
ty = framed.height + int(caption_h * 0.1)
|
||||
draw_text_with_outline(draw, title, tx, ty, title_font)
|
||||
|
||||
bbox = draw.textbbox((0, 0), subtitle, font=sub_font)
|
||||
sxw, sxh = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
||||
sx = (landscape_w - sxw) // 2
|
||||
sy = ty + txh + int(caption_h * 0.05)
|
||||
for ox, oy in [(-1, -1), (1, -1), (-1, 1), (1, 1)]:
|
||||
draw.text((sx + ox, sy + oy), subtitle, font=sub_font, fill="black")
|
||||
draw.text((sx, sy), subtitle, font=sub_font, fill="#AAAAAA")
|
||||
|
||||
canvas.save(input_image_path)
|
||||
return input_image_path
|
||||
|
||||
attempt += 1
|
||||
return None
|
|
@ -1,220 +0,0 @@
|
|||
# The MIT License (MIT)
|
||||
|
||||
# Copyright (c) 2025 ctih1
|
||||
|
||||
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
# of this software and associated documentation files (the "Software"), to deal
|
||||
# in the Software without restriction, including without limitation the rights
|
||||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
# copies of the Software, and to permit persons to whom the Software is
|
||||
# furnished to do so, subject to the following conditions:
|
||||
|
||||
# The above copyright notice and this permission notice shall be included in
|
||||
# all copies or substantial portions of the Software.
|
||||
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
# THE SOFTWARE.
|
||||
|
||||
import os
|
||||
from typing import Dict, List, Literal
|
||||
import json
|
||||
import sys
|
||||
import logging
|
||||
import time
|
||||
|
||||
NOTICE = """
|
||||
# This file was automatically created from localization JSON files.
|
||||
# DO NOT EDIT THIS FILE DIRECTLY. If you want to edit a translation, please use the language's JSON file.
|
||||
|
||||
#fmt: off
|
||||
"""
|
||||
|
||||
|
||||
logger = logging.getLogger("kaannos")
|
||||
|
||||
|
||||
class LanguageCollector:
|
||||
def __init__(self, language_dir: str) -> None:
|
||||
self.path: str = language_dir
|
||||
self.languages: Dict[str, Dict[str, str]] = {}
|
||||
|
||||
for file in os.listdir(self.path):
|
||||
if not file.endswith(".json") or len(file) > 7:
|
||||
logger.debug(f"Skipping {file}")
|
||||
continue
|
||||
|
||||
locale: str = file.split(".json")[0]
|
||||
logger.info(f"Discovered {file}")
|
||||
with open(os.path.join(self.path, file), "r", encoding="UTF-8") as f:
|
||||
keys: Dict[str, str] = json.load(f)
|
||||
self.languages[locale] = keys
|
||||
|
||||
self.find_missing_keys()
|
||||
|
||||
def find_missing_keys(self) -> None:
|
||||
primary_language_keys: Dict[str, str] = self.languages["en"]
|
||||
|
||||
for key in primary_language_keys:
|
||||
for language in self.languages:
|
||||
if key not in self.languages[language]:
|
||||
logger.warning(f"Key {key} missing from {language}")
|
||||
|
||||
for language in self.languages:
|
||||
for key in self.languages[language]:
|
||||
if key not in primary_language_keys:
|
||||
logger.warning(f"Leftover key {key} found from {language}")
|
||||
|
||||
|
||||
class Script:
|
||||
def __init__(self) -> None:
|
||||
self.script: str = ""
|
||||
|
||||
def add_line(self, content, indent: int = 0, newline: bool = True) -> None:
|
||||
tabs = "\t" * indent
|
||||
newline_content = "\n" if newline else ""
|
||||
|
||||
self.script += f"{tabs}{content}{newline_content}"
|
||||
|
||||
|
||||
def process_name(key: str) -> str:
|
||||
return key.replace(" ", "_").replace(":", "").lower()
|
||||
|
||||
|
||||
def find_args(string: str) -> List[str]:
|
||||
variable_open: bool = False
|
||||
temp_content: str = ""
|
||||
|
||||
variables: List[str] = []
|
||||
for char in string:
|
||||
if variable_open:
|
||||
if char == "}":
|
||||
variable_open = False
|
||||
variables.append(temp_content)
|
||||
temp_content = ""
|
||||
continue
|
||||
|
||||
if char == "{":
|
||||
raise SyntaxError("Variable already open!")
|
||||
|
||||
temp_content += char
|
||||
|
||||
else:
|
||||
if char == "}":
|
||||
raise SyntaxError("Trying to close a nonexistant variable")
|
||||
|
||||
if char == "{":
|
||||
variable_open = True
|
||||
|
||||
return variables
|
||||
|
||||
|
||||
def convert_args(
|
||||
inp: str, vars: List[str], mode: Literal["brackets", "none"] = "brackets"
|
||||
) -> str:
|
||||
replacements = {".": "_", ",": "_"}
|
||||
|
||||
for var in vars:
|
||||
cleaned_var = var
|
||||
for key, val in replacements.items():
|
||||
cleaned_var = cleaned_var.replace(key, val)
|
||||
|
||||
if mode == "none":
|
||||
inp = inp.replace(f"{var}", f"{cleaned_var}")
|
||||
else:
|
||||
inp = inp.replace(f"{{{var}}}", f"{{{cleaned_var}}}")
|
||||
|
||||
return inp
|
||||
|
||||
|
||||
class GenerateScript:
|
||||
def __init__(
|
||||
self,
|
||||
primary_lang: str,
|
||||
language_data: Dict[str, Dict[str, str]],
|
||||
use_typing: bool = True,
|
||||
output_path: str = "out.py",
|
||||
generate_comments: bool = True,
|
||||
):
|
||||
self.data = language_data
|
||||
self.primary = primary_lang
|
||||
self.script = Script()
|
||||
self.uses_typing: bool = use_typing
|
||||
self.output = output_path
|
||||
self.generate_comments = generate_comments
|
||||
|
||||
def create(self):
|
||||
# I really don't like this implementation but also it works
|
||||
self.script.add_line(NOTICE)
|
||||
if self.uses_typing:
|
||||
self.script.add_line("from typing import Literal, List")
|
||||
self.script.add_line(f"Language=Literal{list(self.data.keys())}")
|
||||
self.script.add_line(
|
||||
f"languages: List[Language] = {list(self.data.keys())}"
|
||||
)
|
||||
self.script.add_line(f"default_lang: Language | str='{self.primary}'")
|
||||
self.script.add_line(
|
||||
"def change_language(new_lang: Language | str) -> None: global default_lang; default_lang = new_lang"
|
||||
)
|
||||
else:
|
||||
self.script.add_line(f"languages = {list(self.data.keys())}")
|
||||
self.script.add_line(f"default_lang='{self.primary}'")
|
||||
self.script.add_line(
|
||||
"def change_language(new_lang): global default_lang; default_lang = new_lang"
|
||||
)
|
||||
|
||||
self.primary_data = self.data[self.primary]
|
||||
|
||||
for key in self.primary_data:
|
||||
args = find_args(self.primary_data[key])
|
||||
|
||||
self.script.add_line(
|
||||
f"def {process_name(key)}({convert_args(','.join([*args, 'lang:str|None=None' if self.uses_typing else 'lang']), args, 'none')}):"
|
||||
)
|
||||
if self.generate_comments:
|
||||
self.script.add_line('"""', 1)
|
||||
self.script.add_line("### Locales", 1)
|
||||
for language in self.data:
|
||||
self.script.add_line(
|
||||
f"- {language.capitalize()}: **{self.data[language].get(key, self.primary_data[key])}**",
|
||||
1,
|
||||
)
|
||||
self.script.add_line('"""', 1)
|
||||
self.script.add_line("if not lang: lang=default_lang", 1)
|
||||
for language in self.data:
|
||||
formatted_map = "{"
|
||||
for arg in args:
|
||||
formatted_map += f'"{convert_args(arg, args, "none")}": {convert_args(arg, args, "none")},'
|
||||
formatted_map = formatted_map[:-1] + "}"
|
||||
self.script.add_line(
|
||||
f"""if lang == '{language}': return {convert_args(json.dumps(
|
||||
self.data[language].get(key,self.primary_data[key]),
|
||||
ensure_ascii=False
|
||||
), args)}{f'.format_map({formatted_map})' if len(args) > 0 else ''}""",
|
||||
1,
|
||||
)
|
||||
|
||||
self.script.add_line(
|
||||
"else: raise ValueError(f'Invalid language {lang}')", 1
|
||||
)
|
||||
with open(self.output, "w", encoding="UTF-8") as f:
|
||||
f.write(self.script.script)
|
||||
|
||||
|
||||
def build_result(
|
||||
primary_lang: str,
|
||||
locale_dir: str,
|
||||
types: bool,
|
||||
output_path: str,
|
||||
generate_comments: bool = True,
|
||||
):
|
||||
start = time.time()
|
||||
lc = LanguageCollector(locale_dir)
|
||||
GenerateScript(
|
||||
primary_lang, lc.languages, types, output_path, generate_comments
|
||||
).create()
|
||||
logger.info(f"Done in {time.time() - start}s")
|
2340
modules/keys.py
|
@ -1,28 +0,0 @@
|
|||
import logging
|
||||
from modules.globalvars import *
|
||||
|
||||
|
||||
class GooberFormatter(logging.Formatter):
|
||||
def __init__(self, colors: bool = True): # Disable colors for TXT output
|
||||
self.colors = colors
|
||||
|
||||
self._format = f"[ %(levelname)-8s ]: %(message)s {DEBUG} [%(asctime)s.%(msecs)03d] (%(filename)s:%(funcName)s) {RESET}"
|
||||
|
||||
self.FORMATS = {
|
||||
logging.DEBUG: DEBUG + self._format + RESET,
|
||||
logging.INFO: self._format.replace(
|
||||
"%(levelname)-8s", f"{GREEN}%(levelname)-8s{RESET}"
|
||||
),
|
||||
logging.WARNING: YELLOW + self._format + RESET,
|
||||
logging.ERROR: RED + self._format + RESET,
|
||||
logging.CRITICAL: PURPLE + self._format + RESET,
|
||||
}
|
||||
|
||||
def format(self, record: logging.LogRecord):
|
||||
if self.colors:
|
||||
log_fmt = self.FORMATS.get(record.levelno) # Add colors
|
||||
else:
|
||||
log_fmt = self._format # Just use the default format
|
||||
|
||||
formatter = logging.Formatter(log_fmt, datefmt="%m/%d/%y %H:%M:%S")
|
||||
return formatter.format(record)
|
|
@ -1,81 +0,0 @@
|
|||
import os
|
||||
import json
|
||||
import markovify
|
||||
import pickle
|
||||
from modules.globalvars import *
|
||||
import logging
|
||||
import modules.keys as k
|
||||
from modules.settings import instance as settings_manager
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
|
||||
# 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)}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
# 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, additional_data=None) -> markovify.NewlineText | None:
|
||||
if not memory:
|
||||
return None
|
||||
|
||||
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)
|
||||
)
|
||||
|
||||
if not filtered_memory:
|
||||
return None
|
||||
|
||||
text = "\n".join(filtered_memory)
|
||||
model = markovify.NewlineText(text, state_size=2)
|
||||
return model
|
||||
|
||||
|
||||
# Save the Markov model to a pickle file
|
||||
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}.")
|
||||
|
||||
|
||||
# Load the Markov model from a pickle file
|
||||
def load_markov_model(filename="markov_model.pkl"):
|
||||
try:
|
||||
with open(filename, "rb") as f:
|
||||
model = pickle.load(f)
|
||||
logger.info(f"{k.model_loaded()} {filename}.{RESET}")
|
||||
return model
|
||||
except FileNotFoundError:
|
||||
logger.error(f"{filename} {k.not_found()}{RESET}")
|
||||
return None
|
|
@ -1,36 +0,0 @@
|
|||
from functools import wraps
|
||||
import discord
|
||||
|
||||
import discord.ext
|
||||
import discord.ext.commands
|
||||
|
||||
from modules.settings import instance as settings_manager
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
class PermissionError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def requires_admin():
|
||||
async def wrapper(ctx: discord.ext.commands.Context):
|
||||
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
|
||||
|
||||
command = ctx.command
|
||||
if not command:
|
||||
logger.info(f"Unknown command ran {ctx.message}")
|
||||
else:
|
||||
logger.info(
|
||||
f'Command {settings["bot"]["prefix"]}{command.name} @{ctx.author.name}'
|
||||
)
|
||||
return True
|
||||
|
||||
return discord.ext.commands.check(wrapper)
|
|
@ -1,304 +0,0 @@
|
|||
from modules.globalvars import *
|
||||
import time
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import sysconfig
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
from spacy.util import is_package
|
||||
import importlib.metadata
|
||||
import logging
|
||||
import modules.keys as k
|
||||
from modules.settings import instance as settings_manager
|
||||
from modules.sync_conenctor import instance as sync_hub
|
||||
|
||||
settings = settings_manager.settings
|
||||
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
# import shutil
|
||||
psutilavaliable = True
|
||||
try:
|
||||
import requests
|
||||
import psutil
|
||||
except ImportError:
|
||||
psutilavaliable = False
|
||||
logger.error(k.missing_requests_psutil())
|
||||
|
||||
|
||||
def check_for_model():
|
||||
if is_package("en_core_web_sm"):
|
||||
logger.info("Model is installed.")
|
||||
else:
|
||||
logger.info("Model is not installed.")
|
||||
|
||||
|
||||
def iscloned():
|
||||
if os.path.exists(".git"):
|
||||
return True
|
||||
else:
|
||||
logger.error(f"{k.not_cloned()}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def get_stdlib_modules():
|
||||
stdlib_path = pathlib.Path(sysconfig.get_paths()["stdlib"])
|
||||
modules = set()
|
||||
if hasattr(sys, "builtin_module_names"):
|
||||
modules.update(sys.builtin_module_names)
|
||||
for file in stdlib_path.glob("*.py"):
|
||||
if file.stem != "__init__":
|
||||
modules.add(file.stem)
|
||||
for folder in stdlib_path.iterdir():
|
||||
if folder.is_dir() and (folder / "__init__.py").exists():
|
||||
modules.add(folder.name)
|
||||
for file in stdlib_path.glob("*.*"):
|
||||
if file.suffix in (".so", ".pyd"):
|
||||
modules.add(file.stem)
|
||||
|
||||
return modules
|
||||
|
||||
|
||||
def check_requirements():
|
||||
STD_LIB_MODULES = get_stdlib_modules()
|
||||
PACKAGE_ALIASES = {
|
||||
"discord": "discord.py",
|
||||
"better_profanity": "better-profanity",
|
||||
"dotenv": "python-dotenv",
|
||||
"pil": "pillow",
|
||||
"websocket": "websocket-client"
|
||||
}
|
||||
|
||||
parent_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
requirements_path = os.path.abspath(
|
||||
os.path.join(parent_dir, "..", "requirements.txt")
|
||||
)
|
||||
|
||||
if not os.path.exists(requirements_path):
|
||||
logger.error(f"{k.requirements_not_found(path=requirements_path)}")
|
||||
return
|
||||
|
||||
with open(requirements_path, "r") as f:
|
||||
lines = f.readlines()
|
||||
requirements = set()
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
base_pkg = line.split("==")[0].lower()
|
||||
aliased_pkg = PACKAGE_ALIASES.get(base_pkg, base_pkg)
|
||||
requirements.add(aliased_pkg)
|
||||
|
||||
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(k.std_lib_local_skipped(package=req))
|
||||
continue
|
||||
|
||||
check_name = req.lower()
|
||||
|
||||
if check_name in installed_packages:
|
||||
logger.info(f"{k.ok_installed()} {check_name}")
|
||||
else:
|
||||
logger.error(f"{k.missing_package()} {check_name} {k.missing_package2()}")
|
||||
missing.append(check_name)
|
||||
|
||||
if missing:
|
||||
logger.error(k.missing_packages_detected())
|
||||
for pkg in missing:
|
||||
print(f" - {pkg}")
|
||||
sys.exit(1)
|
||||
else:
|
||||
logger.info(k.all_requirements_satisfied())
|
||||
|
||||
|
||||
def check_latency():
|
||||
host = "1.1.1.1"
|
||||
system = platform.system()
|
||||
|
||||
if system == "Windows":
|
||||
cmd = ["ping", "-n", "1", "-w", "1000", host]
|
||||
latency_pattern = r"Average = (\d+)ms"
|
||||
|
||||
elif system == "Darwin":
|
||||
cmd = ["ping", "-c", "1", host]
|
||||
latency_pattern = r"time=([\d\.]+) ms"
|
||||
|
||||
else:
|
||||
cmd = ["ping", "-c", "1", "-W", "1", host]
|
||||
latency_pattern = r"time=([\d\.]+) ms"
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
match = re.search(latency_pattern, result.stdout)
|
||||
if match:
|
||||
latency_ms = float(match.group(1))
|
||||
logger.info(k.ping_to(host=host, latency=latency_ms))
|
||||
if latency_ms > 300:
|
||||
logger.warning(f"{k.high_latency()}")
|
||||
else:
|
||||
logger.warning(k.could_not_parse_latency())
|
||||
else:
|
||||
print(result.stderr)
|
||||
logger.error(f"{k.ping_failed(host=host)}{RESET}")
|
||||
except Exception as e:
|
||||
logger.error(k.error_running_ping(error=e))
|
||||
|
||||
|
||||
def check_memory():
|
||||
if psutilavaliable == False:
|
||||
return
|
||||
try:
|
||||
memory_info = psutil.virtual_memory() # type: ignore
|
||||
total_memory = memory_info.total / (1024**3)
|
||||
used_memory = memory_info.used / (1024**3)
|
||||
free_memory = memory_info.available / (1024**3)
|
||||
|
||||
logger.info(
|
||||
k.memory_usage(
|
||||
used=used_memory,
|
||||
total=total_memory,
|
||||
percent=(used_memory / total_memory) * 100,
|
||||
)
|
||||
)
|
||||
if used_memory > total_memory * 0.9:
|
||||
print(
|
||||
f"{YELLOW}{k.memory_above_90(percent=(used_memory / total_memory) * 100)}{RESET}"
|
||||
)
|
||||
logger.info(k.total_memory(total=total_memory))
|
||||
logger.info(k.used_memory(used=used_memory))
|
||||
if free_memory < 1:
|
||||
logger.warning(f"{k.low_free_memory(free=free_memory)}")
|
||||
|
||||
except ImportError:
|
||||
logger.error(
|
||||
k.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
|
||||
logger.info(k.measuring_cpu())
|
||||
cpu_per_core = psutil.cpu_percent(interval=1, percpu=True) # type: ignore
|
||||
total_cpu = sum(cpu_per_core) / len(cpu_per_core)
|
||||
logger.info(k.total_cpu_usage(usage=total_cpu))
|
||||
|
||||
if total_cpu > 85:
|
||||
logger.warning(f"{k.high_avg_cpu(usage=total_cpu)}")
|
||||
|
||||
if total_cpu > 95:
|
||||
logger.error(k.really_high_cpu())
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def check_memoryjson():
|
||||
try:
|
||||
logger.info(
|
||||
k.memory_file(
|
||||
size=os.path.getsize(settings["bot"]["active_memory"]) / (1024**2)
|
||||
)
|
||||
)
|
||||
if os.path.getsize(settings["bot"]["active_memory"]) > 1_073_741_824:
|
||||
logger.warning(f"{k.memory_file_large()}")
|
||||
try:
|
||||
with open(settings["bot"]["active_memory"], "r", encoding="utf-8") as f:
|
||||
json.load(f)
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
logger.error(f"{k.memory_file_corrupted(error=e)}")
|
||||
logger.warning(f"{k.consider_backup_memory()}")
|
||||
|
||||
except UnicodeDecodeError as e:
|
||||
logger.error(f"{k.memory_file_encoding(error=e)}")
|
||||
logger.warning(f"{k.consider_backup_memory()}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"{k.error_reading_memory(error=e)}")
|
||||
except FileNotFoundError:
|
||||
logger.info(f"{k.memory_file_not_found()}")
|
||||
|
||||
|
||||
def presskey2skip(timeout):
|
||||
if os.name == "nt":
|
||||
import msvcrt
|
||||
|
||||
start_time = time.time()
|
||||
while True:
|
||||
if msvcrt.kbhit():
|
||||
msvcrt.getch()
|
||||
break
|
||||
if time.time() - start_time > timeout:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
else:
|
||||
import select
|
||||
import sys
|
||||
import termios
|
||||
import tty
|
||||
|
||||
fd = sys.stdin.fileno()
|
||||
old_settings = termios.tcgetattr(fd)
|
||||
try:
|
||||
tty.setcbreak(fd)
|
||||
start_time = time.time()
|
||||
while True:
|
||||
if select.select([sys.stdin], [], [], 0)[0]:
|
||||
sys.stdin.read(1)
|
||||
break
|
||||
if time.time() - start_time > timeout:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
finally:
|
||||
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
|
||||
|
||||
def check_synchub():
|
||||
if not sync_hub.connected:
|
||||
logger.warning("Sync hub not connected properly! The bot will not be able to react to messages, or create breaking news unless you disable synchub in settings")
|
||||
else:
|
||||
logger.info("Sync hub is conencted")
|
||||
|
||||
beta = beta
|
||||
|
||||
|
||||
def start_checks():
|
||||
if settings["disable_checks"]:
|
||||
logger.warning(f"{k.checks_disabled()}")
|
||||
return
|
||||
|
||||
logger.info(k.running_prestart_checks())
|
||||
check_for_model()
|
||||
iscloned()
|
||||
check_requirements()
|
||||
check_latency()
|
||||
check_memory()
|
||||
check_memoryjson()
|
||||
check_cpu()
|
||||
check_synchub()
|
||||
if os.path.exists(".env"):
|
||||
pass
|
||||
else:
|
||||
logger.warning(f"{k.env_file_not_found()}")
|
||||
sys.exit(1)
|
||||
if beta == True:
|
||||
logger.warning(
|
||||
f"this build isnt finished yet, some things might not work as expected"
|
||||
)
|
||||
else:
|
||||
pass
|
||||
logger.info(k.continuing_in_seconds(seconds=5))
|
||||
presskey2skip(timeout=5)
|
||||
os.system("cls" if os.name == "nt" else "clear")
|
||||
|
||||
with open(settings["splash_text_loc"], "r") as f:
|
||||
print("".join(f.readlines()))
|
|
@ -1,95 +0,0 @@
|
|||
import re
|
||||
import discord.ext
|
||||
import discord.ext.commands
|
||||
from modules.globalvars import *
|
||||
import spacy
|
||||
from spacy.tokens import Doc
|
||||
from spacytextblob.spacytextblob import SpacyTextBlob
|
||||
import discord
|
||||
import modules.keys as k
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
|
||||
def check_resources():
|
||||
try:
|
||||
nlp = spacy.load("en_core_web_sm")
|
||||
except OSError:
|
||||
logging.critical(k.spacy_model_not_found())
|
||||
spacy.cli.download("en_core_web_sm") # type: ignore
|
||||
nlp = spacy.load("en_core_web_sm")
|
||||
if "spacytextblob" not in nlp.pipe_names:
|
||||
nlp.add_pipe("spacytextblob")
|
||||
logger.info(k.spacy_initialized())
|
||||
|
||||
|
||||
check_resources()
|
||||
|
||||
nlp = spacy.load("en_core_web_sm")
|
||||
nlp.add_pipe("spacytextblob")
|
||||
Doc.set_extension("polarity", getter=lambda doc: doc._.blob.polarity)
|
||||
|
||||
|
||||
def is_positive(sentence):
|
||||
doc = nlp(sentence)
|
||||
sentiment_score = doc._.polarity # from spacytextblob
|
||||
|
||||
debug_message = f"{k.sentence_positivity()} {sentiment_score}{RESET}"
|
||||
logger.debug(debug_message)
|
||||
|
||||
return (
|
||||
sentiment_score > 0.6
|
||||
) # had to raise the bar because it kept saying "death to jews" was fine and it kept reacting to them
|
||||
|
||||
|
||||
async def send_message(
|
||||
ctx: discord.ext.commands.Context,
|
||||
message: str | None = None,
|
||||
embed: discord.Embed | None = None,
|
||||
file: discord.File | None = None,
|
||||
edit: bool = False,
|
||||
message_reference: discord.Message | None = None,
|
||||
) -> discord.Message | None:
|
||||
|
||||
sent_message: discord.Message | None = None
|
||||
|
||||
if edit and message_reference:
|
||||
try:
|
||||
await message_reference.edit(content=message, embed=embed)
|
||||
return message_reference
|
||||
except Exception as e:
|
||||
await ctx.send(f"{k.edit_fail()} {e}")
|
||||
return None
|
||||
|
||||
if embed:
|
||||
sent_message = await ctx.send(embed=embed, content=message)
|
||||
elif file:
|
||||
sent_message = await ctx.send(file=file, content=message)
|
||||
else:
|
||||
sent_message = await ctx.send(content=message)
|
||||
|
||||
return sent_message
|
||||
|
||||
|
||||
def append_mentions_to_18digit_integer(message):
|
||||
pattern = r"\b\d{18}\b"
|
||||
return re.sub(pattern, lambda match: "", message)
|
||||
|
||||
|
||||
def preprocess_message(message):
|
||||
message = append_mentions_to_18digit_integer(message)
|
||||
doc = nlp(message)
|
||||
tokens = [token.text for token in doc if token.is_alpha or token.is_digit]
|
||||
return " ".join(tokens)
|
||||
|
||||
|
||||
def improve_sentence_coherence(sentence):
|
||||
return re.sub(r"\bi\b", "I", sentence)
|
||||
|
||||
|
||||
def rephrase_for_coherence(sentence):
|
||||
words = sentence.split()
|
||||
coherent_sentence = " ".join(words)
|
||||
return coherent_sentence
|
|
@ -1,155 +0,0 @@
|
|||
import json
|
||||
import os
|
||||
from typing import Dict, List, Literal, Mapping, Any, TypedDict
|
||||
from modules.keys import Language
|
||||
import logging
|
||||
import copy
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
ActivityType = Literal["listening", "playing", "streaming", "competing", "watching"]
|
||||
|
||||
class SyncHub(TypedDict):
|
||||
url: str
|
||||
enabled: bool
|
||||
|
||||
class Activity(TypedDict):
|
||||
content: str
|
||||
type: ActivityType
|
||||
|
||||
|
||||
class MiscBotOptions(TypedDict):
|
||||
ping_line: str
|
||||
activity: Activity
|
||||
positive_gifs: List[str]
|
||||
block_profanity: bool
|
||||
|
||||
|
||||
class BotSettings(TypedDict):
|
||||
prefix: str
|
||||
owner_ids: List[int]
|
||||
blacklisted_users: List[int]
|
||||
user_training: bool
|
||||
allow_show_mem_command: bool
|
||||
react_to_messages: bool
|
||||
misc: MiscBotOptions
|
||||
enabled_cogs: List[str]
|
||||
active_memory: str
|
||||
sync_hub: SyncHub
|
||||
|
||||
|
||||
class SettingsType(TypedDict):
|
||||
bot: BotSettings
|
||||
locale: Language
|
||||
name: str
|
||||
auto_update: bool
|
||||
disable_checks: bool
|
||||
splash_text_loc: str
|
||||
cog_settings: Dict[str, Mapping[Any, Any]]
|
||||
|
||||
|
||||
class AdminLogEvent(TypedDict):
|
||||
messageId: int
|
||||
author: int
|
||||
target: str | int
|
||||
action: Literal["del", "add", "set"]
|
||||
change: Literal["owner_ids", "blacklisted_users", "enabled_cogs"]
|
||||
|
||||
|
||||
class Settings:
|
||||
def __init__(self) -> None:
|
||||
global instance
|
||||
instance = self
|
||||
|
||||
self.path: str = os.path.join(".", "settings", "settings.json")
|
||||
|
||||
if not os.path.exists(self.path):
|
||||
logger.critical(
|
||||
f"Missing settings file from {self.path}! Did you forget to copy settings.example.json?"
|
||||
)
|
||||
raise ValueError("settings.json file does not exist!")
|
||||
|
||||
self.settings: SettingsType
|
||||
self.original_settings: SettingsType
|
||||
|
||||
with open(self.path, "r") as f:
|
||||
self.__kv_store: dict = json.load(f)
|
||||
|
||||
self.settings = SettingsType(self.__kv_store) # type: ignore
|
||||
self.original_settings = copy.deepcopy(self.settings)
|
||||
|
||||
self.log_path: str = os.path.join(".", "settings", "admin_logs.json")
|
||||
|
||||
self.migrate()
|
||||
|
||||
def migrate(self):
|
||||
active_song: str | None = (
|
||||
self.settings.get("bot", {}).get("misc", {}).get("active_song")
|
||||
)
|
||||
|
||||
if active_song:
|
||||
logger.warning("Found deprecated active_song, migrating")
|
||||
|
||||
self.settings["bot"]["misc"]["activity"] = {
|
||||
"content": active_song,
|
||||
"type": "listening",
|
||||
}
|
||||
|
||||
del self.settings["bot"]["misc"]["active_song"] # type: ignore
|
||||
|
||||
sync_hub: SyncHub | None = self.settings.get("bot", {}).get("sync_hub")
|
||||
|
||||
if not sync_hub:
|
||||
logger.warning("Adding sync hub settings")
|
||||
self.settings["bot"]["sync_hub"] = {
|
||||
"enabled": True,
|
||||
"url": "ws://goober.frii.site"
|
||||
}
|
||||
|
||||
self.commit()
|
||||
|
||||
def reload_settings(self) -> None:
|
||||
with open(self.path, "r") as f:
|
||||
self.__kv_store: dict = json.load(f)
|
||||
|
||||
self.settings = SettingsType(self.__kv_store) # type: ignore
|
||||
self.original_settings = copy.deepcopy(self.settings)
|
||||
|
||||
def commit(self) -> None:
|
||||
with open(self.path, "w") as f:
|
||||
json.dump(self.settings, f, ensure_ascii=False, indent=4)
|
||||
|
||||
self.original_settings = self.settings
|
||||
|
||||
def discard(self) -> None:
|
||||
self.settings = self.original_settings
|
||||
|
||||
def get_plugin_settings(
|
||||
self, plugin_name: str, default: Mapping[Any, Any]
|
||||
) -> Mapping[Any, Any]:
|
||||
return self.settings["cog_settings"].get(plugin_name, default)
|
||||
|
||||
def set_plugin_setting(
|
||||
self, plugin_name: str, new_settings: Mapping[Any, Any]
|
||||
) -> None:
|
||||
"""Changes a plugin setting. Commits changes"""
|
||||
self.settings["cog_settings"][plugin_name] = new_settings
|
||||
|
||||
self.commit()
|
||||
|
||||
def add_admin_log_event(self, event: AdminLogEvent):
|
||||
if not os.path.exists(self.log_path):
|
||||
logger.warning("Admin log doesn't exist!")
|
||||
with open(self.log_path, "w") as f:
|
||||
json.dump([], f)
|
||||
|
||||
with open(self.log_path, "r") as f:
|
||||
logs: List[AdminLogEvent] = json.load(f)
|
||||
|
||||
logs.append(event)
|
||||
|
||||
with open(self.log_path, "w") as f:
|
||||
json.dump(logs, f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
instance: Settings = Settings()
|
|
@ -1,94 +0,0 @@
|
|||
import websocket
|
||||
from modules.settings import instance as settings_manager
|
||||
import logging
|
||||
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
settings = settings_manager.settings
|
||||
|
||||
class SyncConnector:
|
||||
def __init__(self, url: str):
|
||||
self.connected: bool = True
|
||||
self.url = url
|
||||
self.client: websocket.WebSocket | None = None
|
||||
|
||||
self.try_to_connect()
|
||||
|
||||
def __connect(self) -> bool:
|
||||
try:
|
||||
self.client = websocket.create_connection(self.url)
|
||||
except OSError as e:
|
||||
logger.debug(e)
|
||||
logger.debug(e.strerror)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def try_to_connect(self) -> bool:
|
||||
if self.__connect():
|
||||
logger.info("Connected to sync hub!")
|
||||
self.connected = True
|
||||
else:
|
||||
logger.error("Failed to connect to sync hub.. Disabling for the time being")
|
||||
self.connected = False
|
||||
|
||||
return self.connected
|
||||
|
||||
|
||||
def can_react(self, message_id: int) -> bool:
|
||||
"""
|
||||
Checks if goober can react to a messsage
|
||||
"""
|
||||
|
||||
return self.can_event(message_id, "react")
|
||||
|
||||
|
||||
def can_breaking_news(self, message_id: int) -> bool:
|
||||
"""
|
||||
Checks if goober can send a breaking news alert
|
||||
"""
|
||||
|
||||
return self.can_event(message_id, "breaking_news")
|
||||
|
||||
|
||||
def can_event(self, message_id: int, event: str, retry_depth: int = 0) -> bool:
|
||||
"""
|
||||
Checks if goober can send a breaking news alert
|
||||
"""
|
||||
|
||||
logger.debug(f"Checking {event} for message {message_id}")
|
||||
|
||||
if not settings["bot"]["sync_hub"]["enabled"]:
|
||||
logger.info("Skipping sync hub check")
|
||||
return True
|
||||
|
||||
if retry_depth > 2:
|
||||
logger.error("Too many retries. Returning false")
|
||||
return False
|
||||
|
||||
if not self.client:
|
||||
logger.error("Client no connected")
|
||||
return False
|
||||
|
||||
if not self.connected:
|
||||
logger.warning("Not connected to sync hub.. Returning False to avoid conflicts")
|
||||
return False
|
||||
|
||||
try:
|
||||
self.client.send(f"event={event};ref={message_id}")
|
||||
return self.client.recv() == "unhandled"
|
||||
except ConnectionResetError:
|
||||
logger.error("Connection to sync hub reset! Retrying...")
|
||||
|
||||
if not self.__connect():
|
||||
logger.error("Failed to reconnect to sync hub... Disabling")
|
||||
self.connected = False
|
||||
return False
|
||||
|
||||
logger.info("Managed to reconnect to sync hub! Retrying requests")
|
||||
self.connected = True
|
||||
return self.can_event(message_id, event, retry_depth+1)
|
||||
|
||||
|
||||
|
||||
instance = SyncConnector(settings["bot"]["sync_hub"]["url"])
|
|
@ -1,29 +0,0 @@
|
|||
import sys
|
||||
import traceback
|
||||
import os
|
||||
from modules.settings import instance as settings_manager
|
||||
import logging
|
||||
from modules.globalvars import RED, RESET
|
||||
import modules.keys as k
|
||||
|
||||
settings = settings_manager.settings
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
|
||||
def handle_exception(exc_type, exc_value, exc_traceback, *, context=None):
|
||||
os.system("cls" if os.name == "nt" else "clear")
|
||||
|
||||
if issubclass(exc_type, KeyboardInterrupt):
|
||||
sys.__excepthook__(exc_type, exc_value, exc_traceback)
|
||||
return
|
||||
|
||||
with open(settings["splash_text_loc"], "r") as f:
|
||||
print("".join(f.readlines()))
|
||||
|
||||
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}{k.unhandled_exception()}{RESET}")
|
||||
|
||||
if context:
|
||||
print(f"{RED}Context: {context}{RESET}")
|
1
modules/volta
Submodule
|
@ -0,0 +1 @@
|
|||
Subproject commit 628de5f76ea2a258448d2ddfc081c2ce58f509fd
|
|
@ -1,51 +0,0 @@
|
|||
import os
|
||||
import re
|
||||
|
||||
folder_path = "."
|
||||
|
||||
# Real trap regex 😮💨 — group(1)=key, group(2)=format args (optional)
|
||||
pattern = re.compile(
|
||||
r"""
|
||||
(?<!\w) # not part of a variable name
|
||||
\(? # optional opening (
|
||||
_\(\s*'([a-zA-Z0-9_]+)'\s*\) # k.key()
|
||||
\)? # optional closing )
|
||||
(?:\.format\((.*?)\))? # optional .format(...)
|
||||
""",
|
||||
re.VERBOSE,
|
||||
)
|
||||
|
||||
|
||||
def fix_content(content):
|
||||
def repl(match):
|
||||
key = match.group(1)
|
||||
args = match.group(2)
|
||||
if args:
|
||||
return f"k.{key}({args})"
|
||||
else:
|
||||
return f"k.{key}()"
|
||||
|
||||
return pattern.sub(repl, content)
|
||||
|
||||
|
||||
# File types we sweepin 🧹
|
||||
file_exts = [".py", ".html", ".txt", ".js"]
|
||||
|
||||
for subdir, _, files in os.walk(folder_path):
|
||||
for file in files:
|
||||
if any(file.endswith(ext) for ext in file_exts):
|
||||
path = os.path.join(subdir, file)
|
||||
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
original = f.read()
|
||||
|
||||
updated = fix_content(original)
|
||||
|
||||
if original != updated:
|
||||
print(f"🛠️ Fixed: {path}")
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(updated)
|
||||
|
||||
print(
|
||||
"🚀💥 ALL cleaned. No `_('...')` left on road — now it’s k.dot or nothin fam 😎🔫"
|
||||
)
|
|
@ -1,13 +1,7 @@
|
|||
discord.py
|
||||
markovify
|
||||
spacy
|
||||
spacytextblob
|
||||
nltk
|
||||
requests
|
||||
psutil
|
||||
better_profanity
|
||||
python-dotenv
|
||||
dotenv
|
||||
pillow
|
||||
watchdog
|
||||
py-cpuinfo
|
||||
websocket-client
|
|
@ -1,44 +0,0 @@
|
|||
{
|
||||
"bot": {
|
||||
"prefix": "o.",
|
||||
"owner_ids": [
|
||||
642441889181728810
|
||||
],
|
||||
"blacklisted_users": [
|
||||
1391805740716527666
|
||||
],
|
||||
"user_training": true,
|
||||
"allow_show_mem_command": true,
|
||||
"react_to_messages": true,
|
||||
"misc": {
|
||||
"ping_line": "The Beretta fires fast and won't make you feel any better!",
|
||||
"positive_gifs": [
|
||||
"https://tenor.com/view/i-want-a-divorce-dissolution-annulment-seperation-break-up-gif-25753155"
|
||||
],
|
||||
"block_profanity": false,
|
||||
"activity": {
|
||||
"content": "Rakas - Haloo Helsinki",
|
||||
"type": "listening"
|
||||
}
|
||||
},
|
||||
"active_memory": "memory.json",
|
||||
"enabled_cogs": [
|
||||
"pulse",
|
||||
"breaking_news"
|
||||
],
|
||||
"sync_hub": {
|
||||
"url": "ws://goober.frii.site",
|
||||
"enabled": true
|
||||
}
|
||||
},
|
||||
"locale": "en",
|
||||
"name": "gubert",
|
||||
"auto_update": true,
|
||||
"disable_checks": false,
|
||||
"splash_text_loc": "settings/splash.txt",
|
||||
"cog_settings": {
|
||||
"breaking_news": {
|
||||
"create_from_message_content": true
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,11 +0,0 @@
|
|||
SS\
|
||||
SS |
|
||||
SSSSSS\ SSSSSS\ SSSSSS\ SSSSSSS\ SSSSSS\ SSSSSS\
|
||||
SS __SS\ SS __SS\ SS __SS\ SS __SS\ SS __SS\ SS __SS\
|
||||
SS / SS |SS / SS |SS / SS |SS | SS |SSSSSSSS |SS | \__|
|
||||
SS | SS |SS | SS |SS | SS |SS | SS |SS ____|SS |
|
||||
\SSSSSSS |\SSSSSS |\SSSSSS |SSSSSSS |\SSSSSSS\ SS |
|
||||
\____SS | \______/ \______/ \_______/ \_______|\__|
|
||||
SS\ SS |
|
||||
\SSSSSS |
|
||||
\______/
|
|
@ -1,3 +0,0 @@
|
|||
- The catbox.moe team for memory.json file uploads
|
||||
- Charlie's Computers
|
||||
- ctih1
|
5
todo.txt
|
@ -1,4 +1 @@
|
|||
- fix missing translations in some cases
|
||||
- revamp wiki
|
||||
- clean the rest
|
||||
- alot
|
||||
- update to latest version of goober
|
||||
|
|
16
updater.py
|
@ -1,16 +0,0 @@
|
|||
import subprocess
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
import logging
|
||||
|
||||
|
||||
logger = logging.getLogger("goober")
|
||||
|
||||
def force_update() -> None:
|
||||
logger.info("Forcefully updating...")
|
||||
stash = subprocess.run(["git", "stash"], capture_output=True)
|
||||
logger.info(stash)
|
||||
pull = subprocess.run(["git", "pull", "origin", "main"], check=True, capture_output=True)
|
||||
logger.info(pull)
|
||||
|
208
volta.py
Normal 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..")
|
||||
|