Compare commits
12 commits
main
...
rewrite/se
Author | SHA1 | Date | |
---|---|---|---|
a0e2e39b65 | |||
![]() |
21b5107dd6 | ||
![]() |
3621a65481 | ||
![]() |
2c72a31a1a | ||
![]() |
607656bca0 | ||
![]() |
31dc82b368 | ||
![]() |
7877db4785 | ||
![]() |
ddfd67df5c | ||
![]() |
145587c81f | ||
![]() |
d0ae422233 | ||
![]() |
15e40e0325 | ||
![]() |
587d24d520 |
13
.gitignore
vendored
|
@ -4,12 +4,9 @@ current_version.txt
|
||||||
MEMORY_LOADED
|
MEMORY_LOADED
|
||||||
memory.json
|
memory.json
|
||||||
*.pkl
|
*.pkl
|
||||||
memory.json
|
memories/
|
||||||
venv/
|
models/
|
||||||
output.png
|
|
||||||
.vscode/
|
|
||||||
received_memory.json
|
|
||||||
translation_report.txt
|
|
||||||
translationcompleteness.py
|
|
||||||
modules/volta
|
|
||||||
log.txt
|
log.txt
|
||||||
|
translationcompleteness.py
|
||||||
|
translation_report.txt
|
||||||
|
output.png
|
||||||
|
|
3
.gitmodules
vendored
|
@ -1,3 +0,0 @@
|
||||||
[submodule "modules/volta"]
|
|
||||||
path = modules/volta
|
|
||||||
url = https://forgejo.expect.ovh/gooberinc/volta
|
|
11
README.md
|
@ -1,9 +1,12 @@
|
||||||
knockoff of genai basically :p
|
Discord bot that learns from what people say!
|
||||||
|
|
||||||
|
Please see the [wiki](https://wiki.goober.whatdidyouexpect.eu)
|
||||||
|
|
||||||
Special thanks to [Charlie's Computers](https://github.com/PowerPCFan) for being the only one I know of that's hosting Goober 24/7
|
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)
|
[Goober Central](https://github.com/whatdidyouexpect/goober-central)
|
||||||
|
|
||||||
[Another mirror](https://forgejo.expect.ovh/gooberinc/goober)
|

|
||||||
no promises that it'll be stable
|
|
||||||
|
|
|
@ -1,57 +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.randint(1, 20)
|
|
||||||
text = "Nothing"
|
|
||||||
if answer==1:
|
|
||||||
text = "It is certain."
|
|
||||||
elif answer==2:
|
|
||||||
text = "It is decidedly so."
|
|
||||||
elif answer==3:
|
|
||||||
text = "Without a doubt."
|
|
||||||
elif answer==4:
|
|
||||||
text = "Yes definitely."
|
|
||||||
elif answer==5:
|
|
||||||
text = "You may rely on it."
|
|
||||||
elif answer==6:
|
|
||||||
text = "As I see it, yes."
|
|
||||||
elif answer==7:
|
|
||||||
text = "Most likely."
|
|
||||||
elif answer==8:
|
|
||||||
text = "Outlook good."
|
|
||||||
elif answer==9:
|
|
||||||
text = "Yes."
|
|
||||||
elif answer==10:
|
|
||||||
text = "Signs point to yes."
|
|
||||||
elif answer==11:
|
|
||||||
text = "Reply hazy, try again."
|
|
||||||
elif answer==12:
|
|
||||||
text = "Ask again later."
|
|
||||||
elif answer==13:
|
|
||||||
text = "Better not tell you now."
|
|
||||||
elif answer==14:
|
|
||||||
text = "Cannot predict now."
|
|
||||||
elif answer==15:
|
|
||||||
text = "Concentrate and ask again."
|
|
||||||
elif answer==16:
|
|
||||||
text = "Don't count on it."
|
|
||||||
elif answer==17:
|
|
||||||
text = "My reply is no."
|
|
||||||
elif answer==18:
|
|
||||||
text = "My sources say no."
|
|
||||||
elif answer==19:
|
|
||||||
text = "Outlook not so good."
|
|
||||||
elif answer==20:
|
|
||||||
text = "Very doubtful."
|
|
||||||
|
|
||||||
await ctx.send(text)
|
|
||||||
|
|
||||||
async def setup(bot):
|
|
||||||
await bot.add_cog(eightball(bot))
|
|
|
@ -1,48 +0,0 @@
|
||||||
import discord
|
|
||||||
from discord.ext import commands
|
|
||||||
from modules.globalvars import ownerid
|
|
||||||
class FileSync(commands.Cog):
|
|
||||||
def __init__(self, bot):
|
|
||||||
self.bot = bot
|
|
||||||
self.mode = None
|
|
||||||
self.peer_id = None
|
|
||||||
self.awaiting_file = False
|
|
||||||
|
|
||||||
@commands.command()
|
|
||||||
async def syncfile(self, ctx, mode: str, peer: discord.User):
|
|
||||||
self.mode = mode.lower()
|
|
||||||
self.peer_id = peer.id
|
|
||||||
if ctx.author.id != ownerid:
|
|
||||||
await ctx.send("You don't have permission to execute this command.")
|
|
||||||
return
|
|
||||||
if self.mode == "s":
|
|
||||||
await ctx.send(f"<@{self.peer_id}> FILE_TRANSFER_REQUEST")
|
|
||||||
await ctx.send(file=discord.File("memory.json"))
|
|
||||||
await ctx.send("File sent in this channel.")
|
|
||||||
elif self.mode == "r":
|
|
||||||
await ctx.send("Waiting for incoming file...")
|
|
||||||
self.awaiting_file = True
|
|
||||||
else:
|
|
||||||
await ctx.send("Invalid mode, use 's' or 'r'.")
|
|
||||||
|
|
||||||
|
|
||||||
@commands.Cog.listener()
|
|
||||||
async def on_message(self, 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":
|
|
||||||
print("Ping received. Awaiting file...")
|
|
||||||
if message.attachments:
|
|
||||||
for attachment in message.attachments:
|
|
||||||
if attachment.filename.endswith(".json"):
|
|
||||||
filename = "received_memory.json"
|
|
||||||
await attachment.save(filename)
|
|
||||||
print(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,98 +0,0 @@
|
||||||
import discord
|
|
||||||
from discord.ext import commands
|
|
||||||
from modules.image import *
|
|
||||||
from modules.volta.main import _
|
|
||||||
from PIL import Image, ImageEnhance, ImageFilter, ImageOps, ImageChops, ImageColor
|
|
||||||
import os, random, shutil, tempfile
|
|
||||||
|
|
||||||
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(_('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(_('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(_('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,84 +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,123 +0,0 @@
|
||||||
import discord
|
|
||||||
from discord.ext import commands
|
|
||||||
from discord import app_commands
|
|
||||||
import aiohttp
|
|
||||||
import re
|
|
||||||
|
|
||||||
class Lyrics(commands.Cog):
|
|
||||||
def __init__(self, bot):
|
|
||||||
self.bot = bot
|
|
||||||
|
|
||||||
@app_commands.command(name="lyrics", description="Get lyrics for a song")
|
|
||||||
@app_commands.describe(
|
|
||||||
artist="Name of the artist",
|
|
||||||
song="Title of the song",
|
|
||||||
language="Target language code (optional)"
|
|
||||||
)
|
|
||||||
@app_commands.choices(language=[
|
|
||||||
app_commands.Choice(name="Bulgarian", value="bg"),
|
|
||||||
app_commands.Choice(name="Czech", value="cs"),
|
|
||||||
app_commands.Choice(name="Danish", value="da"),
|
|
||||||
app_commands.Choice(name="German", value="de"),
|
|
||||||
app_commands.Choice(name="Greek", value="el"),
|
|
||||||
app_commands.Choice(name="English", value="en"),
|
|
||||||
app_commands.Choice(name="Spanish", value="es"),
|
|
||||||
app_commands.Choice(name="Estonian", value="et"),
|
|
||||||
app_commands.Choice(name="Finnish", value="fi"),
|
|
||||||
app_commands.Choice(name="French", value="fr"),
|
|
||||||
app_commands.Choice(name="Irish", value="ga"),
|
|
||||||
app_commands.Choice(name="Croatian", value="hr"),
|
|
||||||
app_commands.Choice(name="Hungarian", value="hu"),
|
|
||||||
app_commands.Choice(name="Italian", value="it"),
|
|
||||||
app_commands.Choice(name="Lithuanian", value="lt"),
|
|
||||||
app_commands.Choice(name="Latvian", value="lv"),
|
|
||||||
app_commands.Choice(name="Maltese", value="mt"),
|
|
||||||
app_commands.Choice(name="Dutch", value="nl"),
|
|
||||||
app_commands.Choice(name="Polish", value="pl"),
|
|
||||||
app_commands.Choice(name="Portuguese", value="pt"),
|
|
||||||
app_commands.Choice(name="Romanian", value="ro"),
|
|
||||||
app_commands.Choice(name="Slovak", value="sk"),
|
|
||||||
app_commands.Choice(name="Slovene", value="sl"),
|
|
||||||
app_commands.Choice(name="Swedish", value="sv"),
|
|
||||||
])
|
|
||||||
async def lyrics(self, interaction: discord.Interaction, artist: str = None, song: str = None, language: app_commands.Choice[str] = None):
|
|
||||||
await interaction.response.defer()
|
|
||||||
if not artist or not song:
|
|
||||||
member = interaction.guild.get_member(interaction.user.id)
|
|
||||||
if not member:
|
|
||||||
member = await interaction.guild.fetch_member(interaction.user.id)
|
|
||||||
act_artist, act_song = await self.get_artist_song_from_presence(member)
|
|
||||||
if act_artist and act_song:
|
|
||||||
artist = artist or act_artist
|
|
||||||
song = song or act_song
|
|
||||||
else:
|
|
||||||
await interaction.followup.send("No artist or song provided and couldn't find it from your current activity.")
|
|
||||||
return
|
|
||||||
|
|
||||||
lyrics = await self.fetch_lyrics(artist, song)
|
|
||||||
if not lyrics:
|
|
||||||
await interaction.followup.send(f"Could not find lyrics for **{artist} - {song}**")
|
|
||||||
return
|
|
||||||
|
|
||||||
if language:
|
|
||||||
translated = await self.translate_text(lyrics, language.value)
|
|
||||||
if translated:
|
|
||||||
lyrics = translated
|
|
||||||
|
|
||||||
if len(lyrics) > 1900:
|
|
||||||
lyrics = lyrics[:1900] + "\n\n[...lyrics truncated...]"
|
|
||||||
|
|
||||||
embed = discord.Embed(
|
|
||||||
title=f"{artist} - {song}",
|
|
||||||
description=lyrics,
|
|
||||||
color=discord.Color.blue()
|
|
||||||
)
|
|
||||||
embed.set_footer(text=f"Requested by {interaction.user}", icon_url=interaction.user.display_avatar.url)
|
|
||||||
await interaction.followup.send(embed=embed)
|
|
||||||
|
|
||||||
async def get_artist_song_from_presence(self, member: discord.Member):
|
|
||||||
for activity in member.activities:
|
|
||||||
if isinstance(activity, discord.Spotify):
|
|
||||||
return activity.artist, activity.title
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
|
|
||||||
async def fetch_lyrics(self, artist, song):
|
|
||||||
artist_q = artist.replace(' ', '+').lower()
|
|
||||||
song_q = song.replace(' ', '+').lower()
|
|
||||||
|
|
||||||
url = f"https://lrclib.net/api/get?artist_name={artist_q}&track_name={song_q}"
|
|
||||||
print(url)
|
|
||||||
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
try:
|
|
||||||
async with session.get(url) as resp:
|
|
||||||
if resp.status != 200:
|
|
||||||
return None
|
|
||||||
data = await resp.json()
|
|
||||||
return data.get('plainLyrics')
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def translate_text(self, text: str, target_lang: str) -> str | None:
|
|
||||||
translate_url = "https://translate.googleapis.com/translate_a/single"
|
|
||||||
params = {
|
|
||||||
"client": "gtx",
|
|
||||||
"sl": "auto",
|
|
||||||
"tl": target_lang,
|
|
||||||
"dt": "t",
|
|
||||||
"q": text
|
|
||||||
}
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
try:
|
|
||||||
async with session.get(translate_url, params=params) as resp:
|
|
||||||
if resp.status != 200:
|
|
||||||
return None
|
|
||||||
result = await resp.json()
|
|
||||||
translated_chunks = [item[0] for item in result[0] if item[0]]
|
|
||||||
return ''.join(translated_chunks)
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def setup(bot):
|
|
||||||
await bot.add_cog(Lyrics(bot))
|
|
|
@ -1,66 +0,0 @@
|
||||||
from discord.ext import commands
|
|
||||||
import discord
|
|
||||||
from collections import defaultdict, Counter
|
|
||||||
import datetime
|
|
||||||
from modules.globalvars import ownerid
|
|
||||||
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
|
|
||||||
|
|
||||||
@commands.command()
|
|
||||||
async def spyware(self, ctx):
|
|
||||||
if ctx.author.id != ownerid:
|
|
||||||
return
|
|
||||||
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: 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,151 +0,0 @@
|
||||||
{
|
|
||||||
"minigames_hangman_game": "Word: {display_word()}\nWrong guesses: {wrong_guesses}/{max_wrong}",
|
|
||||||
"minigames_hangman_lost": "You lost! The word was:",
|
|
||||||
"minigames_hangman_won": "You won! The word was:",
|
|
||||||
"minigames_hangman_already_guessed": "You already guessed",
|
|
||||||
"minigames_hangman_user_letter_guess": "Your letter guess",
|
|
||||||
"minigames_hangman_guess": "Guess a Letter",
|
|
||||||
"minigames_hangman_api_failed": "Failed to get a random word.",
|
|
||||||
"minigames_hangman": "Play Hangman with a random word",
|
|
||||||
"minigames_click_to_guess": "Click to guess a number from 1 to 10",
|
|
||||||
"minigames_guess_button": "Guess",
|
|
||||||
"minigames_wrong_number": "Wrong! The number was",
|
|
||||||
"minigames_correct": "Correct!",
|
|
||||||
"minigames_invalid_number": "Invalid number!",
|
|
||||||
"minigames_guess_the_number": "Guess the number",
|
|
||||||
"minigames_your_guess": "Your guess (1-10)",
|
|
||||||
"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 Git.",
|
|
||||||
"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}```"
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,149 +0,0 @@
|
||||||
{
|
|
||||||
"minigames_hangman_game": "Mot à deviner : {display_word()}\nMauvaises guesses : {wrong_guesses}/{max_wrong}",
|
|
||||||
"minigames_hangman_lost": "T'es échoué solide! Le mot était :",
|
|
||||||
"minigames_hangman_won": "T'as gagné en masse! Le mot était :",
|
|
||||||
"minigames_hangman_already_guessed": "T'as déjà essayé ça mon chum",
|
|
||||||
"minigames_hangman_user_letter_guess": "Ta guess de lettre",
|
|
||||||
"minigames_hangman_guess": "Devine une lettre",
|
|
||||||
"minigames_hangman_api_failed": "Ça a chié en essayant d'avoir un mot aléatoire.",
|
|
||||||
"minigames_hangman": "Jouer au Pendu avec un mot pogné au hasard",
|
|
||||||
"minigames_click_to_guess": "Clique pour deviner un chiffre entre 1 pis 10",
|
|
||||||
"minigames_guess_button": "Devine",
|
|
||||||
"minigames_wrong_number": "Nope! C'était",
|
|
||||||
"minigames_correct": "Bonne guess!",
|
|
||||||
"minigames_invalid_number": "Chiffre pas valide!",
|
|
||||||
"minigames_guess_the_number": "Devine le chiffre",
|
|
||||||
"minigames_your_guess": "Ta guess (1-10)",
|
|
||||||
"memory_file_valid": "Le fichier memory.json est correct!",
|
|
||||||
"file_aint_uft8": "Le fichier est pas du bon UTF-8. Ça doit être binaire ou scrap.",
|
|
||||||
"psutil_not_installed": "Vérification de mémoire skipée.",
|
|
||||||
"not_cloned": "Goober est pas cloné! Va donc le cloner depuis Git.",
|
|
||||||
"checks_disabled": "Les checks sont désactivées!",
|
|
||||||
"unhandled_exception": "Y'a eu une erreur pas prévue. Rapporte ça sur GitHub mon gars.",
|
|
||||||
"active_users:": "Monde actif :",
|
|
||||||
"spacy_initialized": "spaCy pis spacytextblob sont prêts.",
|
|
||||||
"spacy_model_not_found": "Le modèle spaCy est introuvable! On le télécharge...",
|
|
||||||
"env_file_not_found": "Le fichier .env est pas là! Fais-en un avec les variables nécessaires.",
|
|
||||||
"error_fetching_active_users": "Ça a chié en essayant de pogner les utilisateurs actifs : {error}",
|
|
||||||
"error_sending_alive_ping": "Ça a chié en envoyant le ping : {error}",
|
|
||||||
"already_started": "J'suis déjà parti! J'me mets pas à jour...",
|
|
||||||
"please_restart": "Redémarre-moi donc!",
|
|
||||||
"local_ahead": "La version locale {remote}/{branch} est à jour. Pas besoin d'update...",
|
|
||||||
"remote_ahead": "La version remote {remote}/{branch} est en avance. On update...",
|
|
||||||
"cant_find_local_version": "J'arrive pas à trouver la variable local_version! Ou ben elle a été modifiée pis c'est pas un chiffre!",
|
|
||||||
"running_prestart_checks": "On fait les checks avant de partir...",
|
|
||||||
"continuing_in_seconds": "On continue dans {seconds} secondes... Appuie sur une touche pour skip.",
|
|
||||||
"missing_requests_psutil": "Y manque requests pis psutil! Installe-les avec pip : `pip install requests psutil`",
|
|
||||||
"requirements_not_found": "requirements.txt introuvable à {path}, est-ce qu'il a été modifié?",
|
|
||||||
"warning_failed_parse_imports": "Attention : Ça a chié en lisant les imports de {filename} : {error}",
|
|
||||||
"cogs_dir_not_found": "Le dossier des cogs est pas à {path}, on skip le scan.",
|
|
||||||
"std_lib_local_skipped": "LIB STD / LOCAL {package} (check skipé)",
|
|
||||||
"ok_installed": "OK",
|
|
||||||
"missing_package": "MANQUANT",
|
|
||||||
"missing_package2": "est pas installé",
|
|
||||||
"missing_packages_detected": "Y'a des affaires qui manquent :",
|
|
||||||
"telling_goober_central": "J'envoie ça à goober central à {url}",
|
|
||||||
"failed_to_contact": "J'ai pas réussi à contacter {url} : {error}",
|
|
||||||
"all_requirements_satisfied": "Tout ce qu'il faut est installé.",
|
|
||||||
"ping_to": "Ping à {host} : {latency} ms",
|
|
||||||
"high_latency": "Latence élevée! Ça pourrait être lent.",
|
|
||||||
"could_not_parse_latency": "J'ai pas pu comprendre la latence.",
|
|
||||||
"ping_failed": "Le ping à {host} a chié.",
|
|
||||||
"error_running_ping": "Ça a chié en faisant le ping : {error}",
|
|
||||||
"memory_usage": "Mémoire utilisée : {used} Go / {total} Go ({percent}%)",
|
|
||||||
"memory_above_90": "La mémoire est à plus de 90% ({percent}%). Libère de la mémoire.",
|
|
||||||
"total_memory": "Mémoire totale : {total} Go",
|
|
||||||
"used_memory": "Mémoire utilisée : {used} Go",
|
|
||||||
"low_free_memory": "Y'a presque plus de mémoire! Juste {free} Go de libre.",
|
|
||||||
"measuring_cpu": "On check l'usage CPU par coeur...",
|
|
||||||
"core_usage": "Coeur {idx} : [{bar}] {usage}%",
|
|
||||||
"total_cpu_usage": "Usage total CPU : {usage}%",
|
|
||||||
"high_avg_cpu": "CPU trop élevé : {usage}%",
|
|
||||||
"really_high_cpu": "Le CPU est en tabarnak! Ça pourrait crasher.",
|
|
||||||
"memory_file": "Fichier mémoire : {size} Mo",
|
|
||||||
"memory_file_large": "Fichier mémoire de 1 Go ou plus, nettoie ça pour faire de la place.",
|
|
||||||
"memory_file_corrupted": "Fichier mémoire scrap! Erreur JSON : {error}",
|
|
||||||
"consider_backup_memory": "Pense à faire un backup pis recréer le fichier mémoire.",
|
|
||||||
"memory_file_encoding": "Problème d'encodage du fichier mémoire : {error}",
|
|
||||||
"error_reading_memory": "Ça a chié en lisant le fichier mémoire : {error}",
|
|
||||||
"memory_file_not_found": "Fichier mémoire pas trouvé.",
|
|
||||||
"modification_warning": "Goober a été modifié! Tes modifications vont être perdues à l'update!",
|
|
||||||
"reported_version": "Version rapportée :",
|
|
||||||
"current_hash": "Hash actuel :",
|
|
||||||
"not_found": "est pas trouvé!",
|
|
||||||
"version_error": "J'ai pas pu avoir les infos de version. Code d'état",
|
|
||||||
"loaded_cog": "Cog chargé :",
|
|
||||||
"loaded_cog2": "Module chargé :",
|
|
||||||
"cog_fail": "Ça a chié en chargeant le cog :",
|
|
||||||
"cog_fail2": "Ça a chié en chargeant le module :",
|
|
||||||
"no_model": "Y'a pas de modèle Markov de sauvegardé. On part de zéro.",
|
|
||||||
"folder_created": "Dossier '{folder_name}' créé.",
|
|
||||||
"folder_exists": "Le dossier '{folder_name}' existe déjà. On skip...",
|
|
||||||
"logged_in": "Connecté en tant que",
|
|
||||||
"synced_commands": "Synchronisé",
|
|
||||||
"synced_commands2": "commandes!",
|
|
||||||
"fail_commands_sync": "Ça a chié en synchronisant les commandes :",
|
|
||||||
"started": "{name} est parti!",
|
|
||||||
"name_check": "Ça a chié en checkant si le nom est libre :",
|
|
||||||
"name_taken": "Le nom est déjà pris. Choisis-en un autre.",
|
|
||||||
"name_check2": "Ça a chié en checkant si le nom est libre :",
|
|
||||||
"add_token": "Token : {token}\nAjoute ce token dans ton .env comme",
|
|
||||||
"token_exists": "Le token existe déjà dans .env. On utilise celui-là.",
|
|
||||||
"registration_error": "Ça a chié en s'enregistrant :",
|
|
||||||
"version_backup": "Backup créé :",
|
|
||||||
"backup_error": "Erreur : {LOCAL_VERSION_FILE} pas trouvé pour le backup.",
|
|
||||||
"model_loaded": "Modèle Markov chargé depuis",
|
|
||||||
"fetch_update_fail": "J'ai pas pu avoir les infos d'update.",
|
|
||||||
"invalid_server": "Erreur : Infos de version invalides du serveur.",
|
|
||||||
"goober_server_alert": "Alerte du serveur Goober central!\n",
|
|
||||||
"new_version": "Nouvelle version disponible : {latest_version} (Actuelle : {local_version})",
|
|
||||||
"changelog": "Va voir {VERSION_URL}/goob/changes.txt pour les changements\n\n",
|
|
||||||
"invalid_version": "La version : {local_version} est pas valide!",
|
|
||||||
"invalid_version2": "Si c'est fait exprès, ignore ça. Sinon, appuie sur Y pour avoir une version valide du serveur, peu importe ta version actuelle de Goober.",
|
|
||||||
"invalid_version3": "La version actuelle va être backupée dans current_version.bak..",
|
|
||||||
"input": "(Y ou n'importe quelle touche pour skip...)",
|
|
||||||
"modification_ignored": "T'as modifié",
|
|
||||||
"modification_ignored2": "IGNOREWARNING est désactivé..",
|
|
||||||
"latest_version": "T'as la dernière version :",
|
|
||||||
"latest_version2": "Va voir {VERSION_URL}/goob/changes.txt pour les changements",
|
|
||||||
"pinging_disabled": "Le ping est désactivé! J'dis pas au serveur que j'suis en ligne...",
|
|
||||||
"goober_ping_success": "Connecté à Goober central en tant que {NAME}",
|
|
||||||
"goober_ping_fail": "Ça a chié en envoyant les données. Le serveur a retourné :",
|
|
||||||
"goober_ping_fail2": "Ça a chié en envoyant les données :",
|
|
||||||
"sentence_positivity": "La phrase est positive à :",
|
|
||||||
"command_edit_fail": "Ça a chié en éditant le message :",
|
|
||||||
"command_desc_retrain": "Réentraîne le modèle Markov à la main.",
|
|
||||||
"command_markov_retrain": "Réentraînement du modèle Markov... Attend un peu.",
|
|
||||||
"command_markov_memory_not_found": "Erreur : fichier mémoire pas trouvé!",
|
|
||||||
"command_markov_memory_is_corrupt": "Erreur : fichier mémoire scrap!",
|
|
||||||
"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 avec {data_size} points de données!",
|
|
||||||
"command_desc_talk": "parle pis toute",
|
|
||||||
"command_talk_insufficent_text": "J'ai pas assez appris pour pouvoir parler.",
|
|
||||||
"command_talk_generation_fail": "J'ai rien à dire pour l'instant!",
|
|
||||||
"command_desc_help": "aide",
|
|
||||||
"command_help_embed_title": "Aide du bot",
|
|
||||||
"command_help_embed_desc": "Liste des commandes par catégorie.",
|
|
||||||
"command_help_categories_general": "Général",
|
|
||||||
"command_help_categories_admin": "Admin",
|
|
||||||
"command_help_categories_custom": "Commandes perso",
|
|
||||||
"command_ran": "Info : {message.author.name} a fait {message.content}",
|
|
||||||
"command_ran_s": "Info : {interaction.user} a fait ",
|
|
||||||
"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": "stats",
|
|
||||||
"command_stats_embed_title": "Stats du bot",
|
|
||||||
"command_stats_embed_desc": "Infos sur la mémoire du bot.",
|
|
||||||
"command_stats_embed_field1name": "Stats 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": "Infos variables",
|
|
||||||
"command_stats_embed_field3value": "Nom : {NAME} \nPréfixe : {PREFIX} \nID du proprio : {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}```"
|
|
||||||
}
|
|
|
@ -1,152 +0,0 @@
|
||||||
{
|
|
||||||
"minigames_hangman_game": "Parola: {display_word()}\nErrori: {wrong_guesses}/{max_wrong}",
|
|
||||||
"minigames_hangman_lost": "Hai perso! La parola era:",
|
|
||||||
"minigames_hangman_won": "Hai vinto! La parola era:",
|
|
||||||
"minigames_hangman_already_guessed": "Hai già indovinato",
|
|
||||||
"minigames_hangman_user_letter_guess": "La tua lettera",
|
|
||||||
"minigames_hangman_guess": "Indovina una lettera",
|
|
||||||
"minigames_hangman_api_failed": "Impossibile ottenere una parola casuale.",
|
|
||||||
"minigames_hangman": "Gioca all'impiccato con una parola casuale",
|
|
||||||
"minigames_click_to_guess": "Clicca per indovinare un numero da 1 a 10",
|
|
||||||
"minigames_guess_button": "Indovina",
|
|
||||||
"minigames_wrong_number": "Sbagliato! Il numero era",
|
|
||||||
"minigames_correct": "Corretto!",
|
|
||||||
"minigames_invalid_number": "Numero non valido!",
|
|
||||||
"minigames_guess_the_number": "Indovina il numero",
|
|
||||||
"minigames_your_guess": "Il tuo numero (1-10)",
|
|
||||||
"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 Git.",
|
|
||||||
"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:",
|
|
||||||
"not_found": "non trovato!",
|
|
||||||
"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...",
|
|
||||||
"logged_in": "Accesso effettuato come",
|
|
||||||
"synced_commands": "Sincronizzati",
|
|
||||||
"synced_commands2": "comandi!",
|
|
||||||
"fail_commands_sync": "Impossibile sincronizzare i comandi:",
|
|
||||||
"started": "{name} è stato avviato!\nIl palco è tuo!",
|
|
||||||
"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.",
|
|
||||||
"model_loaded": "Modello Markov caricato da",
|
|
||||||
"fetch_update_fail": "Impossibile recuperare le informazioni sull'aggiornamento.",
|
|
||||||
"invalid_server": "Errore: informazioni sulla versione non valide ricevute dal server.",
|
|
||||||
"new_version": "Nuova versione disponibile: {latest_version} (Attuale: {local_version})",
|
|
||||||
"changelog": "Controlla {VERSION_URL}/goob/changes.txt per vedere il changelog\n\n",
|
|
||||||
"invalid_version": "La versione: {local_version} non è valida!",
|
|
||||||
"invalid_version2": "Se è intenzionale ignora questo messaggio, altrimenti premi Y per scaricare una versione valida dal server indipendentemente dalla versione attuale di goober",
|
|
||||||
"invalid_version3": "La versione attuale sarà salvata come current_version.bak..",
|
|
||||||
"input": "(Y o qualsiasi altro tasto per ignorare....)",
|
|
||||||
"modification_ignored": "Hai modificato",
|
|
||||||
"modification_ignored2": "IGNOREWARNING è impostato su false..",
|
|
||||||
"latest_version": "Stai utilizzando l'ultima versione:",
|
|
||||||
"latest_version2": "Controlla {VERSION_URL}/goob/changes.txt per vedere il changelog",
|
|
||||||
"pinging_disabled": "Il ping è disabilitato! Non dico al server che sono online...",
|
|
||||||
"goober_ping_success": "Accesso a goober central come {NAME}",
|
|
||||||
"goober_ping_fail": "Impossibile inviare i dati. Il server ha restituito il codice di stato:",
|
|
||||||
"goober_ping_fail2": "Si è verificato un errore durante l'invio dei dati:",
|
|
||||||
"sentence_positivity": "La positività della frase è:",
|
|
||||||
"command_edit_fail": "Impossibile modificare il messaggio:",
|
|
||||||
"command_desc_retrain": "Rafforza manualmente il modello Markov.",
|
|
||||||
"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_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.",
|
|
||||||
"command_talk_generation_fail": "Non ho nulla da dire in questo momento!",
|
|
||||||
"command_desc_help": "aiuto",
|
|
||||||
"command_help_embed_title": "Aiuto Bot",
|
|
||||||
"command_help_embed_desc": "Elenco dei comandi raggruppati per categoria.",
|
|
||||||
"command_help_categories_general": "Generale",
|
|
||||||
"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",
|
|
||||||
"command_about_embed_title": "Informazioni su di me",
|
|
||||||
"command_about_embed_field1": "Nome",
|
|
||||||
"command_about_embed_field2name": "Versione",
|
|
||||||
"command_about_embed_field2value": "Locale: {local_version} \nUltima: {latest_version}",
|
|
||||||
"command_desc_stats": "statistiche",
|
|
||||||
"command_stats_embed_title": "Statistiche del bot",
|
|
||||||
"command_stats_embed_desc": "Dati sulla memoria del bot.",
|
|
||||||
"command_stats_embed_field1name": "Statistiche del file",
|
|
||||||
"command_stats_embed_field1value": "Dimensione: {file_size} byte\nLinee: {line_count}",
|
|
||||||
"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}```"
|
|
||||||
}
|
|
||||||
|
|
866
bot.py
|
@ -1,194 +1,435 @@
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
import random
|
|
||||||
import traceback
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
import shutil
|
|
||||||
import psutil
|
|
||||||
import asyncio
|
|
||||||
import platform
|
|
||||||
import sys
|
|
||||||
from typing import List, Dict, Set, Optional, Tuple, Any, Union, Callable, Coroutine, TypeVar, Type
|
|
||||||
import logging
|
|
||||||
from modules.globalvars import *
|
|
||||||
from modules.prestartchecks import start_checks
|
|
||||||
from modules.logger import GooberFormatter
|
|
||||||
import logging
|
|
||||||
|
|
||||||
logger = logging.getLogger("goober")
|
|
||||||
logger.setLevel(logging.DEBUG)
|
|
||||||
|
|
||||||
console_handler = logging.StreamHandler()
|
|
||||||
console_handler.setLevel(logging.DEBUG)
|
|
||||||
console_handler.setFormatter(GooberFormatter())
|
|
||||||
|
|
||||||
file_handler = logging.FileHandler("log.txt", mode="w+", encoding="UTF-8")
|
|
||||||
file_handler.setLevel(logging.DEBUG)
|
|
||||||
file_handler.setFormatter(GooberFormatter(colors=False))
|
|
||||||
|
|
||||||
logger.addHandler(console_handler)
|
|
||||||
logger.addHandler(file_handler)
|
|
||||||
|
|
||||||
# Print splash text and check for updates
|
|
||||||
print(splashtext) # Print splash text (from modules/globalvars.py)
|
|
||||||
start_checks()
|
|
||||||
|
|
||||||
import requests
|
|
||||||
import discord
|
import discord
|
||||||
from discord.ext import commands
|
from discord.ext import commands, tasks
|
||||||
from discord import app_commands
|
from discord import app_commands
|
||||||
from discord import Colour, Embed, File, Interaction, Message
|
import json
|
||||||
from discord.abc import Messageable
|
import markovify
|
||||||
from discord.ext import commands
|
import nltk
|
||||||
|
from nltk.tokenize import word_tokenize
|
||||||
|
import random
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import re
|
||||||
|
import os
|
||||||
|
import requests
|
||||||
|
import platform
|
||||||
|
import subprocess
|
||||||
|
import psutil
|
||||||
|
import pickle
|
||||||
|
import hashlib
|
||||||
|
from better_profanity import profanity
|
||||||
|
from config import *
|
||||||
|
import traceback
|
||||||
|
import shutil
|
||||||
|
from volta import *
|
||||||
|
from nltk.sentiment.vader import SentimentIntensityAnalyzer
|
||||||
|
|
||||||
from modules.volta.main import _, set_language
|
analyzer = SentimentIntensityAnalyzer()
|
||||||
from modules.markovmemory import *
|
|
||||||
from modules.version import *
|
|
||||||
from modules.sentenceprocessing import *
|
|
||||||
from modules.unhandledexception import handle_exception
|
|
||||||
from modules.image import gen_meme, gen_demotivator
|
|
||||||
from modules.minigames import guessthenumber, hangman
|
|
||||||
sys.excepthook = handle_exception
|
|
||||||
check_for_update() # Check for updates (from modules/version.py)
|
|
||||||
# Type aliases
|
|
||||||
T = TypeVar('T')
|
|
||||||
MessageContext = Union[commands.Context, discord.Interaction]
|
|
||||||
MessageReference = Union[Message, discord.WebhookMessage]
|
|
||||||
|
|
||||||
# Constants with type hints
|
print(splashtext) # you can use https://patorjk.com/software/taag/ for 3d text or just remove this entirely
|
||||||
positive_gifs: List[str] = os.getenv("POSITIVE_GIFS", "").split(',')
|
|
||||||
currenthash: str = ""
|
|
||||||
launched: bool = False
|
|
||||||
slash_commands_enabled: bool = False
|
|
||||||
|
|
||||||
# Load memory and Markov model for text generation
|
os.makedirs("memories", exist_ok=True)
|
||||||
memory: List[str] = load_memory()
|
os.makedirs("models", exist_ok=True)
|
||||||
markov_model: Optional[markovify.Text] = load_markov_model()
|
|
||||||
if not markov_model:
|
|
||||||
logger.error(_('markov_model_not_found'))
|
|
||||||
memory = load_memory()
|
|
||||||
markov_model = train_markov_model(memory)
|
|
||||||
|
|
||||||
generated_sentences: Set[str] = set()
|
|
||||||
used_words: Set[str] = set()
|
|
||||||
|
|
||||||
async def load_cogs_from_folder(bot, folder_name="assets/cogs"):
|
def download_json():
|
||||||
|
locales_dir = "locales"
|
||||||
|
response = requests.get(f"{VERSION_URL}/goob/locales/{LOCALE}.json")
|
||||||
|
if response.status_code == 200:
|
||||||
|
|
||||||
|
if not os.path.exists(locales_dir):
|
||||||
|
os.makedirs(locales_dir)
|
||||||
|
file_path = os.path.join(locales_dir, f"{LOCALE}.json")
|
||||||
|
if os.path.exists(file_path):
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
with open(file_path, "w", encoding="utf-8") as file:
|
||||||
|
file.write(response.text)
|
||||||
|
|
||||||
|
if not os.path.exists(os.path.join(locales_dir, "en.json")):
|
||||||
|
|
||||||
|
response = requests.get(f"{VERSION_URL}/goob/locales/en.json")
|
||||||
|
if response.status_code == 200:
|
||||||
|
with open(os.path.join(locales_dir, "en.json"), "w", encoding="utf-8") as file:
|
||||||
|
file.write(response.text)
|
||||||
|
|
||||||
|
download_json()
|
||||||
|
def load_translations():
|
||||||
|
translations = {}
|
||||||
|
translations_dir = os.path.join(os.path.dirname(__file__), "locales")
|
||||||
|
|
||||||
|
for filename in os.listdir(translations_dir):
|
||||||
|
if filename.endswith(".json"):
|
||||||
|
lang_code = filename.replace(".json", "")
|
||||||
|
with open(os.path.join(translations_dir, filename), "r", encoding="utf-8") as f:
|
||||||
|
translations[lang_code] = json.load(f)
|
||||||
|
|
||||||
|
return translations
|
||||||
|
|
||||||
|
translations = load_translations()
|
||||||
|
|
||||||
|
|
||||||
|
def save_markov_model(model, filename='markov_model.pkl'):
|
||||||
|
model_file = f"models/{filename}"
|
||||||
|
with open(model_file, "wb") as f:
|
||||||
|
pickle.dump(model, f)
|
||||||
|
print(f"{GREEN}Markov model saved to {model_file}{RESET}")
|
||||||
|
|
||||||
|
def load_markov_model(server_id=None):
|
||||||
|
if server_id:
|
||||||
|
filename = f"markov_model_{server_id}.pkl"
|
||||||
|
else:
|
||||||
|
filename = "markov_model.pkl"
|
||||||
|
|
||||||
|
model_file = f"models/{filename}"
|
||||||
|
|
||||||
|
def get_latest_version_info():
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
response = requests.get(UPDATE_URL, timeout=5)
|
||||||
|
if response.status_code == 200:
|
||||||
|
return response.json()
|
||||||
|
else:
|
||||||
|
print(f"{RED}{get_translation(LOCALE, 'version_error')} {response.status_code}{RESET}")
|
||||||
|
return None
|
||||||
|
except requests.RequestException as e:
|
||||||
|
print(f"{RED}{get_translation(LOCALE, 'version_error')} {e}{RESET}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def load_cogs_from_folder(bot, folder_name="cogs"):
|
||||||
for filename in os.listdir(folder_name):
|
for filename in os.listdir(folder_name):
|
||||||
if filename.endswith(".py") and not filename.startswith("_"):
|
if filename.endswith(".py") and not filename.startswith("_"):
|
||||||
cog_name = filename[:-3]
|
cog_name = filename[:-3]
|
||||||
module_path = folder_name.replace("/", ".").replace("\\", ".") + f".{cog_name}"
|
|
||||||
try:
|
try:
|
||||||
await bot.load_extension(module_path)
|
await bot.load_extension(f"{folder_name}.{cog_name}")
|
||||||
logger.info(f"{(_('loaded_cog'))} {cog_name}")
|
print(f"{GREEN}{get_translation(LOCALE, 'loaded_cog')} {cog_name}{RESET}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"{(_('cog_fail'))} {cog_name} {e}")
|
print(f"{RED}{get_translation(LOCALE, 'cog_fail')} {cog_name} {e}{RESET}")
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
|
|
||||||
async def send_alive_ping_periodically() -> None:
|
currenthash = ""
|
||||||
while True:
|
def generate_sha256_of_current_file():
|
||||||
try:
|
global currenthash
|
||||||
requests.post(f"{VERSION_URL}/aliveping", json={"name": NAME})
|
sha256_hash = hashlib.sha256()
|
||||||
except Exception as e:
|
with open(__file__, "rb") as f:
|
||||||
logger.error(f"{(_('error_sending_alive_ping'))}{RESET} {e}")
|
for byte_block in iter(lambda: f.read(4096), b""):
|
||||||
await asyncio.sleep(60)
|
sha256_hash.update(byte_block)
|
||||||
|
currenthash = sha256_hash.hexdigest()
|
||||||
|
|
||||||
# Event: Called when the bot is ready
|
|
||||||
@bot.event
|
|
||||||
async def on_ready() -> None:
|
|
||||||
global launched
|
|
||||||
global slash_commands_enabled
|
|
||||||
global NAME
|
|
||||||
global status
|
|
||||||
|
|
||||||
folder_name: str = "cogs"
|
|
||||||
if launched:
|
latest_version = "0.0.0"
|
||||||
|
local_version = "rewrite/seperate-memories"
|
||||||
|
os.environ['gooberlocal_version'] = local_version
|
||||||
|
|
||||||
|
|
||||||
|
def check_for_update():
|
||||||
return
|
return
|
||||||
|
|
||||||
await load_cogs_from_folder(bot)
|
def get_file_info(file_path):
|
||||||
try:
|
try:
|
||||||
synced: List[discord.app_commands.AppCommand] = await bot.tree.sync()
|
file_size = os.path.getsize(file_path)
|
||||||
logger.info(f"{_('synced_commands')} {len(synced)} {(_('synced_commands2'))}")
|
with open(file_path, "r") as f:
|
||||||
slash_commands_enabled = True
|
lines = f.readlines()
|
||||||
logger.info(f"{(_('started')).format(name=NAME)}")
|
return {"file_size_bytes": file_size, "line_count": len(lines)}
|
||||||
bot.loop.create_task(send_alive_ping_periodically())
|
|
||||||
except discord.errors.Forbidden as perm_error:
|
|
||||||
logger.error(f"Permission error while syncing commands: {perm_error}")
|
|
||||||
logger.error("Make sure the bot has the 'applications.commands' scope and is invited with the correct permissions.")
|
|
||||||
quit()
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"{_('fail_commands_sync')} {e}")
|
return {"error": str(e)}
|
||||||
|
|
||||||
|
nltk.download('punkt')
|
||||||
|
|
||||||
|
def load_memory(server_id=None):
|
||||||
|
if server_id:
|
||||||
|
memory_file = f"memories/memory_{server_id}.json"
|
||||||
|
else:
|
||||||
|
memory_file = "memories/memory.json"
|
||||||
|
|
||||||
|
data = []
|
||||||
|
try:
|
||||||
|
with open(memory_file, "r") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
print(f"{RED}Error decoding memory file {memory_file}{RESET}")
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
def save_memory(memory, server_id=None):
|
||||||
|
if server_id:
|
||||||
|
memory_file = f"memories/memory_{server_id}.json"
|
||||||
|
else:
|
||||||
|
memory_file = "memories/memory.json"
|
||||||
|
|
||||||
|
with open(memory_file, "w") as f:
|
||||||
|
json.dump(memory, f, indent=4)
|
||||||
|
|
||||||
|
def train_markov_model(memory, additional_data=None, server_id=None):
|
||||||
|
if not memory:
|
||||||
|
return None
|
||||||
|
|
||||||
|
text = "\n".join(memory)
|
||||||
|
if additional_data:
|
||||||
|
text += "\n" + "\n".join(additional_data)
|
||||||
|
|
||||||
|
try:
|
||||||
|
model = markovify.NewlineText(text, state_size=2)
|
||||||
|
if server_id:
|
||||||
|
model_filename = f"markov_model_{server_id}.pkl"
|
||||||
|
save_markov_model(model, model_filename)
|
||||||
|
return model
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{RED}Error training model: {e}{RESET}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
#this doesnt work and im extremely pissed and mad
|
||||||
|
def append_mentions_to_18digit_integer(message):
|
||||||
|
pattern = r'\b\d{18}\b'
|
||||||
|
return re.sub(pattern, lambda match: f"", message)
|
||||||
|
|
||||||
|
def preprocess_message(message):
|
||||||
|
message = append_mentions_to_18digit_integer(message)
|
||||||
|
tokens = word_tokenize(message)
|
||||||
|
tokens = [token for token in tokens if token.isalnum()]
|
||||||
|
return " ".join(tokens)
|
||||||
|
|
||||||
|
|
||||||
|
intents = discord.Intents.default()
|
||||||
|
|
||||||
|
intents.messages = True
|
||||||
|
intents.message_content = True
|
||||||
|
bot = commands.Bot(command_prefix=PREFIX, intents=intents, allowed_mentions=discord.AllowedMentions(everyone=False, roles=False, users=False, replied_user=True))
|
||||||
|
memory = load_memory()
|
||||||
|
markov_model = load_markov_model()
|
||||||
|
if not markov_model:
|
||||||
|
print(f"{get_translation(LOCALE, 'no_model')}")
|
||||||
|
memory = load_memory()
|
||||||
|
markov_model = train_markov_model(memory)
|
||||||
|
|
||||||
|
generated_sentences = set()
|
||||||
|
used_words = set()
|
||||||
|
|
||||||
|
slash_commands_enabled = False
|
||||||
|
@bot.event
|
||||||
|
async def on_ready():
|
||||||
|
|
||||||
|
folder_name = "cogs"
|
||||||
|
if not os.path.exists(folder_name):
|
||||||
|
os.makedirs(folder_name)
|
||||||
|
print(f"{GREEN}{get_translation(LOCALE, 'folder_created').format(folder_name=folder_name)}{RESET}")
|
||||||
|
else:
|
||||||
|
print(f"{DEBUG}{get_translation(LOCALE, 'folder_exists').format(folder_name=folder_name)}{RESET}")
|
||||||
|
markov_model = train_markov_model(memory)
|
||||||
|
await load_cogs_from_folder(bot)
|
||||||
|
global slash_commands_enabled
|
||||||
|
print(f"{GREEN}{get_translation(LOCALE, 'logged_in')} {bot.user}{RESET}")
|
||||||
|
try:
|
||||||
|
synced = await bot.tree.sync()
|
||||||
|
print(f"{GREEN}{get_translation(LOCALE, 'synced_commands')} {len(synced)} {get_translation(LOCALE, 'synced_commands2')} {RESET}")
|
||||||
|
slash_commands_enabled = True
|
||||||
|
print(f"{GREEN}{get_translation(LOCALE, 'started').format()}{RESET}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{RED}{get_translation(LOCALE, 'fail_commands_sync')} {e}{RESET}")
|
||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
quit()
|
quit()
|
||||||
|
|
||||||
if not song:
|
if not song:
|
||||||
return
|
return
|
||||||
|
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{song}"))
|
||||||
|
|
||||||
status = {
|
positive_gifs = os.getenv("POSITIVEGIFS").split(',')
|
||||||
"idle": discord.Status.idle,
|
|
||||||
"dnd": discord.Status.dnd,
|
|
||||||
"invisible": discord.Status.invisible,
|
|
||||||
"online": discord.Status.online
|
|
||||||
}.get(status.lower(), discord.Status.online)
|
|
||||||
await bot.change_presence(status=status, activity=discord.Activity(type=discord.ActivityType.listening, name=f"{song}"))
|
|
||||||
launched = True
|
|
||||||
@bot.event
|
|
||||||
async def on_command_error(ctx: commands.Context, error: commands.CommandError) -> None:
|
|
||||||
from modules.unhandledexception import handle_exception
|
|
||||||
|
|
||||||
if isinstance(error, commands.CommandInvokeError):
|
def is_positive(sentence):
|
||||||
original: Exception = error.original
|
scores = analyzer.polarity_scores(sentence)
|
||||||
handle_exception(
|
sentiment_score = scores['compound']
|
||||||
type(original), original, original.__traceback__,
|
|
||||||
context=f"Command: {ctx.command} | User: {ctx.author}"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
handle_exception(
|
|
||||||
type(error), error, error.__traceback__,
|
|
||||||
context=f"Command: {ctx.command} | User: {ctx.author}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Command: Retrain the Markov model from memory
|
# forcin this fucker
|
||||||
@bot.hybrid_command(description=f"{(_('command_desc_retrain'))}")
|
debug_message = f"{DEBUG}{get_translation(LOCALE, 'sentence_positivity')} {sentiment_score}{RESET}"
|
||||||
async def retrain(ctx: commands.Context) -> None:
|
print(debug_message)
|
||||||
if ctx.author.id != ownerid:
|
|
||||||
return
|
|
||||||
|
|
||||||
message_ref: MessageReference = await send_message(ctx, f"{(_('command_markov_retrain'))}")
|
return sentiment_score > 0.1
|
||||||
|
|
||||||
|
|
||||||
|
async def send_message(ctx, message=None, embed=None, file=None, edit=False, message_reference=None):
|
||||||
|
if edit and message_reference:
|
||||||
try:
|
try:
|
||||||
with open(MEMORY_FILE, 'r') as f:
|
# Editing the existing message
|
||||||
memory: List[str] = json.load(f)
|
await message_reference.edit(content=message, embed=embed)
|
||||||
|
except Exception as e:
|
||||||
|
await ctx.send(f"{RED}{get_translation(LOCALE, 'edit_fail')} {e}{RESET}")
|
||||||
|
else:
|
||||||
|
if hasattr(ctx, "respond"):
|
||||||
|
# For slash command contexts
|
||||||
|
sent_message = None
|
||||||
|
if embed:
|
||||||
|
sent_message = await ctx.respond(embed=embed, ephemeral=False)
|
||||||
|
elif message:
|
||||||
|
sent_message = await ctx.respond(message, ephemeral=False)
|
||||||
|
if file:
|
||||||
|
sent_message = await ctx.respond(file=file, ephemeral=False)
|
||||||
|
else:
|
||||||
|
|
||||||
|
sent_message = None
|
||||||
|
if embed:
|
||||||
|
sent_message = await ctx.send(embed=embed)
|
||||||
|
elif message:
|
||||||
|
sent_message = await ctx.send(message)
|
||||||
|
if file:
|
||||||
|
sent_message = await ctx.send(file=file)
|
||||||
|
return sent_message
|
||||||
|
|
||||||
|
@bot.hybrid_command(description="Retrain Markov models for servers")
|
||||||
|
@app_commands.choices(option=[
|
||||||
|
app_commands.Choice(name="Retrain current server", value="current"),
|
||||||
|
app_commands.Choice(name="Retrain all servers", value="all"),
|
||||||
|
app_commands.Choice(name="Select servers to retrain", value="select")
|
||||||
|
])
|
||||||
|
async def retrain_models(ctx, option: str = None):
|
||||||
|
if option is None and not ctx.interaction:
|
||||||
|
options_text = "all, current, select"
|
||||||
|
return await ctx.send(f"Please specify an option:\n{options_text}")
|
||||||
|
|
||||||
|
if isinstance(option, app_commands.Choice):
|
||||||
|
option = option.value
|
||||||
|
if ctx.author.id == ownerid:
|
||||||
|
if option == "current":
|
||||||
|
server_id = ctx.guild.id if ctx.guild else "DM"
|
||||||
|
await retrain_single_server(ctx, server_id)
|
||||||
|
elif option == "all":
|
||||||
|
await retrain_all_servers(ctx)
|
||||||
|
elif option == "select":
|
||||||
|
await show_server_selection(ctx)
|
||||||
|
else:
|
||||||
|
if ctx.guild and (ctx.author.guild_permissions.administrator or any(role.permissions.administrator for role in ctx.author.roles)):
|
||||||
|
if option == "current":
|
||||||
|
server_id = ctx.guild.id
|
||||||
|
await retrain_single_server(ctx, server_id)
|
||||||
|
else:
|
||||||
|
await ctx.send("You can only retrain the current server.", ephemeral=True)
|
||||||
|
else:
|
||||||
|
await ctx.send("You don't have permission to use this command.", ephemeral=True)
|
||||||
|
|
||||||
|
async def retrain_single_server(ctx, server_id):
|
||||||
|
memory_file = f"memories/memory_{server_id}.json"
|
||||||
|
model_file = f"models/markov_model_{server_id}.pkl"
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(memory_file, 'r') as f:
|
||||||
|
memory = json.load(f)
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
await send_message(ctx, f"{(_('command_markov_memory_not_found'))}")
|
return await ctx.send(f"No memory data found for server {server_id}", ephemeral=True)
|
||||||
return
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
await send_message(ctx, f"{(_('command_markov_memory_is_corrupt'))}")
|
|
||||||
return
|
|
||||||
|
|
||||||
data_size: int = len(memory)
|
processing_msg = await ctx.send(f"Retraining model for server {server_id}...")
|
||||||
processed_data: int = 0
|
|
||||||
processing_message_ref: MessageReference = await send_message(ctx, f"{(_('command_markov_retraining')).format(processed_data=processed_data, data_size=data_size)}")
|
|
||||||
start_time: float = time.time()
|
|
||||||
|
|
||||||
for i, data in enumerate(memory):
|
model = train_markov_model(memory, server_id=server_id)
|
||||||
processed_data += 1
|
|
||||||
|
|
||||||
global markov_model
|
if model:
|
||||||
markov_model = train_markov_model(memory)
|
await processing_msg.edit(content=f"Successfully retrained model for server {server_id}")
|
||||||
save_markov_model(markov_model)
|
else:
|
||||||
|
await processing_msg.edit(content=f"Failed to retrain model for server {server_id}")
|
||||||
|
|
||||||
await send_message(ctx, f"{_('command_markov_retrain_successful').format(data_size=data_size)}", edit=True, message_reference=processing_message_ref)
|
async def retrain_all_servers(ctx):
|
||||||
|
memory_files = [f for f in os.listdir("memories/") if f.startswith("memory_") and f.endswith(".json")]
|
||||||
|
|
||||||
|
if not memory_files:
|
||||||
|
return await ctx.send("No server memory files found to retrain.", ephemeral=True)
|
||||||
|
|
||||||
|
progress_msg = await ctx.send(f"Retraining models for {len(memory_files)} servers...")
|
||||||
|
success_count = 0
|
||||||
|
|
||||||
|
for mem_file in memory_files:
|
||||||
|
try:
|
||||||
|
server_id = mem_file.replace("memory_", "").replace(".json", "")
|
||||||
|
with open(f"memories/{mem_file}", 'r') as f:
|
||||||
|
memory = json.load(f)
|
||||||
|
|
||||||
|
model = train_markov_model(memory, server_id=server_id)
|
||||||
|
if model:
|
||||||
|
success_count += 1
|
||||||
|
|
||||||
|
if success_count % 5 == 0:
|
||||||
|
await progress_msg.edit(content=f"Retraining in progress... {success_count}/{len(memory_files)} completed")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error retraining {mem_file}: {e}")
|
||||||
|
|
||||||
|
await progress_msg.edit(content=f"Retraining complete successfully retrained {success_count}/{len(memory_files)} servers")
|
||||||
|
|
||||||
|
async def show_server_selection(ctx):
|
||||||
|
memory_files = [f for f in os.listdir("memories/") if f.startswith("memory_") and f.endswith(".json")]
|
||||||
|
|
||||||
|
if not memory_files:
|
||||||
|
return await ctx.send("No server memory files found.", ephemeral=True)
|
||||||
|
options = []
|
||||||
|
for mem_file in memory_files:
|
||||||
|
server_id = mem_file.replace("memory_", "").replace(".json", "")
|
||||||
|
server_name = f"Server {server_id}"
|
||||||
|
if server_id != "DM":
|
||||||
|
guild = bot.get_guild(int(server_id))
|
||||||
|
if guild:
|
||||||
|
server_name = guild.name
|
||||||
|
|
||||||
|
options.append(discord.SelectOption(label=server_name, value=server_id))
|
||||||
|
select_menus = []
|
||||||
|
for i in range(0, len(options), 25):
|
||||||
|
chunk = options[i:i+25]
|
||||||
|
|
||||||
|
select = discord.ui.Select(
|
||||||
|
placeholder=f"Select servers to retrain ({i+1}-{min(i+25, len(options))})",
|
||||||
|
min_values=1,
|
||||||
|
max_values=len(chunk),
|
||||||
|
options=chunk
|
||||||
|
)
|
||||||
|
|
||||||
|
select_menus.append(select)
|
||||||
|
view = discord.ui.View()
|
||||||
|
for menu in select_menus:
|
||||||
|
menu.callback = lambda interaction, m=menu: handle_server_selection(interaction, m)
|
||||||
|
view.add_item(menu)
|
||||||
|
|
||||||
|
if ctx.interaction:
|
||||||
|
await ctx.send("Select which servers to retrain:", view=view)
|
||||||
|
else:
|
||||||
|
await ctx.reply("Select which servers to retrain:", view=view)
|
||||||
|
|
||||||
|
async def handle_server_selection(interaction, select_menu):
|
||||||
|
await interaction.response.defer()
|
||||||
|
|
||||||
|
selected_servers = select_menu.values
|
||||||
|
if not selected_servers:
|
||||||
|
return await interaction.followup.send("No servers selected.", ephemeral=True)
|
||||||
|
|
||||||
|
progress_msg = await interaction.followup.send(f"Retraining {len(selected_servers)} selected servers...")
|
||||||
|
success_count = 0
|
||||||
|
|
||||||
|
for server_id in selected_servers:
|
||||||
|
try:
|
||||||
|
memory_file = f"memories/memory_{server_id}.json"
|
||||||
|
with open(memory_file, 'r') as f:
|
||||||
|
memory = json.load(f)
|
||||||
|
|
||||||
|
model = train_markov_model(memory, server_id=server_id)
|
||||||
|
if model:
|
||||||
|
success_count += 1
|
||||||
|
if success_count % 5 == 0:
|
||||||
|
await progress_msg.edit(content=f"Retraining in progress... {success_count}/{len(selected_servers)} completed")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error retraining {server_id}: {e}")
|
||||||
|
|
||||||
|
await progress_msg.edit(content=f"Retraining complete Successfully retrained {success_count}/{len(selected_servers)} selected servers")
|
||||||
|
|
||||||
|
@bot.hybrid_command(description=f"{get_translation(LOCALE, 'command_desc_talk')}")
|
||||||
|
async def talk(ctx, sentence_size: int = 5):
|
||||||
|
server_id = ctx.guild.id if ctx.guild else "DM"
|
||||||
|
markov_model = load_markov_model(server_id)
|
||||||
|
|
||||||
# Command: Generate a sentence using the Markov model
|
|
||||||
@bot.hybrid_command(description=f"{(_('command_desc_talk'))}")
|
|
||||||
async def talk(ctx: commands.Context, sentence_size: int = 5) -> None:
|
|
||||||
if not markov_model:
|
if not markov_model:
|
||||||
await send_message(ctx, f"{(_('command_talk_insufficent_text'))}")
|
memory = load_memory(server_id)
|
||||||
|
markov_model = train_markov_model(memory, server_id=server_id)
|
||||||
|
if not markov_model:
|
||||||
|
await send_message(ctx, f"{get_translation(LOCALE, 'command_talk_insufficent_text')}")
|
||||||
return
|
return
|
||||||
|
|
||||||
response: Optional[str] = None
|
response = None
|
||||||
for _ in range(20):
|
for _ in range(20):
|
||||||
if sentence_size == 1:
|
if sentence_size == 1:
|
||||||
response = markov_model.make_short_sentence(max_chars=100, tries=100)
|
response = markov_model.make_short_sentence(max_chars=100, tries=100)
|
||||||
|
@ -204,169 +445,65 @@ async def talk(ctx: commands.Context, sentence_size: int = 5) -> None:
|
||||||
break
|
break
|
||||||
|
|
||||||
if response:
|
if response:
|
||||||
cleaned_response: str = re.sub(r'[^\w\s]', '', response).lower()
|
cleaned_response = re.sub(r'[^\w\s]', '', response).lower()
|
||||||
coherent_response: str = rephrase_for_coherence(cleaned_response)
|
coherent_response = rephrase_for_coherence(cleaned_response)
|
||||||
if random.random() < 0.9 and is_positive(coherent_response):
|
if random.random() < 0.9 and is_positive(coherent_response):
|
||||||
gif_url: str = random.choice(positive_gifs)
|
gif_url = random.choice(positive_gifs)
|
||||||
combined_message: str = f"{coherent_response}\n[jif]({gif_url})"
|
combined_message = f"{coherent_response}\n[jif]({gif_url})"
|
||||||
else:
|
else:
|
||||||
combined_message: str = coherent_response
|
combined_message = coherent_response
|
||||||
logger.info(combined_message)
|
print(combined_message)
|
||||||
os.environ['gooberlatestgen'] = combined_message
|
os.environ['gooberlatestgen'] = combined_message
|
||||||
await send_message(ctx, combined_message)
|
await send_message(ctx, combined_message)
|
||||||
else:
|
else:
|
||||||
await send_message(ctx, f"{(_('command_talk_generation_fail'))}")
|
await send_message(ctx, f"{get_translation(LOCALE, 'command_talk_generation_fail')}")
|
||||||
|
|
||||||
@bot.hybrid_command(description=f"RAM")
|
|
||||||
async def ramusage(ctx):
|
|
||||||
process = psutil.Process(os.getpid())
|
|
||||||
mem = process.memory_info().rss
|
|
||||||
await send_message(ctx, f"Total memory used: {mem / 1024 / 1024:.2f} MB")
|
|
||||||
|
|
||||||
# Command: Generate an image
|
|
||||||
@bot.hybrid_command(description=f"{(_('command_desc_help'))}")
|
|
||||||
async def impact(ctx: commands.Context, text: Optional[str] = None) -> None:
|
|
||||||
assets_folder: str = "assets/images"
|
|
||||||
temp_input: Optional[str] = None
|
|
||||||
|
|
||||||
def get_random_asset_image() -> Optional[str]:
|
|
||||||
files: List[str] = [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: discord.Attachment = ctx.message.attachments[0]
|
|
||||||
if attachment.content_type and attachment.content_type.startswith("image/"):
|
|
||||||
ext: str = os.path.splitext(attachment.filename)[1]
|
|
||||||
temp_input = f"tempy{ext}"
|
|
||||||
await attachment.save(temp_input)
|
|
||||||
input_path: str = temp_input
|
|
||||||
else:
|
|
||||||
fallback_image: Optional[str] = get_random_asset_image()
|
|
||||||
if fallback_image is None:
|
|
||||||
await ctx.reply(_('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(_('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: Optional[str] = await gen_meme(input_path, custom_text=text)
|
|
||||||
|
|
||||||
|
|
||||||
if output_path is None or not os.path.isfile(output_path):
|
def improve_sentence_coherence(sentence):
|
||||||
if temp_input and os.path.exists(temp_input):
|
|
||||||
os.remove(temp_input)
|
|
||||||
await ctx.reply(_('failed_generate_image'))
|
|
||||||
return
|
|
||||||
|
|
||||||
await ctx.send(file=discord.File(output_path))
|
sentence = sentence.replace(" i ", " I ")
|
||||||
|
return sentence
|
||||||
|
|
||||||
if temp_input and os.path.exists(temp_input):
|
def rephrase_for_coherence(sentence):
|
||||||
os.remove(temp_input)
|
|
||||||
|
|
||||||
# New demotivator command
|
words = sentence.split()
|
||||||
@bot.hybrid_command(description="Generate a demotivator poster with two lines of text")
|
|
||||||
async def demotivator(ctx: commands.Context) -> None:
|
|
||||||
assets_folder: str = "assets/images"
|
|
||||||
temp_input: Optional[str] = None
|
|
||||||
|
|
||||||
def get_random_asset_image() -> Optional[str]:
|
coherent_sentence = " ".join(words)
|
||||||
files: List[str] = [f for f in os.listdir(assets_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]
|
return coherent_sentence
|
||||||
if not files:
|
|
||||||
return None
|
|
||||||
return os.path.join(assets_folder, random.choice(files))
|
|
||||||
|
|
||||||
if ctx.message.attachments:
|
bot.help_command = None
|
||||||
attachment: discord.Attachment = ctx.message.attachments[0]
|
|
||||||
if attachment.content_type and attachment.content_type.startswith("image/"):
|
|
||||||
ext: str = os.path.splitext(attachment.filename)[1]
|
|
||||||
temp_input = f"tempy{ext}"
|
|
||||||
await attachment.save(temp_input)
|
|
||||||
input_path: str = temp_input
|
|
||||||
else:
|
|
||||||
fallback_image: Optional[str] = get_random_asset_image()
|
|
||||||
if fallback_image is None:
|
|
||||||
await ctx.reply(_('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(_('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: Optional[str] = await gen_demotivator(input_path)
|
|
||||||
|
|
||||||
if output_path is None or not os.path.isfile(output_path):
|
@bot.hybrid_command(description=f"{get_translation(LOCALE, 'command_desc_help')}")
|
||||||
if temp_input and os.path.exists(temp_input):
|
async def help(ctx):
|
||||||
os.remove(temp_input)
|
embed = discord.Embed(
|
||||||
await ctx.reply("Failed to generate demotivator.")
|
title=f"{get_translation(LOCALE, 'command_help_embed_title')}",
|
||||||
return
|
description=f"{get_translation(LOCALE, 'command_help_embed_desc')}",
|
||||||
|
color=discord.Color.blue()
|
||||||
await ctx.send(file=discord.File(output_path))
|
|
||||||
|
|
||||||
if temp_input and os.path.exists(temp_input):
|
|
||||||
os.remove(temp_input)
|
|
||||||
|
|
||||||
bot.remove_command('help')
|
|
||||||
# Command: Show help information
|
|
||||||
@bot.hybrid_command(description=f"{(_('command_desc_help'))}")
|
|
||||||
async def help(ctx: commands.Context) -> None:
|
|
||||||
embed: discord.Embed = discord.Embed(
|
|
||||||
title=f"{(_('command_help_embed_title'))}",
|
|
||||||
description=f"{(_('command_help_embed_desc'))}",
|
|
||||||
color=Colour(0x000000)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
command_categories: Dict[str, List[str]] = {
|
command_categories = {
|
||||||
f"{(_('command_help_categories_general'))}": ["mem", "talk", "about", "ping", "impact", "demotivator", "help"],
|
f"{get_translation(LOCALE, 'command_help_categories_general')}": ["mem", "talk", "about", "ping"],
|
||||||
f"{(_('command_help_categories_admin'))}": ["stats", "retrain", "setlanguage"]
|
f"{get_translation(LOCALE, 'command_help_categories_admin')}": ["stats", "retrain"]
|
||||||
}
|
}
|
||||||
|
|
||||||
custom_commands: List[str] = []
|
custom_commands = []
|
||||||
for cog_name, cog in bot.cogs.items():
|
for cog_name, cog in bot.cogs.items():
|
||||||
for command in cog.get_commands():
|
for command in cog.get_commands():
|
||||||
if command.name not in command_categories[f"{(_('command_help_categories_general'))}"] and command.name not in command_categories[f"{(_('command_help_categories_admin'))}"]:
|
if command.name not in command_categories[f"{get_translation(LOCALE, 'command_help_categories_general')}"] and command.name not in command_categories[f"{get_translation(LOCALE, 'command_help_categories_admin')}"]:
|
||||||
custom_commands.append(command.name)
|
custom_commands.append(command.name)
|
||||||
|
|
||||||
if custom_commands:
|
if custom_commands:
|
||||||
embed.add_field(name=f"{(_('command_help_categories_custom'))}", value="\n".join([f"{PREFIX}{command}" for command in custom_commands]), inline=False)
|
embed.add_field(name=f"{get_translation(LOCALE, 'command_help_categories_custom')}", value="\n".join([f"{PREFIX}{command}" for command in custom_commands]), inline=False)
|
||||||
|
|
||||||
for category, commands_list in command_categories.items():
|
for category, commands_list in command_categories.items():
|
||||||
commands_in_category: str = "\n".join([f"{PREFIX}{command}" for command in commands_list])
|
commands_in_category = "\n".join([f"{PREFIX}{command}" for command in commands_list])
|
||||||
embed.add_field(name=category, value=commands_in_category, inline=False)
|
embed.add_field(name=category, value=commands_in_category, inline=False)
|
||||||
|
|
||||||
await send_message(ctx, embed=embed)
|
await send_message(ctx, embed=embed)
|
||||||
|
|
||||||
@bot.hybrid_command(description=f"{(_('command_desc_setlang'))}")
|
|
||||||
@app_commands.describe(locale="Choose your language")
|
|
||||||
async def setlanguage(ctx: commands.Context, locale: str) -> None:
|
|
||||||
if ctx.author.id != ownerid:
|
|
||||||
await ctx.send(":thumbsdown:")
|
|
||||||
return
|
|
||||||
await ctx.defer()
|
|
||||||
set_language(locale)
|
|
||||||
await ctx.send(":thumbsup:")
|
|
||||||
|
|
||||||
# Event: Called on every message
|
|
||||||
@bot.event
|
@bot.event
|
||||||
async def on_message(message: discord.Message) -> None:
|
async def on_message(message):
|
||||||
global memory, markov_model
|
|
||||||
EMOJIS = ["\U0001F604", "\U0001F44D", "\U0001F525", "\U0001F4AF", "\U0001F389", "\U0001F60E"] # originally was emojis but it would probably shit itself on systems without unicode so....
|
|
||||||
if message.author.bot:
|
if message.author.bot:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
@ -374,155 +511,114 @@ async def on_message(message: discord.Message) -> None:
|
||||||
return
|
return
|
||||||
|
|
||||||
if message.content.startswith((f"{PREFIX}talk", f"{PREFIX}mem", f"{PREFIX}help", f"{PREFIX}stats", f"{PREFIX}")):
|
if message.content.startswith((f"{PREFIX}talk", f"{PREFIX}mem", f"{PREFIX}help", f"{PREFIX}stats", f"{PREFIX}")):
|
||||||
logger.info(f"{(_('command_ran')).format(message=message)}")
|
print(f"{get_translation(LOCALE, 'command_ran').format(message=message)}")
|
||||||
await bot.process_commands(message)
|
await bot.process_commands(message)
|
||||||
return
|
return
|
||||||
|
|
||||||
if message.content:
|
if profanity.contains_profanity(message.content):
|
||||||
if not USERTRAIN_ENABLED:
|
|
||||||
return
|
return
|
||||||
formatted_message: str = message.content
|
|
||||||
cleaned_message: str = formatted_message
|
if message.content and USERTRAIN_ENABLED:
|
||||||
|
server_id = message.guild.id if message.guild else "DM"
|
||||||
|
memory = load_memory(server_id)
|
||||||
|
|
||||||
|
formatted_message = append_mentions_to_18digit_integer(message.content)
|
||||||
|
cleaned_message = preprocess_message(formatted_message)
|
||||||
|
|
||||||
if cleaned_message:
|
if cleaned_message:
|
||||||
memory.append(cleaned_message)
|
memory.append(cleaned_message)
|
||||||
message_metadata = {
|
save_memory(memory, server_id)
|
||||||
"user_id": str(message.author.id),
|
|
||||||
"user_name": str(message.author),
|
|
||||||
"guild_id": str(message.guild.id) if message.guild else "DM",
|
|
||||||
"guild_name": str(message.guild.name) if message.guild else "DM",
|
|
||||||
"channel_id": str(message.channel.id),
|
|
||||||
"channel_name": str(message.channel),
|
|
||||||
"message": message.content,
|
|
||||||
"timestamp": time.time()
|
|
||||||
}
|
|
||||||
try:
|
|
||||||
if isinstance(memory, list):
|
|
||||||
memory.append({"_meta": message_metadata})
|
|
||||||
else:
|
|
||||||
logger.warning("Memory is not a list; can't append metadata")
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Failed to append metadata to memory: {e}")
|
|
||||||
|
|
||||||
save_memory(memory)
|
|
||||||
|
|
||||||
sentiment_score = is_positive(message.content) # doesnt work but im scared to change the logic now please ignore
|
|
||||||
if sentiment_score > 0.8:
|
|
||||||
if REACT != "True":
|
|
||||||
return
|
|
||||||
emoji = random.choice(EMOJIS)
|
|
||||||
try:
|
|
||||||
await message.add_reaction(emoji)
|
|
||||||
except Exception as e:
|
|
||||||
logger.info(f"Failed to react with emoji: {e}")
|
|
||||||
|
|
||||||
await bot.process_commands(message)
|
await bot.process_commands(message)
|
||||||
|
|
||||||
@bot.event
|
|
||||||
async def on_interaction(interaction: discord.Interaction) -> None:
|
|
||||||
name = None
|
|
||||||
if interaction.data.get('name') is None:
|
|
||||||
name = "Unknown"
|
|
||||||
else:
|
|
||||||
name = interaction.data['name']
|
|
||||||
logger.info(f"{(_('command_ran_s')).format(interaction=interaction)}{name}")
|
|
||||||
|
|
||||||
# Global check: Block blacklisted users from running commands
|
@bot.event
|
||||||
|
async def on_interaction(interaction):
|
||||||
|
try:
|
||||||
|
if interaction.type == discord.InteractionType.application_command:
|
||||||
|
command_name = interaction.data.get('name', 'unknown')
|
||||||
|
print(f"{get_translation(LOCALE, 'command_ran_s').format(interaction=interaction)}{command_name}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{RED}Error handling interaction: {e}{RESET}")
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
@bot.check
|
@bot.check
|
||||||
async def block_blacklisted(ctx: commands.Context) -> bool:
|
async def block_blacklisted(ctx):
|
||||||
if str(ctx.author.id) in BLACKLISTED_USERS:
|
if str(ctx.author.id) in BLACKLISTED_USERS:
|
||||||
try:
|
try:
|
||||||
if isinstance(ctx, discord.Interaction):
|
if isinstance(ctx, discord.Interaction):
|
||||||
if not ctx.response.is_done():
|
if not ctx.response.is_done():
|
||||||
await ctx.response.send_message(_('blacklisted'), ephemeral=True)
|
await ctx.response.send_message("You are blacklisted.", ephemeral=True)
|
||||||
else:
|
else:
|
||||||
await ctx.followup.send(_('blacklisted'), ephemeral=True)
|
await ctx.followup.send("You are blacklisted.", ephemeral=True)
|
||||||
else:
|
else:
|
||||||
await ctx.send(_('blacklisted_user'), ephemeral=True)
|
await ctx.send("You are blacklisted.", ephemeral=True)
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Command: Show bot latency
|
@bot.hybrid_command(description=f"{get_translation(LOCALE, 'command_desc_ping')}")
|
||||||
@bot.hybrid_command(description=f"{(_('command_desc_ping'))}")
|
async def ping(ctx):
|
||||||
async def ping(ctx: commands.Context) -> None:
|
|
||||||
await ctx.defer()
|
await ctx.defer()
|
||||||
latency: int = round(bot.latency * 1000)
|
latency = round(bot.latency * 1000)
|
||||||
|
|
||||||
LOLembed: discord.Embed = discord.Embed(
|
LOLembed = discord.Embed(
|
||||||
title="Pong!!",
|
title="Pong!!",
|
||||||
description=(
|
description=(
|
||||||
f"{PING_LINE}\n"
|
f"{PING_LINE}\n"
|
||||||
f"`{(_('command_ping_embed_desc'))}: {latency}ms`\n"
|
f"`{get_translation(LOCALE, 'command_ping_embed_desc')}: {latency}ms`\n"
|
||||||
),
|
),
|
||||||
color=Colour(0x000000)
|
color=discord.Color.blue()
|
||||||
)
|
)
|
||||||
LOLembed.set_footer(text=f"{(_('command_ping_footer'))} {ctx.author.name}", icon_url=ctx.author.avatar.url)
|
LOLembed.set_footer(text=f"{get_translation(LOCALE, 'command_ping_footer')} {ctx.author.name}", icon_url=ctx.author.avatar.url)
|
||||||
|
|
||||||
await ctx.send(embed=LOLembed)
|
await ctx.send(embed=LOLembed)
|
||||||
|
|
||||||
def get_git_remote_url():
|
@bot.hybrid_command(description=f"{get_translation(LOCALE, 'command_about_desc')}")
|
||||||
try:
|
async def about(ctx):
|
||||||
url = subprocess.check_output(
|
embed = discord.Embed(title=f"{get_translation(LOCALE, 'command_about_embed_title')}", description="", color=discord.Color.blue())
|
||||||
["git", "config", "--get", "remote.origin.url"],
|
embed.add_field(name=f"{get_translation(LOCALE, 'command_about_embed_field1')}", value=f"{NAME}", inline=False)
|
||||||
text=True,
|
embed.add_field(name=f"{get_translation(LOCALE, 'command_about_embed_field2name')}", value=f"{get_translation(LOCALE, 'command_about_embed_field2value').format(local_version=local_version, latest_version='I have not been updated with the new version checking!')}", inline=False)
|
||||||
stderr=subprocess.DEVNULL,
|
|
||||||
).strip()
|
|
||||||
return url
|
|
||||||
except subprocess.CalledProcessError:
|
|
||||||
return "Unknown"
|
|
||||||
|
|
||||||
# Command: Show about information
|
|
||||||
@bot.hybrid_command(description=f"{(_('command_about_desc'))}")
|
|
||||||
async def about(ctx: commands.Context) -> None:
|
|
||||||
print("-----------------------------------\n\n")
|
|
||||||
latest_version: str = check_for_update()
|
|
||||||
print("-----------------------------------")
|
|
||||||
embed: discord.Embed = discord.Embed(title=f"{(_('command_about_embed_title'))}", description="", color=Colour(0x000000))
|
|
||||||
embed.add_field(name=f"{(_('command_about_embed_field1'))}", value=f"{NAME}", inline=False)
|
|
||||||
embed.add_field(name=f"{(_('command_about_embed_field2name'))}", value=f"{(_('command_about_embed_field2value')).format(local_version=local_version, latest_version=latest_version)}", inline=False)
|
|
||||||
embed.add_field(name=f"Git", value=get_git_remote_url())
|
|
||||||
embed.add_field(name=f"OS", value=platform.platform())
|
|
||||||
|
|
||||||
await send_message(ctx, embed=embed)
|
await send_message(ctx, embed=embed)
|
||||||
|
|
||||||
# Command: Show bot statistics (admin only)
|
|
||||||
@bot.hybrid_command(description="stats")
|
@bot.hybrid_command(description="stats")
|
||||||
async def stats(ctx: commands.Context) -> None:
|
async def stats(ctx):
|
||||||
if ctx.author.id != ownerid:
|
if ctx.author.id != ownerid:
|
||||||
return
|
return
|
||||||
print("-----------------------------------\n\n")
|
print("-----------------------------------\n\n")
|
||||||
latest_version: str = check_for_update()
|
try:
|
||||||
|
check_for_update()
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
print("-----------------------------------")
|
print("-----------------------------------")
|
||||||
memory_file: str = 'memory.json'
|
memory_file = 'memory.json'
|
||||||
file_size: int = os.path.getsize(memory_file)
|
file_size = os.path.getsize(memory_file)
|
||||||
|
|
||||||
with open(memory_file, 'r') as file:
|
with open(memory_file, 'r') as file:
|
||||||
line_count: int = sum(1 for _ in file)
|
line_count = sum(1 for _ in file)
|
||||||
|
embed = discord.Embed(title=f"{get_translation(LOCALE, 'command_stats_embed_title')}", description=f"{get_translation(LOCALE, 'command_stats_embed_desc')}", color=discord.Color.blue())
|
||||||
|
embed.add_field(name=f"{get_translation(LOCALE, 'command_stats_embed_field1name')}", value=f"{get_translation(LOCALE, 'command_stats_embed_field1value').format(file_size=file_size, line_count=line_count)}", inline=False)
|
||||||
|
embed.add_field(name=f"{get_translation(LOCALE, 'command_stats_embed_field2name')}", value=f"{get_translation(LOCALE, 'command_stats_embed_field2value').format(local_version=local_version, latest_version=latest_version)}", inline=False)
|
||||||
|
embed.add_field(name=f"{get_translation(LOCALE, 'command_stats_embed_field3name')}", value=f"{get_translation(LOCALE, 'command_stats_embed_field3value').format(NAME=NAME, PREFIX=PREFIX, ownerid=ownerid, cooldown_time=cooldown_time, PING_LINE=PING_LINE, showmemenabled=showmemenabled, USERTRAIN_ENABLED=USERTRAIN_ENABLED, last_random_talk_time=last_random_talk_time, song=song, splashtext=splashtext)}", inline=False)
|
||||||
|
|
||||||
embed: discord.Embed = discord.Embed(title=f"{(_('command_stats_embed_title'))}", description=f"{(_('command_stats_embed_desc'))}", color=Colour(0x000000))
|
|
||||||
embed.add_field(name=f"{(_('command_stats_embed_field1name'))}", value=f"{(_('command_stats_embed_field1value')).format(file_size=file_size, line_count=line_count)}", inline=False)
|
|
||||||
embed.add_field(name=f"{(_('command_stats_embed_field2name'))}", value=f"{(_('command_stats_embed_field2value')).format(local_version=local_version, latest_version=latest_version)}", inline=False)
|
|
||||||
embed.add_field(name=f"{(_('command_stats_embed_field3name'))}", value=f"{(_('command_stats_embed_field3value')).format(NAME=NAME, PREFIX=PREFIX, ownerid=ownerid, PING_LINE=PING_LINE, showmemenabled=showmemenabled, USERTRAIN_ENABLED=USERTRAIN_ENABLED, song=song, splashtext=splashtext)}", inline=False)
|
|
||||||
embed.add_field(name=f"OS", value=platform.platform())
|
|
||||||
embed.add_field(name="Python Version", value=platform.python_version())
|
|
||||||
await send_message(ctx, embed=embed)
|
await send_message(ctx, embed=embed)
|
||||||
|
|
||||||
# Command: Upload memory.json to litterbox.catbox.moe and return the link
|
|
||||||
@bot.hybrid_command()
|
@bot.hybrid_command()
|
||||||
async def mem(ctx: commands.Context) -> None:
|
async def mem(ctx):
|
||||||
if showmemenabled != "true":
|
if showmemenabled != "true":
|
||||||
return
|
return
|
||||||
command: str = """curl -F "reqtype=fileupload" -F "time=1h" -F "fileToUpload=@memory.json" https://litterbox.catbox.moe/resources/internals/api.php"""
|
server_id = ctx.guild.id if ctx.guild else "DM"
|
||||||
memorylitter: subprocess.CompletedProcess = subprocess.run(command, shell=True, capture_output=True, text=True)
|
memory_file = f"memories/memory_{server_id}.json" if server_id else "memories/memory.json"
|
||||||
logger.debug(memorylitter)
|
try:
|
||||||
await send_message(ctx, memorylitter.stdout.strip())
|
with open(memory_file, "r") as f:
|
||||||
|
await send_message(ctx, file=discord.File(f, memory_file))
|
||||||
|
except FileNotFoundError:
|
||||||
|
await send_message(ctx, f"No memory file found at {memory_file}")
|
||||||
|
|
||||||
# Helper: Improve sentence coherence (simple capitalization fix)
|
def improve_sentence_coherence(sentence):
|
||||||
def improve_sentence_coherence(sentence: str) -> str:
|
|
||||||
# Capitalizes "i" to "I" in the sentence
|
|
||||||
sentence = sentence.replace(" i ", " I ")
|
sentence = sentence.replace(" i ", " I ")
|
||||||
return sentence
|
return sentence
|
||||||
|
|
||||||
# Start the bot
|
|
||||||
bot.run(TOKEN)
|
bot.run(TOKEN)
|
245
botminimal.py
|
@ -1,245 +0,0 @@
|
||||||
import discord
|
|
||||||
from discord.ext import commands, tasks
|
|
||||||
import json
|
|
||||||
import markovify
|
|
||||||
import nltk
|
|
||||||
from nltk.tokenize import word_tokenize
|
|
||||||
import random
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import re
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
load_dotenv()
|
|
||||||
# download NLTK data files
|
|
||||||
nltk.download('punkt')
|
|
||||||
MEMORY_FILE = "memory.json"
|
|
||||||
MEMORY_LOADED_FILE = "MEMORY_LOADED"
|
|
||||||
|
|
||||||
def load_memory():
|
|
||||||
data = []
|
|
||||||
|
|
||||||
# Try to load data from MEMORY_FILE
|
|
||||||
try:
|
|
||||||
with open(MEMORY_FILE, "r") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
except FileNotFoundError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return data
|
|
||||||
|
|
||||||
# Save memory data to MEMORY_FILE
|
|
||||||
def save_memory(memory):
|
|
||||||
with open(MEMORY_FILE, "w") as f:
|
|
||||||
json.dump(memory, f, indent=4)
|
|
||||||
|
|
||||||
def train_markov_model(memory, additional_data=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
|
|
||||||
|
|
||||||
#this doesnt work and im extremely pissed and mad
|
|
||||||
def append_mentions_to_18digit_integer(message):
|
|
||||||
pattern = r'\b\d{18}\b'
|
|
||||||
return re.sub(pattern, lambda match: f"<@{match.group(0)}>", message)
|
|
||||||
|
|
||||||
def preprocess_message(message):
|
|
||||||
message = append_mentions_to_18digit_integer(message)
|
|
||||||
tokens = word_tokenize(message)
|
|
||||||
tokens = [token for token in tokens if token.isalnum()]
|
|
||||||
return " ".join(tokens)
|
|
||||||
|
|
||||||
|
|
||||||
intents = discord.Intents.default()
|
|
||||||
intents.messages = True
|
|
||||||
intents.message_content = True
|
|
||||||
bot = commands.Bot(command_prefix="g!", intents=intents)
|
|
||||||
memory = load_memory()
|
|
||||||
markov_model = train_markov_model(memory)
|
|
||||||
|
|
||||||
generated_sentences = set()
|
|
||||||
used_words = set()
|
|
||||||
|
|
||||||
@bot.event
|
|
||||||
async def on_ready():
|
|
||||||
print(f"Logged in as {bot.user}")
|
|
||||||
post_message.start()
|
|
||||||
|
|
||||||
positive_keywords = ["happy", "good", "great", "amazing", "awesome", "joy", "love", "fantastic", "positive", "cheerful", "victory", "favorite", "lmao", "lol", "xd", "XD", "xD", "Xd"]
|
|
||||||
|
|
||||||
positive_gifs = [
|
|
||||||
"https://tenor.com/view/chill-guy-my-new-character-gif-2777893510283028272",
|
|
||||||
"https://tenor.com/view/goodnight-goodnight-friends-weezer-weezer-goodnight-gif-7322052181075806988"
|
|
||||||
]
|
|
||||||
|
|
||||||
def is_positive(sentence):
|
|
||||||
sentence_lower = sentence.lower()
|
|
||||||
return any(keyword in sentence_lower for keyword in positive_keywords)
|
|
||||||
|
|
||||||
@bot.command()
|
|
||||||
async def ask(ctx):
|
|
||||||
await ctx.send("Command undergoing fixes!")
|
|
||||||
#not really lol
|
|
||||||
|
|
||||||
@bot.command()
|
|
||||||
async def talk(ctx):
|
|
||||||
if markov_model:
|
|
||||||
response = None
|
|
||||||
for _ in range(10): # im going to shit my pants 10 times to get a coherent sentence
|
|
||||||
response = markov_model.make_sentence(tries=100)
|
|
||||||
if response and response not in generated_sentences:
|
|
||||||
# preprocess shit for grammer
|
|
||||||
response = improve_sentence_coherence(response)
|
|
||||||
generated_sentences.add(response)
|
|
||||||
break
|
|
||||||
|
|
||||||
if response:
|
|
||||||
async with ctx.typing():
|
|
||||||
cleaned_response = re.sub(r'[^\w\s]', '', response)
|
|
||||||
cleaned_response = cleaned_response.lower()
|
|
||||||
coherent_response = rephrase_for_coherence(cleaned_response)
|
|
||||||
if random.random() < 0.9:
|
|
||||||
if is_positive(coherent_response):
|
|
||||||
gif_url = random.choice(positive_gifs)
|
|
||||||
combined_message = f"{coherent_response}\n[jif]({gif_url})"
|
|
||||||
await ctx.send(combined_message)
|
|
||||||
else:
|
|
||||||
await ctx.send(coherent_response)
|
|
||||||
else:
|
|
||||||
await ctx.send(coherent_response)
|
|
||||||
else:
|
|
||||||
await ctx.send("I have nothing to say right now!")
|
|
||||||
else:
|
|
||||||
await ctx.send("I need to learn more from messages before I can talk.")
|
|
||||||
|
|
||||||
def improve_sentence_coherence(sentence):
|
|
||||||
|
|
||||||
sentence = sentence.replace(" i ", " I ")
|
|
||||||
return sentence
|
|
||||||
|
|
||||||
def rephrase_for_coherence(sentence):
|
|
||||||
|
|
||||||
words = sentence.split()
|
|
||||||
|
|
||||||
coherent_sentence = " ".join(words)
|
|
||||||
return coherent_sentence
|
|
||||||
|
|
||||||
bot.help_command = None
|
|
||||||
|
|
||||||
|
|
||||||
@bot.command()
|
|
||||||
async def help(ctx, *args):
|
|
||||||
|
|
||||||
if args:
|
|
||||||
command_name = args[0]
|
|
||||||
command = bot.get_command(command_name)
|
|
||||||
|
|
||||||
if command:
|
|
||||||
embed = discord.Embed(
|
|
||||||
title=f"Help: g!{command_name}",
|
|
||||||
description=f"**Description:** {command.help}",
|
|
||||||
color=discord.Color.blue()
|
|
||||||
)
|
|
||||||
await ctx.send(embed=embed)
|
|
||||||
else:
|
|
||||||
await ctx.send(f"Command `{command_name}` not found.")
|
|
||||||
else:
|
|
||||||
|
|
||||||
embed = discord.Embed(
|
|
||||||
title="Bot Help",
|
|
||||||
description="List of commands grouped by category.",
|
|
||||||
color=discord.Color.blue()
|
|
||||||
)
|
|
||||||
|
|
||||||
command_categories = {
|
|
||||||
"General": ["show_memory", "talk", "ask", "ping"],
|
|
||||||
"Debug": ["word_usage"]
|
|
||||||
}
|
|
||||||
|
|
||||||
for category, commands_list in command_categories.items():
|
|
||||||
commands_in_category = "\n".join([f"g!{command}" for command in commands_list])
|
|
||||||
embed.add_field(name=category, value=commands_in_category, inline=False)
|
|
||||||
|
|
||||||
await ctx.send(embed=embed)
|
|
||||||
|
|
||||||
@bot.event
|
|
||||||
async def on_message(message):
|
|
||||||
global memory, markov_model, last_random_talk_time
|
|
||||||
|
|
||||||
if message.author.bot:
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
if message.content.startswith(("g!talk", "g!show_memory", "g!help", "g!")):
|
|
||||||
await bot.process_commands(message)
|
|
||||||
return
|
|
||||||
|
|
||||||
if message.content:
|
|
||||||
formatted_message = append_mentions_to_18digit_integer(message.content)
|
|
||||||
cleaned_message = preprocess_message(formatted_message)
|
|
||||||
if cleaned_message:
|
|
||||||
memory.append(cleaned_message)
|
|
||||||
save_memory(memory)
|
|
||||||
markov_model = train_markov_model(memory)
|
|
||||||
|
|
||||||
# process any commands in the message
|
|
||||||
await bot.process_commands(message)
|
|
||||||
|
|
||||||
@bot.command()
|
|
||||||
async def ping(ctx):
|
|
||||||
await ctx.defer()
|
|
||||||
#stolen from my expect bot very proud
|
|
||||||
latency = round(bot.latency * 1000)
|
|
||||||
|
|
||||||
LOLembed = discord.Embed(
|
|
||||||
title="Pong!!",
|
|
||||||
description=(
|
|
||||||
f"The Beretta fires fast and won't make you feel any better!\n"
|
|
||||||
f"`Bot Latency: {latency}ms`\n"
|
|
||||||
),
|
|
||||||
color=discord.Color.blue()
|
|
||||||
)
|
|
||||||
LOLembed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar.url)
|
|
||||||
|
|
||||||
await ctx.send(embed=LOLembed) # use ctx.send instead of respond because it has nothing to respond to and its not a slash command
|
|
||||||
|
|
||||||
@bot.command()
|
|
||||||
async def show_memory(ctx):
|
|
||||||
memory = load_memory()
|
|
||||||
memory_text = json.dumps(memory, indent=4)
|
|
||||||
if len(memory_text) > 1024:
|
|
||||||
with open(MEMORY_FILE, "r") as f:
|
|
||||||
await ctx.send(" ", file=discord.File(f, MEMORY_FILE))
|
|
||||||
else:
|
|
||||||
embed = discord.Embed(title="Memory Contents", description="The bot's memory.", color=discord.Color.blue())
|
|
||||||
embed.add_field(name="Memory Data", value=f"```json\n{memory_text}\n```", inline=False)
|
|
||||||
await ctx.send(embed=embed)
|
|
||||||
|
|
||||||
def improve_sentence_coherence(sentence):
|
|
||||||
sentence = sentence.replace(" i ", " I ")
|
|
||||||
return sentence
|
|
||||||
|
|
||||||
@tasks.loop(minutes=60)
|
|
||||||
async def post_message():
|
|
||||||
channel_id = 1296141985253691433
|
|
||||||
channel = bot.get_channel(channel_id)
|
|
||||||
if channel and markov_model:
|
|
||||||
response = None
|
|
||||||
for _ in range(10):
|
|
||||||
response = markov_model.make_sentence(tries=100)
|
|
||||||
if response and response not in generated_sentences:
|
|
||||||
generated_sentences.add(response)
|
|
||||||
break
|
|
||||||
|
|
||||||
if response:
|
|
||||||
await channel.send(response)
|
|
||||||
|
|
||||||
# run the bot
|
|
||||||
TOKEN = os.getenv("DISCORDBOTTOKEN", "0")
|
|
||||||
bot.run(TOKEN)
|
|
|
@ -8,6 +8,9 @@ by PowerPCFan
|
||||||
[Cog Manager](https://github.com/WhatDidYouExpect/goober/blob/main/cogs/cogmanager.py)
|
[Cog Manager](https://github.com/WhatDidYouExpect/goober/blob/main/cogs/cogmanager.py)
|
||||||
by expect
|
by expect
|
||||||
|
|
||||||
|
[TensorFlow integration](https://github.com/WhatDidYouExpect/goober/blob/main/cogs/tf.py)
|
||||||
|
by SuperSilly2 (requires Python 3.7 - 3.10, tensorflow-metal/tensorflow-gpu and tensorflow/tensorflow-macos)
|
||||||
|
|
||||||
[Web Scraper](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/webscraper.py)
|
[Web Scraper](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/webscraper.py)
|
||||||
by expect (requires goober version 0.11.7.2 or higher)
|
by expect (requires goober version 0.11.7.2 or higher)
|
||||||
|
|
||||||
|
@ -19,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)
|
[webUI](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/webserver.py)
|
||||||
by expect (requires goober version 0.11.8 or higher)
|
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
|
|
|
@ -1,8 +1,7 @@
|
||||||
import discord
|
import discord
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
from modules.globalvars import ownerid
|
import os
|
||||||
|
from config import ownerid
|
||||||
COG_PREFIX = "assets.cogs."
|
|
||||||
|
|
||||||
class CogManager(commands.Cog):
|
class CogManager(commands.Cog):
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
|
@ -17,7 +16,7 @@ class CogManager(commands.Cog):
|
||||||
await ctx.send("Please provide the cog name to load.")
|
await ctx.send("Please provide the cog name to load.")
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
await self.bot.load_extension(COG_PREFIX + cog_name)
|
await self.bot.load_extension(f"cogs.{cog_name}")
|
||||||
await ctx.send(f"Loaded cog `{cog_name}` successfully.")
|
await ctx.send(f"Loaded cog `{cog_name}` successfully.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await ctx.send(f"Error loading cog `{cog_name}`: {e}")
|
await ctx.send(f"Error loading cog `{cog_name}`: {e}")
|
||||||
|
@ -31,7 +30,7 @@ class CogManager(commands.Cog):
|
||||||
await ctx.send("Please provide the cog name to unload.")
|
await ctx.send("Please provide the cog name to unload.")
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
await self.bot.unload_extension(COG_PREFIX + cog_name)
|
await self.bot.unload_extension(f"cogs.{cog_name}")
|
||||||
await ctx.send(f"Unloaded cog `{cog_name}` successfully.")
|
await ctx.send(f"Unloaded cog `{cog_name}` successfully.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await ctx.send(f"Error unloading cog `{cog_name}`: {e}")
|
await ctx.send(f"Error unloading cog `{cog_name}`: {e}")
|
||||||
|
@ -45,8 +44,8 @@ class CogManager(commands.Cog):
|
||||||
await ctx.send("Please provide the cog name to reload.")
|
await ctx.send("Please provide the cog name to reload.")
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
await self.bot.unload_extension(COG_PREFIX + cog_name)
|
await self.bot.unload_extension(f"cogs.{cog_name}")
|
||||||
await self.bot.load_extension(COG_PREFIX + cog_name)
|
await self.bot.load_extension(f"cogs.{cog_name}")
|
||||||
await ctx.send(f"Reloaded cog `{cog_name}` successfully.")
|
await ctx.send(f"Reloaded cog `{cog_name}` successfully.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
await ctx.send(f"Error reloading cog `{cog_name}`: {e}")
|
await ctx.send(f"Error reloading cog `{cog_name}`: {e}")
|
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))
|
|
@ -1,6 +1,6 @@
|
||||||
import discord
|
import discord
|
||||||
from discord.ext import commands
|
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
|
import os
|
||||||
|
|
||||||
class songchange(commands.Cog):
|
class songchange(commands.Cog):
|
155
cogs/tf.py.disabled
Normal file
|
@ -0,0 +1,155 @@
|
||||||
|
import discord
|
||||||
|
from discord.ext import commands
|
||||||
|
import os
|
||||||
|
import numpy as np
|
||||||
|
import json
|
||||||
|
import pickle
|
||||||
|
import functools
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
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
|
||||||
|
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'):
|
||||||
|
print("Using Metal for macOS acceleration")
|
||||||
|
except ImportError:
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class TFCallback(keras.callbacks.Callback):
|
||||||
|
def __init__(self, bot, progress_embed: discord.Embed, message):
|
||||||
|
self.embed = progress_embed
|
||||||
|
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)
|
||||||
|
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."))
|
||||||
|
|
||||||
|
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))
|
||||||
|
|
||||||
|
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)}"))
|
||||||
|
|
||||||
|
|
||||||
|
class Ai:
|
||||||
|
def __init__(self):
|
||||||
|
model_path = settings.get("model_path")
|
||||||
|
if model_path:
|
||||||
|
self.__load_model(model_path)
|
||||||
|
self.is_loaded = model_path is not None
|
||||||
|
self.batch_size = 64
|
||||||
|
|
||||||
|
def generate_model_name(self):
|
||||||
|
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"))
|
||||||
|
model_name = os.path.basename(model_path)
|
||||||
|
try:
|
||||||
|
with open(os.path.join(model_path, "tokenizer.pkl"), "rb") as f:
|
||||||
|
self.tokenizer = pickle.load(f)
|
||||||
|
except FileNotFoundError:
|
||||||
|
print("Failed to load tokenizer, using default.")
|
||||||
|
self.tokenizer = Tokenizer()
|
||||||
|
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")
|
||||||
|
if model_path:
|
||||||
|
self.__load_model(model_path)
|
||||||
|
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))
|
||||||
|
|
||||||
|
|
||||||
|
class Learning(Ai):
|
||||||
|
def create_model(self, memory, epochs=2):
|
||||||
|
memory = memory[:2000]
|
||||||
|
tokenizer = Tokenizer()
|
||||||
|
tokenizer.fit_on_texts(memory)
|
||||||
|
sequences = tokenizer.texts_to_sequences(memory)
|
||||||
|
X, y = [], []
|
||||||
|
for seq in sequences:
|
||||||
|
for i in range(1, len(seq)):
|
||||||
|
X.append(seq[:i])
|
||||||
|
y.append(seq[i])
|
||||||
|
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"])
|
||||||
|
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), "")
|
||||||
|
seed += " " + output_word
|
||||||
|
return seed
|
||||||
|
|
||||||
|
|
||||||
|
VOCAB_SIZE = 100_000
|
||||||
|
settings = {}
|
||||||
|
learning = Learning()
|
||||||
|
generation = Generation()
|
||||||
|
|
||||||
|
tf_callback = None
|
||||||
|
|
||||||
|
|
||||||
|
async def setup(bot):
|
||||||
|
await bot.add_cog(Tf(bot))
|
|
@ -5,7 +5,7 @@ from bs4 import BeautifulSoup
|
||||||
import json
|
import json
|
||||||
import asyncio
|
import asyncio
|
||||||
from urllib.parse import urljoin
|
from urllib.parse import urljoin
|
||||||
from modules.globalvars import ownerid
|
from config import ownerid
|
||||||
class WebScraper(commands.Cog):
|
class WebScraper(commands.Cog):
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
|
@ -10,7 +10,7 @@ import time
|
||||||
import aiohttp
|
import aiohttp
|
||||||
import re
|
import re
|
||||||
from aiohttp import WSMsgType
|
from aiohttp import WSMsgType
|
||||||
from modules.globalvars import VERSION_URL
|
from config import VERSION_URL
|
||||||
import sys
|
import sys
|
||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
|
@ -60,7 +60,7 @@ class GooberWeb(commands.Cog):
|
||||||
try:
|
try:
|
||||||
user = await self.bot.fetch_user(int(user_id))
|
user = await self.bot.fetch_user(int(user_id))
|
||||||
blacklisted_users.append({
|
blacklisted_users.append({
|
||||||
"name": f"{user.name}",
|
"name": f"{user.name}#{user.discriminator}",
|
||||||
"avatar_url": str(user.avatar.url) if user.avatar else str(user.default_avatar.url),
|
"avatar_url": str(user.avatar.url) if user.avatar else str(user.default_avatar.url),
|
||||||
"id": user.id
|
"id": user.id
|
||||||
})
|
})
|
||||||
|
@ -158,7 +158,7 @@ class GooberWeb(commands.Cog):
|
||||||
self._update_command_stats(command.name, interaction.user)
|
self._update_command_stats(command.name, interaction.user)
|
||||||
|
|
||||||
def _update_command_stats(self, command_name, 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")
|
self.last_command_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||||
if self.websockets:
|
if self.websockets:
|
||||||
asyncio.create_task(self.update_clients())
|
asyncio.create_task(self.update_clients())
|
||||||
|
@ -380,7 +380,7 @@ class GooberWeb(commands.Cog):
|
||||||
if owner_id:
|
if owner_id:
|
||||||
try:
|
try:
|
||||||
owner = await self.bot.fetch_user(int(owner_id))
|
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 ""
|
owner_pfp = str(owner.avatar.url) if owner and owner.avatar else ""
|
||||||
except:
|
except:
|
||||||
pass
|
pass
|
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"
|
56
example.env
|
@ -1,29 +1,29 @@
|
||||||
DISCORDBOTTOKEN=
|
DISCORD_BOT_TOKEN=token
|
||||||
BOTPREFIX="g."
|
BOT_PREFIX="g."
|
||||||
PINGLINE="The Beretta fires fast and won't make you feel any better!"
|
PING_LINE="The Beretta fires fast and won't make you feel any better!"
|
||||||
BLACKLISTEDUSERS=
|
BLACKLISTED_USERS=
|
||||||
OWNERID=
|
rnd_talk_channel1=1319593363997589614
|
||||||
USERTRAINENABLED="true"
|
rnd_talk_channel2=1318263176134918246
|
||||||
SHOWMEMENABLED="true"
|
cooldown=10800
|
||||||
LOCALE=fi
|
hourlyspeak=1318263176134918246
|
||||||
NAME=goober
|
ownerid=542701119948849163
|
||||||
AUTOUPDATE="True"
|
USERTRAIN_ENABLED="true"
|
||||||
SONG="Basket Case - Green Day"
|
showmemenabled="true"
|
||||||
CHECKSDISABLED="Frue"
|
NAME="an instance of goober"
|
||||||
REACT="True"
|
locale=fi
|
||||||
STATUS="idle"
|
ALIVEPING="true"
|
||||||
POSITIVEGIFS="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"
|
gooberTOKEN=
|
||||||
SPLASHTEXT="
|
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"
|
||||||
SS\
|
splashtext="
|
||||||
SS |
|
d8b
|
||||||
SSSSSS\ SSSSSS\ SSSSSS\ SSSSSSS\ SSSSSS\ SSSSSS\
|
?88
|
||||||
SS __SS\ SS __SS\ SS __SS\ SS __SS\ SS __SS\ SS __SS\
|
88b
|
||||||
SS / SS |SS / SS |SS / SS |SS | SS |SSSSSSSS |SS | \__|
|
d888b8b d8888b d8888b 888888b d8888b 88bd88b
|
||||||
SS | SS |SS | SS |SS | SS |SS | SS |SS ____|SS |
|
d8P' ?88 d8P' ?88d8P' ?88 88P `?8bd8b_,dP 88P' `
|
||||||
\SSSSSSS |\SSSSSS |\SSSSSS |SSSSSSS |\SSSSSSS\ SS |
|
88b ,88b 88b d8888b d88 d88, d8888b d88
|
||||||
\____SS | \______/ \______/ \_______/ \_______|\__|
|
`?88P'`88b`?8888P'`?8888P'd88'`?88P'`?888P'd88'
|
||||||
SS\ SS |
|
)88
|
||||||
\SSSSSS |
|
,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_commands": "Sincronizado",
|
||||||
"synced_commands2": "comandos!",
|
"synced_commands2": "comandos!",
|
||||||
"fail_commands_sync": "Error al sincronizar 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_check": "Error al comprobar la disponibilidad del nombre:",
|
||||||
"name_taken": "El nombre ya está en uso. Elija otro.",
|
"name_taken": "El nombre ya está en uso. Elija otro.",
|
||||||
"name_check2": "Error durante la comprobacion de disponibilidad del nombre:",
|
"name_check2": "Error durante la comprobacion de disponibilidad del nombre:",
|
||||||
|
@ -73,5 +73,5 @@
|
||||||
"command_stats_embed_field2name": "Version",
|
"command_stats_embed_field2name": "Version",
|
||||||
"command_stats_embed_field2value": "Version local: {local_version} \nUltima version: {latest_version}",
|
"command_stats_embed_field2value": "Version local: {local_version} \nUltima version: {latest_version}",
|
||||||
"command_stats_embed_field3name": "informacion sobre las variables",
|
"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,61 +1,4 @@
|
||||||
{
|
{
|
||||||
"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...",
|
"modification_warning": "Gooberia on muokattu! Ohitetaan palvelimen tarkistus kokonaan...",
|
||||||
"reported_version": "Ilmoitettu versio:",
|
"reported_version": "Ilmoitettu versio:",
|
||||||
"current_hash": "Tämänhetkinen hash:",
|
"current_hash": "Tämänhetkinen hash:",
|
||||||
|
@ -70,7 +13,7 @@
|
||||||
"synced_commands": "Synkronoitiin",
|
"synced_commands": "Synkronoitiin",
|
||||||
"synced_commands2": "komennot!",
|
"synced_commands2": "komennot!",
|
||||||
"fail_commands_sync": "Komentojen synkronointi epäonnistui:",
|
"fail_commands_sync": "Komentojen synkronointi epäonnistui:",
|
||||||
"started": "{name} on käynnistynyt!\nOlet nyt sarjan tähti, beibi!",
|
"started": "Goober on käynnistynyt!",
|
||||||
"name_check": "Nimen saatavuuden tarkistus epäonnistui:",
|
"name_check": "Nimen saatavuuden tarkistus epäonnistui:",
|
||||||
"name_taken": "Nimi on jo käytössä. Valitse toinen nimi.",
|
"name_taken": "Nimi on jo käytössä. Valitse toinen nimi.",
|
||||||
"name_check2": "Virhe tapahtui nimen saatavuuden tarkistamisessa:",
|
"name_check2": "Virhe tapahtui nimen saatavuuden tarkistamisessa:",
|
||||||
|
@ -130,6 +73,6 @@
|
||||||
"command_stats_embed_field2name": "Versio",
|
"command_stats_embed_field2name": "Versio",
|
||||||
"command_stats_embed_field2value": "Paikallinen: {local_version} \nUusin: {latest_version}",
|
"command_stats_embed_field2value": "Paikallinen: {local_version} \nUusin: {latest_version}",
|
||||||
"command_stats_embed_field3name": "Muuttajainformaatio",
|
"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}```"
|
"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}```"
|
||||||
}
|
}
|
||||||
|
|
78
locales/it.json
Normal file
|
@ -0,0 +1,78 @@
|
||||||
|
{
|
||||||
|
"modification_warning": "Goober è stato modificato! Verifiche del server saltate completamente...",
|
||||||
|
"reported_version": "Versione segnalata:",
|
||||||
|
"current_hash": "Hash attuale:",
|
||||||
|
"not_found": "non trovato!",
|
||||||
|
"version_error": "Impossibile recuperare le informazioni sulla versione. Codice di stato",
|
||||||
|
"loaded_cog": "Cog caricato:",
|
||||||
|
"cog_fail": "Impossibile caricare il cog:",
|
||||||
|
"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...",
|
||||||
|
"logged_in": "Accesso effettuato come",
|
||||||
|
"synced_commands": "Sincronizzati",
|
||||||
|
"synced_commands2": "comandi!",
|
||||||
|
"fail_commands_sync": "Impossibile sincronizzare i comandi:",
|
||||||
|
"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.",
|
||||||
|
"registration_error": "Errore durante la registrazione:",
|
||||||
|
"version_backup": "Backup creato:",
|
||||||
|
"backup_error": "Errore: {LOCAL_VERSION_FILE} non trovato per il backup.",
|
||||||
|
"model_loaded": "Modello Markov caricato da",
|
||||||
|
"fetch_update_fail": "Impossibile recuperare le informazioni sull'aggiornamento.",
|
||||||
|
"invalid_server": "Errore: informazioni sulla versione non valide ricevute dal server.",
|
||||||
|
"new_version": "Nuova versione disponibile: {latest_version} (Attuale: {local_version})",
|
||||||
|
"changelog": "Controlla {VERSION_URL}/goob/changes.txt per vedere il changelog\n\n",
|
||||||
|
"invalid_version": "La versione: {local_version} non è valida!",
|
||||||
|
"invalid_version2": "Se è intenzionale ignora questo messaggio, altrimenti premi Y per scaricare una versione valida dal server indipendentemente dalla versione attuale di goober",
|
||||||
|
"invalid_version3": "La versione attuale sarà salvata come current_version.bak..",
|
||||||
|
"input": "(Y o qualsiasi altro tasto per ignorare....)",
|
||||||
|
"modification_ignored": "Hai modificato",
|
||||||
|
"modification_ignored2": "IGNOREWARNING è impostato su false..",
|
||||||
|
"latest_version": "Stai utilizzando l'ultima versione:",
|
||||||
|
"latest_version2": "Controlla {VERSION_URL}/goob/changes.txt per vedere il changelog",
|
||||||
|
"pinging_disabled": "Il ping è disabilitato! Non dico al server che sono online...",
|
||||||
|
"goober_ping_success": "Accesso a goober central come {NAME}",
|
||||||
|
"goober_ping_fail": "Impossibile inviare i dati. Il server ha restituito il codice di stato:",
|
||||||
|
"goober_ping_fail2": "Si è verificato un errore durante l'invio dei dati:",
|
||||||
|
"sentence_positivity": "La positività della frase è:",
|
||||||
|
"command_edit_fail": "Impossibile modificare il messaggio:",
|
||||||
|
"command_desc_retrain": "Rafforza manualmente il modello Markov.",
|
||||||
|
"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 {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.",
|
||||||
|
"command_talk_generation_fail": "Non ho nulla da dire in questo momento!",
|
||||||
|
"command_desc_help": "aiuto",
|
||||||
|
"command_help_embed_title": "Aiuto Bot",
|
||||||
|
"command_help_embed_desc": "Elenco dei comandi raggruppati per categoria.",
|
||||||
|
"command_help_categories_general": "Generale",
|
||||||
|
"command_help_categories_admin": "Amministrazione",
|
||||||
|
"command_help_categories_custom": "Comandi personalizzati",
|
||||||
|
"command_ran": "Info: {message.author.name} ha eseguito {message.content}",
|
||||||
|
"command_desc_ping": "ping",
|
||||||
|
"command_ping_embed_desc": "Latenza del bot:",
|
||||||
|
"command_ping_footer": "Richiesto da",
|
||||||
|
"command_about_desc": "informazioni",
|
||||||
|
"command_about_embed_title": "Informazioni su di me",
|
||||||
|
"command_about_embed_field1": "Nome",
|
||||||
|
"command_about_embed_field2name": "Versione",
|
||||||
|
"command_about_embed_field2value": "Locale: {local_version} \nUltima: {latest_version}",
|
||||||
|
"command_desc_stats": "statistiche",
|
||||||
|
"command_stats_embed_title": "Statistiche del bot",
|
||||||
|
"command_stats_embed_desc": "Dati sulla memoria del bot.",
|
||||||
|
"command_stats_embed_field1name": "Statistiche del file",
|
||||||
|
"command_stats_embed_field1value": "Dimensione: {file_size} byte\nLinee: {line_count}",
|
||||||
|
"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} \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,72 +0,0 @@
|
||||||
import os
|
|
||||||
import platform
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
import pathlib
|
|
||||||
import discord
|
|
||||||
from discord.ext import commands
|
|
||||||
from discord import app_commands
|
|
||||||
from discord import Colour, Embed, File, Interaction, Message
|
|
||||||
from discord.abc import Messageable
|
|
||||||
from discord.ext import commands
|
|
||||||
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)
|
|
||||||
ANSI = "\033["
|
|
||||||
RED = f"{ANSI}31m"
|
|
||||||
GREEN = f"{ANSI}32m"
|
|
||||||
YELLOW = f"{ANSI}33m"
|
|
||||||
PURPLE = f"{ANSI}35m"
|
|
||||||
DEBUG = f"{ANSI}1;30m"
|
|
||||||
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")
|
|
||||||
gooberTOKEN = os.getenv("GOOBERTOKEN")
|
|
||||||
splashtext = os.getenv("SPLASHTEXT")
|
|
||||||
ownerid = int(os.getenv("OWNERID", "0"))
|
|
||||||
status = os.getenv("STATUS")
|
|
||||||
showmemenabled = os.getenv("SHOWMEMENABLED")
|
|
||||||
BLACKLISTED_USERS = os.getenv("BLACKLISTEDUSERS", "").split(",")
|
|
||||||
USERTRAIN_ENABLED = os.getenv("USERTRAINENABLED", "true").lower() == "true"
|
|
||||||
NAME = os.getenv("NAME")
|
|
||||||
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")
|
|
||||||
song = os.getenv("SONG")
|
|
||||||
arch = platform.machine()
|
|
||||||
launched = False
|
|
||||||
latest_version = "0.0.0"
|
|
||||||
local_version = "2.3.5"
|
|
||||||
os.environ['gooberlocal_version'] = local_version
|
|
||||||
REACT = os.getenv("REACT")
|
|
||||||
if get_git_branch() == "dev":
|
|
||||||
beta = True
|
|
||||||
# this makes goober think its a beta version, so it will not update to the latest stable version or run any version checks
|
|
||||||
else:
|
|
||||||
beta = False
|
|
||||||
|
|
||||||
|
|
||||||
# Set up Discord bot intents and create bot instance
|
|
||||||
intents: discord.Intents = discord.Intents.default()
|
|
||||||
intents.messages = True
|
|
||||||
intents.presences = True
|
|
||||||
intents.members = True
|
|
||||||
intents.message_content = True
|
|
||||||
bot: commands.Bot = commands.Bot(command_prefix=PREFIX, intents=intents, allowed_mentions=discord.AllowedMentions(everyone=False, roles=False, users=False, replied_user=True))
|
|
177
modules/image.py
|
@ -1,177 +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, custom_text=None):
|
|
||||||
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
|
|
||||||
if custom_text:
|
|
||||||
response = custom_text
|
|
||||||
else:
|
|
||||||
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,30 +0,0 @@
|
||||||
import logging
|
|
||||||
import re
|
|
||||||
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):
|
|
||||||
ansiescape = re.compile(r'\x1B[@-_][0-?]*[ -/]*[@-~]')
|
|
||||||
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")
|
|
||||||
formatted = formatter.format(record)
|
|
||||||
if not self.colors:
|
|
||||||
formatted = ansiescape.sub('', formatted)
|
|
||||||
return formatted
|
|
|
@ -1,64 +0,0 @@
|
||||||
import os
|
|
||||||
import json
|
|
||||||
import markovify
|
|
||||||
import pickle
|
|
||||||
from modules.globalvars import *
|
|
||||||
from modules.volta.main import _
|
|
||||||
import logging
|
|
||||||
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(MEMORY_FILE, "r") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
except FileNotFoundError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
return data
|
|
||||||
|
|
||||||
# Save memory data to MEMORY_FILE
|
|
||||||
def save_memory(memory):
|
|
||||||
with open(MEMORY_FILE, "w") as f:
|
|
||||||
json.dump(memory, f, indent=4)
|
|
||||||
|
|
||||||
def train_markov_model(memory, additional_data=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"{_('model_loaded')} {filename}.{RESET}")
|
|
||||||
return model
|
|
||||||
except FileNotFoundError:
|
|
||||||
logger.error(f"{filename} {_('not_found')}{RESET}")
|
|
||||||
return None
|
|
|
@ -1,71 +0,0 @@
|
||||||
import random
|
|
||||||
import discord
|
|
||||||
from discord import ui, Interaction, TextStyle
|
|
||||||
from discord.ext import commands
|
|
||||||
import aiohttp
|
|
||||||
import asyncio
|
|
||||||
from modules.globalvars import bot
|
|
||||||
from modules.volta.main import _
|
|
||||||
|
|
||||||
# @bot.hybrid_command(description=_('minigames_guess_the_number'))
|
|
||||||
async def guessthenumber(ctx: commands.Context):
|
|
||||||
number = random.randint(1, 10)
|
|
||||||
class GuessModal(ui.Modal, title=_('minigames_guess_the_number')):
|
|
||||||
guess = ui.TextInput(label=_('minigames_your_guess'), style=TextStyle.short)
|
|
||||||
async def on_submit(self, interaction: Interaction):
|
|
||||||
try:
|
|
||||||
user_guess = int(self.guess.value)
|
|
||||||
except:
|
|
||||||
await interaction.response.send_message(_('minigames_invalid_number'), ephemeral=True)
|
|
||||||
return
|
|
||||||
if user_guess == number:
|
|
||||||
await interaction.response.send_message(_('minigames_correct'), ephemeral=True)
|
|
||||||
else:
|
|
||||||
await interaction.response.send_message(f"{_('minigames_wrong_number')} {number}.", ephemeral=True)
|
|
||||||
async def button_callback(interaction: Interaction):
|
|
||||||
await interaction.response.send_modal(GuessModal())
|
|
||||||
button = ui.Button(label=_('minigames_guess_button'), style=discord.ButtonStyle.primary)
|
|
||||||
button.callback = button_callback
|
|
||||||
view = ui.View()
|
|
||||||
view.add_item(button)
|
|
||||||
await ctx.send(_('minigames_click_to_guess'), view=view)
|
|
||||||
|
|
||||||
# @bot.hybrid_command(description=_('minigames_hangman')) nope nope nope fuck no nope no thanks no nuh uh not today nope
|
|
||||||
async def hangman(ctx: commands.Context):
|
|
||||||
async with aiohttp.ClientSession() as session:
|
|
||||||
async with session.get("https://random-word-api.herokuapp.com/word?number=1") as resp:
|
|
||||||
if resp.status != 200:
|
|
||||||
await ctx.send("Failed to get a random word.")
|
|
||||||
return
|
|
||||||
data = await resp.json()
|
|
||||||
word = data[0].lower()
|
|
||||||
print(word)
|
|
||||||
guessed_letters = set()
|
|
||||||
wrong_guesses = 0
|
|
||||||
max_wrong = 6
|
|
||||||
def display_word():
|
|
||||||
return " ".join([c if c in guessed_letters else "_" for c in word])
|
|
||||||
class GuessModal(ui.Modal, title=_('minigames_hangman_guess')):
|
|
||||||
letter = ui.TextInput(label=_('minigames_hangman_user_letter_guess'), style=TextStyle.short, max_length=1)
|
|
||||||
async def on_submit(self, interaction: Interaction):
|
|
||||||
nonlocal guessed_letters, wrong_guesses
|
|
||||||
guess = self.letter.value.lower()
|
|
||||||
if guess in guessed_letters:
|
|
||||||
await interaction.response.send_message(f"{_('minigames_hangman_already_guessed')}'{guess}'!", ephemeral=True)
|
|
||||||
return
|
|
||||||
guessed_letters.add(guess)
|
|
||||||
if guess not in word:
|
|
||||||
wrong_guesses += 1
|
|
||||||
if all(c in guessed_letters for c in word):
|
|
||||||
await interaction.response.edit_message(content=f"{_('minigames_hangman_won')} **{word}**", view=None)
|
|
||||||
elif wrong_guesses >= max_wrong:
|
|
||||||
await interaction.response.edit_message(content=f"{_('minigames_hangman_lost')} **{word}**", view=None)
|
|
||||||
else:
|
|
||||||
await interaction.response.edit_message(content=_('minigames_hangman_game').format(display_word=display_word(),wrong_guesses=wrong_guesses,max_wrong=max_wrong), view=view)
|
|
||||||
async def button_callback(interaction: Interaction):
|
|
||||||
await interaction.response.send_modal(GuessModal())
|
|
||||||
button = ui.Button(label=_('minigames_click_to_guess'), style=discord.ButtonStyle.primary)
|
|
||||||
button.callback = button_callback
|
|
||||||
view = ui.View()
|
|
||||||
view.add_item(button)
|
|
||||||
await ctx.send(_('minigames_hangman_game').format(display_word=display_word,wrong_guesses=wrong_guesses,max_wrong=max_wrong), view=view)
|
|
|
@ -1,255 +0,0 @@
|
||||||
from modules.globalvars import *
|
|
||||||
from modules.volta.main import _, check_missing_translations
|
|
||||||
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
|
|
||||||
|
|
||||||
logger = logging.getLogger("goober")
|
|
||||||
|
|
||||||
# import shutil
|
|
||||||
psutilavaliable = True
|
|
||||||
try:
|
|
||||||
import requests
|
|
||||||
import psutil
|
|
||||||
except ImportError:
|
|
||||||
psutilavaliable = False
|
|
||||||
logger.error(_('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"{_('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"
|
|
||||||
}
|
|
||||||
|
|
||||||
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"{(_('requirements_not_found')).format(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((_('std_lib_local_skipped')).format(package=req))
|
|
||||||
continue
|
|
||||||
|
|
||||||
check_name = req.lower()
|
|
||||||
|
|
||||||
if check_name in installed_packages:
|
|
||||||
logger.info(f"{_('ok_installed').format(package=check_name)} {check_name}")
|
|
||||||
else:
|
|
||||||
logger.error(f"{(_('missing_package')).format(package=check_name)} {check_name} {(_('missing_package2'))}")
|
|
||||||
missing.append(check_name)
|
|
||||||
|
|
||||||
if missing:
|
|
||||||
logger.error(_('missing_packages_detected'))
|
|
||||||
for pkg in missing:
|
|
||||||
print(f" - {pkg}")
|
|
||||||
sys.exit(1)
|
|
||||||
else:
|
|
||||||
logger.info(_('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((_('ping_to')).format(host=host, latency=latency_ms))
|
|
||||||
if latency_ms > 300:
|
|
||||||
logger.warning(f"{(_('high_latency'))}")
|
|
||||||
else:
|
|
||||||
logger.warning((_('could_not_parse_latency')))
|
|
||||||
else:
|
|
||||||
print(result.stderr)
|
|
||||||
logger.error(f"{(_('ping_failed')).format(host=host)}{RESET}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error((_('error_running_ping')).format(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((_('memory_usage')).format(used=used_memory, total=total_memory, percent=(used_memory / total_memory) * 100))
|
|
||||||
if used_memory > total_memory * 0.9:
|
|
||||||
print(f"{YELLOW}{(_('memory_above_90')).format(percent=(used_memory / total_memory) * 100)}{RESET}")
|
|
||||||
logger.info((_('total_memory')).format(total=total_memory))
|
|
||||||
logger.info((_('used_memory')).format(used=used_memory))
|
|
||||||
if free_memory < 1:
|
|
||||||
logger.warning(f"{(_('low_free_memory')).format(free=free_memory)}")
|
|
||||||
sys.exit(1)
|
|
||||||
except ImportError:
|
|
||||||
logger.error(_('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((_('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((_('total_cpu_usage')).format(usage=total_cpu))
|
|
||||||
if total_cpu > 85:
|
|
||||||
logger.warning(f"{(_('high_avg_cpu')).format(usage=total_cpu)}")
|
|
||||||
if total_cpu > 95:
|
|
||||||
logger.error(_('really_high_cpu'))
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
def check_memoryjson():
|
|
||||||
try:
|
|
||||||
logger.info((_('memory_file')).format(size=os.path.getsize(MEMORY_FILE) / (1024 ** 2)))
|
|
||||||
if os.path.getsize(MEMORY_FILE) > 1_073_741_824:
|
|
||||||
logger.warning(f"{(_('memory_file_large'))}")
|
|
||||||
try:
|
|
||||||
with open(MEMORY_FILE, 'r', encoding='utf-8') as f:
|
|
||||||
json.load(f)
|
|
||||||
except json.JSONDecodeError as e:
|
|
||||||
logger.error(f"{(_('memory_file_corrupted')).format(error=e)}")
|
|
||||||
logger.warning(f"{(_('consider_backup_memory'))}")
|
|
||||||
except UnicodeDecodeError as e:
|
|
||||||
logger.error(f"{(_('memory_file_encoding')).format(error=e)}")
|
|
||||||
logger.warning(f"{(_('consider_backup_memory'))}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"{(_('error_reading_memory')).format(error=e)}")
|
|
||||||
except FileNotFoundError:
|
|
||||||
logger(f"{(_('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)
|
|
||||||
beta = beta
|
|
||||||
def start_checks():
|
|
||||||
if CHECKS_DISABLED == "True":
|
|
||||||
logger.warning(f"{(_('checks_disabled'))}")
|
|
||||||
return
|
|
||||||
logger.info(_('running_prestart_checks'))
|
|
||||||
check_for_model()
|
|
||||||
iscloned()
|
|
||||||
check_missing_translations()
|
|
||||||
check_requirements()
|
|
||||||
check_latency()
|
|
||||||
check_memory()
|
|
||||||
check_memoryjson()
|
|
||||||
check_cpu()
|
|
||||||
if os.path.exists(".env"):
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
logger.warning(f"{(_('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(_('continuing_in_seconds').format(seconds=5))
|
|
||||||
presskey2skip(timeout=5)
|
|
||||||
os.system('cls' if os.name == 'nt' else 'clear')
|
|
||||||
print(splashtext)
|
|
|
@ -1,75 +0,0 @@
|
||||||
import re
|
|
||||||
from modules.globalvars import *
|
|
||||||
from modules.volta.main import _
|
|
||||||
|
|
||||||
import spacy
|
|
||||||
from spacy.tokens import Doc
|
|
||||||
from spacytextblob.spacytextblob import SpacyTextBlob
|
|
||||||
|
|
||||||
import logging
|
|
||||||
logger = logging.getLogger("goober")
|
|
||||||
|
|
||||||
|
|
||||||
def check_resources():
|
|
||||||
try:
|
|
||||||
nlp = spacy.load("en_core_web_sm")
|
|
||||||
except OSError:
|
|
||||||
logging.critical((_('spacy_model_not_found')))
|
|
||||||
spacy.cli.download("en_core_web_sm")
|
|
||||||
nlp = spacy.load("en_core_web_sm")
|
|
||||||
if "spacytextblob" not in nlp.pipe_names:
|
|
||||||
nlp.add_pipe("spacytextblob")
|
|
||||||
logger.info((_('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"{(_('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, message=None, embed=None, file=None, edit=False, message_reference=None):
|
|
||||||
if edit and message_reference:
|
|
||||||
try:
|
|
||||||
await message_reference.edit(content=message, embed=embed)
|
|
||||||
except Exception as e:
|
|
||||||
await ctx.send(f"{RED}{(_('edit_fail'))} {e}{RESET}")
|
|
||||||
else:
|
|
||||||
if hasattr(ctx, "respond"):
|
|
||||||
sent_message = None
|
|
||||||
if embed:
|
|
||||||
sent_message = await ctx.respond(embed=embed, ephemeral=False)
|
|
||||||
elif message:
|
|
||||||
sent_message = await ctx.respond(message, ephemeral=False)
|
|
||||||
if file:
|
|
||||||
sent_message = await ctx.respond(file=file, ephemeral=False)
|
|
||||||
else:
|
|
||||||
sent_message = None
|
|
||||||
if embed:
|
|
||||||
sent_message = await ctx.send(embed=embed)
|
|
||||||
elif message:
|
|
||||||
sent_message = await ctx.send(message)
|
|
||||||
if file:
|
|
||||||
sent_message = await ctx.send(file=file)
|
|
||||||
return sent_message
|
|
||||||
|
|
||||||
def preprocess_message(message):
|
|
||||||
message = 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 ""
|
|
||||||
|
|
||||||
def rephrase_for_coherence(sentence):
|
|
||||||
coherent_sentence = sentence
|
|
||||||
return coherent_sentence
|
|
|
@ -1,25 +0,0 @@
|
||||||
import sys
|
|
||||||
import traceback
|
|
||||||
import os
|
|
||||||
from modules.globalvars import RED, RESET, splashtext
|
|
||||||
from modules.volta.main import _
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
print(splashtext)
|
|
||||||
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}{_('unhandled_exception')}{RESET}")
|
|
||||||
|
|
||||||
|
|
||||||
if context:
|
|
||||||
print(f"{RED}Context: {context}{RESET}")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -1,105 +0,0 @@
|
||||||
from modules.volta.main import _
|
|
||||||
from modules.globalvars import *
|
|
||||||
import requests
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import logging
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
import random
|
|
||||||
logger = logging.getLogger("goober")
|
|
||||||
launched = False
|
|
||||||
|
|
||||||
# Run a shell command and return its output
|
|
||||||
def run_cmd(cmd):
|
|
||||||
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
|
|
||||||
return result.stdout.strip()
|
|
||||||
|
|
||||||
# Check if the remote branch is ahead of the local branch
|
|
||||||
def is_remote_ahead(branch='main', remote='origin'):
|
|
||||||
run_cmd(f'git fetch {remote}')
|
|
||||||
count = run_cmd(f'git rev-list --count HEAD..{remote}/{branch}')
|
|
||||||
return int(count) > 0
|
|
||||||
|
|
||||||
# Automatically update the local repository if the remote is ahead
|
|
||||||
def auto_update(branch='main', remote='origin'):
|
|
||||||
if launched == True:
|
|
||||||
print(_("already_started"))
|
|
||||||
return
|
|
||||||
if AUTOUPDATE != "True":
|
|
||||||
pass # Auto-update is disabled
|
|
||||||
if is_remote_ahead(branch, remote):
|
|
||||||
print(_( "remote_ahead").format(remote=remote, branch=branch))
|
|
||||||
pull_result = run_cmd(f'git pull {remote} {branch}')
|
|
||||||
logger.info(pull_result)
|
|
||||||
logger.info(_( "please_restart"))
|
|
||||||
sys.exit(0)
|
|
||||||
else:
|
|
||||||
logger.info(_( "local_ahead").format(remote=remote, branch=branch))
|
|
||||||
|
|
||||||
def get_latest_version_info():
|
|
||||||
try:
|
|
||||||
unique_suffix = f"{int(time.time())}_{random.randint(0, 9999)}"
|
|
||||||
url = f"{UPDATE_URL}?_={unique_suffix}"
|
|
||||||
|
|
||||||
curl_cmd = [
|
|
||||||
"curl",
|
|
||||||
"-s",
|
|
||||||
"-H", "Cache-Control: no-cache",
|
|
||||||
"-H", "Pragma: no-cache",
|
|
||||||
url
|
|
||||||
]
|
|
||||||
|
|
||||||
result = subprocess.run(curl_cmd, capture_output=True, text=True, timeout=5)
|
|
||||||
content = result.stdout
|
|
||||||
|
|
||||||
if result.returncode != 0:
|
|
||||||
logger.error(f"curl failed with return code {result.returncode}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
try:
|
|
||||||
data = json.loads(content)
|
|
||||||
return data
|
|
||||||
except json.JSONDecodeError:
|
|
||||||
logger.error("JSON decode failed")
|
|
||||||
logger.error(content[:500])
|
|
||||||
return None
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Exception in get_latest_version_info: {e}")
|
|
||||||
return None
|
|
||||||
|
|
||||||
# Check if an update is available and perform update if needed
|
|
||||||
def check_for_update():
|
|
||||||
global latest_version, local_version, launched
|
|
||||||
|
|
||||||
latest_version_info = get_latest_version_info()
|
|
||||||
if not latest_version_info:
|
|
||||||
logger.error(f"{_('fetch_update_fail')}")
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
latest_version = latest_version_info.get("version")
|
|
||||||
os.environ['gooberlatest_version'] = latest_version
|
|
||||||
download_url = latest_version_info.get("download_url")
|
|
||||||
|
|
||||||
if not latest_version or not download_url:
|
|
||||||
logger.error(f"{RED}{_('invalid_server')}{RESET}")
|
|
||||||
return None, None
|
|
||||||
# Check if local_version is valid
|
|
||||||
if local_version == "0.0.0" or None:
|
|
||||||
logger.error(f"{RED}{_('cant_find_local_version')}{RESET}")
|
|
||||||
return
|
|
||||||
# Compare local and latest versions
|
|
||||||
if local_version < latest_version:
|
|
||||||
logger.info(f"{YELLOW}{_('new_version').format(latest_version=latest_version, local_version=local_version)}{RESET}")
|
|
||||||
logger.info(f"{YELLOW}{_('changelog').format(VERSION_URL=VERSION_URL)}{RESET}")
|
|
||||||
auto_update()
|
|
||||||
elif beta == True:
|
|
||||||
logger.warning(f"You are running an \"unstable\" version of Goober, do not expect it to work properly.\nVersion {local_version}\nServer: {latest_version}{RESET}")
|
|
||||||
elif local_version > latest_version:
|
|
||||||
logger.warning(f"{_('modification_warning')}")
|
|
||||||
elif local_version == latest_version:
|
|
||||||
logger.info(f"{_('latest_version')} {local_version}")
|
|
||||||
logger.info(f"{_('latest_version2').format(VERSION_URL=VERSION_URL)}\n\n")
|
|
||||||
launched = True
|
|
||||||
return latest_version
|
|
1
modules/volta
Submodule
|
@ -0,0 +1 @@
|
||||||
|
Subproject commit 628de5f76ea2a258448d2ddfc081c2ce58f509fd
|
|
@ -1,9 +1,7 @@
|
||||||
discord.py
|
discord.py
|
||||||
markovify
|
markovify
|
||||||
spacy
|
nltk
|
||||||
spacytextblob
|
|
||||||
requests
|
requests
|
||||||
psutil
|
psutil
|
||||||
|
better_profanity
|
||||||
python-dotenv
|
python-dotenv
|
||||||
dotenv
|
|
||||||
pillow
|
|
|
@ -1,3 +0,0 @@
|
||||||
- The catbox.moe team for memory.json file uploads
|
|
||||||
- Charlie's Computers
|
|
||||||
- ctih1
|
|
3
todo.txt
|
@ -1,2 +1 @@
|
||||||
- revamp wiki
|
- update to latest version of goober
|
||||||
- alot
|
|
||||||
|
|
|
@ -7,11 +7,8 @@ import locale
|
||||||
import json
|
import json
|
||||||
import pathlib
|
import pathlib
|
||||||
import threading
|
import threading
|
||||||
import platform
|
|
||||||
import sys
|
|
||||||
import time
|
import time
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from functools import lru_cache
|
|
||||||
|
|
||||||
ANSI = "\033["
|
ANSI = "\033["
|
||||||
RED = f"{ANSI}31m"
|
RED = f"{ANSI}31m"
|
||||||
|
@ -64,6 +61,10 @@ if working_dir != module_dir:
|
||||||
translations = {}
|
translations = {}
|
||||||
_file_mod_times = {}
|
_file_mod_times = {}
|
||||||
|
|
||||||
|
import locale
|
||||||
|
import platform
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
def get_system_locale():
|
def get_system_locale():
|
||||||
system = platform.system() # fallback incase locale isnt set
|
system = platform.system() # fallback incase locale isnt set
|
||||||
|
@ -118,7 +119,6 @@ def reload_if_changed():
|
||||||
current_mtime = file_path.stat().st_mtime
|
current_mtime = file_path.stat().st_mtime
|
||||||
if current_mtime != last_mtime:
|
if current_mtime != last_mtime:
|
||||||
print(f"[VOLTA] {RED}Translation file changed: {file_path}, reloading...{RESET}")
|
print(f"[VOLTA] {RED}Translation file changed: {file_path}, reloading...{RESET}")
|
||||||
_lookup_translation.cache_clear()
|
|
||||||
load_translations()
|
load_translations()
|
||||||
break
|
break
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
|
@ -140,10 +140,9 @@ def set_language(lang: str):
|
||||||
else:
|
else:
|
||||||
print(f"[VOLTA] {RED}The fallback translations cannot be found! No fallback available.{RESET}")
|
print(f"[VOLTA] {RED}The fallback translations cannot be found! No fallback available.{RESET}")
|
||||||
ENGLISH_MISSING = True
|
ENGLISH_MISSING = True
|
||||||
_lookup_translation.cache_clear()
|
|
||||||
|
|
||||||
def check_missing_translations(LOCALE=LOCALE):
|
def check_missing_translations():
|
||||||
global ENGLISH_MISSING
|
global LOCALE, ENGLISH_MISSING
|
||||||
load_translations()
|
load_translations()
|
||||||
if FALLBACK_LOCALE not in translations:
|
if FALLBACK_LOCALE not in translations:
|
||||||
print(f"[VOLTA] {RED}Fallback translations ({FALLBACK_LOCALE}.json) missing from assets/locales.{RESET}")
|
print(f"[VOLTA] {RED}Fallback translations ({FALLBACK_LOCALE}.json) missing from assets/locales.{RESET}")
|
||||||
|
@ -176,31 +175,24 @@ def check_missing_translations(LOCALE=LOCALE):
|
||||||
|
|
||||||
printedsystemfallback = False
|
printedsystemfallback = False
|
||||||
|
|
||||||
@lru_cache(maxsize=600)
|
|
||||||
def _lookup_translation(lang: str, key: str):
|
|
||||||
return translations.get(lang, {}).get(key)
|
|
||||||
|
|
||||||
def get_translation(lang: str, key: str):
|
def get_translation(lang: str, key: str):
|
||||||
global printedsystemfallback
|
global printedsystemfallback
|
||||||
if ENGLISH_MISSING:
|
if ENGLISH_MISSING:
|
||||||
return f"[VOLTA] {RED}No fallback available!{RESET}"
|
return f"[VOLTA] {RED}No fallback available!{RESET}"
|
||||||
|
fallback_translations = translations.get(FALLBACK_LOCALE, {})
|
||||||
val = _lookup_translation(lang, key)
|
|
||||||
if val:
|
|
||||||
return val
|
|
||||||
sys_lang = get_system_locale().split("_")[0] if get_system_locale() else None
|
sys_lang = get_system_locale().split("_")[0] if get_system_locale() else None
|
||||||
if sys_lang and sys_lang != lang:
|
sys_translations = translations.get(sys_lang, {}) if sys_lang else {}
|
||||||
sys_val = _lookup_translation(sys_lang, key)
|
lang_translations = translations.get(lang, {})
|
||||||
if sys_val:
|
if key in lang_translations:
|
||||||
|
return lang_translations[key]
|
||||||
|
if sys_lang and sys_lang != lang and key in sys_translations:
|
||||||
if not printedsystemfallback:
|
if not printedsystemfallback:
|
||||||
print(f"[VOLTA] {YELLOW}Falling back to system language {sys_lang}!{RESET}")
|
print(f"[VOLTA] {YELLOW}Falling back to system language {sys_lang}!{RESET}")
|
||||||
printedsystemfallback = True
|
printedsystemfallback = True
|
||||||
return sys_val
|
return sys_translations[key]
|
||||||
fallback_val = _lookup_translation(FALLBACK_LOCALE, key)
|
if key in fallback_translations:
|
||||||
if fallback_val:
|
|
||||||
print(f"[VOLTA] {YELLOW}Missing key: '{key}' in '{lang}', falling back to fallback locale '{FALLBACK_LOCALE}'{RESET}")
|
print(f"[VOLTA] {YELLOW}Missing key: '{key}' in '{lang}', falling back to fallback locale '{FALLBACK_LOCALE}'{RESET}")
|
||||||
return fallback_val
|
return fallback_translations[key]
|
||||||
|
|
||||||
return f"[VOLTA] {YELLOW}Missing key: '{key}' in all locales!{RESET}"
|
return f"[VOLTA] {YELLOW}Missing key: '{key}' in all locales!{RESET}"
|
||||||
|
|
||||||
def _(key: str) -> str:
|
def _(key: str) -> str:
|
||||||
|
@ -212,9 +204,5 @@ watchdog_thread = threading.Thread(target=reload_if_changed, daemon=True)
|
||||||
watchdog_thread.start()
|
watchdog_thread.start()
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
import argparse
|
print("Volta should not be run directly! Please use it as a module..")
|
||||||
parser = argparse.ArgumentParser()
|
|
||||||
parser.add_argument("LOCALE", help="Locale to validate")
|
|
||||||
args = parser.parse_args()
|
|
||||||
print("[VOLTA] Validating all locales....")
|
|
||||||
check_missing_translations(LOCALE=f"{args.LOCALE}")
|
|