Skip to content

Commit

Permalink
I HAVEN'T BEEN COMMITTING???
Browse files Browse the repository at this point in the history
  • Loading branch information
balt-dev committed Nov 2, 2024
1 parent e0e5598 commit d78f18a
Show file tree
Hide file tree
Showing 12 changed files with 1,166 additions and 749 deletions.
31 changes: 26 additions & 5 deletions ROBOT.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import auth
import config
import webhooks
from src.types import Macro
from src.types import TextMacro
from src.db import Database

from numpy import set_printoptions as numpy_set_printoptions
Expand Down Expand Up @@ -111,13 +111,34 @@ async def close(self) -> None:
await self.db.close()
await super().close()

async def on_ready(self) -> None:
await self.db.connect(self.db_path)
async def load_macros(self):
print("Loading macros...")
async with self.db.conn.cursor() as cur:
await cur.execute("SELECT * from macros")
for (name, value, description, author) in await cur.fetchall():
self.macros[name] = Macro(value, description, author)
rows = await cur.fetchall()
length = len(rows)
print(f"0 / {length}", end = "")
for i, (name, source, description, author, input, varargs) in enumerate(rows):
inputs = input.split("\t")
inputs = [input for input in inputs if input]
macro = TextMacro(name, description, source, inputs, varargs, author, None)
try:
macro.forest = self.macro_handler.parse_forest(source)
except AssertionError as err:
warnings.warn(traceback.format_exc())
await asyncio.sleep(10)
continue
except Exception as err:
macro.failure = err
self.macros[name] = macro
print(f"\r{i + 1} / {length}", end = "")
sys.stdout.flush()
print("\nMacros loaded.")

async def on_ready(self) -> None:
await self.db.connect(self.db_path)
await self.load_macros()

print(f"Logged in as {self.user}!")
if bot.baba_loaded:
await self.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="commands..."))
Expand Down
4 changes: 2 additions & 2 deletions config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import discord

activity = "Booting..."
description = "*An entertainment bot for rendering levels and custom scenes based on the indie game Baba Is You.*"
prefixes = ["=", "robot is ", "ROBOT IS "]
description = "*Beta branch. May be unstable.*"
prefixes = ["=="]
trigger_on_mention = True
embed_color = discord.Color(12877055)
logging_color = 0xffffff
Expand Down
33 changes: 27 additions & 6 deletions src/cogs/errorhandler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import io
import os
import re
import signal
Expand Down Expand Up @@ -196,11 +197,31 @@ async def on_command_error(self, ctx: Context, error: Exception):
return await ctx.error(f'The render took too long, so it was cancelled.')
elif isinstance(error, errors.InvalidFlagError):
return await ctx.error(f'A flag failed to parse:\n> `{error}`')
elif isinstance(error, errors.FailedBuiltinMacro):
if error.custom:
return await ctx.error(f'A macro created a custom error:\n> {error.message}')
else:
return await ctx.error(f'A builtin macro failed to compute in `{error.raw}`:\n> {error.message}')
elif isinstance(error, errors.MacroSyntaxError):
return await ctx.error(f"A macro tree failed to parse!\n```{error}```")
elif isinstance(error, errors.MacroRuntimeError):
tb = [[error, 1]]
while error.cause is not None:
error = error.cause
if not isinstance(error, errors.MacroRuntimeError):
tb.append([error, 1])
break
if error.name == tb[-1][0].name and error.reason == tb[-1][0].reason:
tb[-1][1] += 1
else:
if hasattr(error, "_builtin"):
tb[-1][0].reason = error.reason
else:
tb.append([error, 1])
buf = io.StringIO()
buf.write("Macro execution failed!\n")
for err in tb:
buf.write(f"- {err[0]}")
if err[1] > 1:
buf.write(f" (x{err[1]})")
buf.write("\n")
return await ctx.error(buf.getvalue())

elif isinstance(error, commands.BadLiteralArgument):
return await ctx.error(f"An argument for the command wasn't in the allowed values of `{', '.join(repr(o) for o in error.literals)}`.")
elif isinstance(error, re.error):
Expand Down Expand Up @@ -244,7 +265,7 @@ async def on_command_error(self, ctx: Context, error: Exception):
file=sys.stderr)
except Exception as err:
try:
title = f'**Unhandled exception in fallback handler!!!**'
title = f':warning: Error fallback crash!'
if len(title) > 32:
title = title[:32]
if os.name == "nt":
Expand Down
4 changes: 2 additions & 2 deletions src/cogs/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .. import constants
from ..errors import InvalidFlagError
from ..tile import Tile
from ..types import Color, Macro, RenderContext
from ..types import Color, TextMacro, RenderContext

if TYPE_CHECKING:
from ...ROBOT import Bot
Expand Down Expand Up @@ -311,4 +311,4 @@ async def boomerang(match, ctx):
)
async def macro(match, ctx):
"""Define macros for variants."""
ctx.macros[match.group(1)] = Macro(value=match.group(2), description="<internal>", author=-1)
ctx.macros[match.group(1)] = TextMacro(source=match.group(2), description="<internal>", author=-1)
19 changes: 8 additions & 11 deletions src/cogs/global.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,8 +305,7 @@ async def render_tiles(self, ctx: Context, *, objects: str, rule: bool):
try:
await ctx.typing()
ctx.silent = ctx.message is not None and ctx.message.flags.silent
tiles = emoji.demojize(objects.strip(), language='alias').replace(":hearts:",
"♥") # keep the heart, for the people
tiles = emoji.demojize(objects.strip(), language='alias').replace(":hearts:", "♥") # keep the heart, for the people
tiles = re.sub(r'<a?(:.+?:)\d+?>', r'\1', tiles)
tiles = re.sub(r"\\(?=[:<])", "", tiles)
tiles = re.sub(r"(?<!\\)`", "", tiles)
Expand Down Expand Up @@ -361,14 +360,12 @@ async def render_tiles(self, ctx: Context, *, objects: str, rule: bool):
tiles = tiles[:a - offset] + text + tiles[b - offset:]
offset += (b - a) - len(text)

user_macros = ctx.bot.macros | render_ctx.macros
last_tiles = None
passes = 0
while last_tiles != tiles and passes < 50:
last_tiles = tiles
tiles, _ = ctx.bot.macro_handler.parse_macros(tiles, False, user_macros, "r" if rule else "t")
tiles = tiles.strip()
passes += 1
user_macros = {} # TODO: Reimplement --mc

objects = objects.strip("`").strip()
parsed = ctx.bot.macro_handler.parse_forest(objects)
tiles = await ctx.bot.macro_handler.evaluate_forest(parsed, vars = {"_CONTEXT": "r" if rule else "t"})
tiles = "" if tiles is None else str(tiles)

# Check for empty input
if not tiles:
Expand All @@ -389,7 +386,7 @@ async def render_tiles(self, ctx: Context, *, objects: str, rule: bool):
comma_grid = split_commas(comma_grid, "$")
except errors.SplittingException as e:
cause = e.args[0]
return await ctx.error(f"I couldn't split the following input into separate objects: \"{cause}\".")
return await ctx.error(f"Couldn't split the following input into separate objects: \"{cause}\".")

tilecount = 0
maxstack = 1
Expand Down
Loading

0 comments on commit d78f18a

Please sign in to comment.