From a2b5b10625126b7e98643af9fe40569c9e004047 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sat, 18 Apr 2026 00:24:50 +0200 Subject: refactor + preparing bot for public use Signed-off-by: salmonik --- cogs/plot.py | 65 ++++++++++++++++++++++++++++++------------------------------ 1 file changed, 32 insertions(+), 33 deletions(-) (limited to 'cogs/plot.py') diff --git a/cogs/plot.py b/cogs/plot.py index 1516bc1..65dcae4 100644 --- a/cogs/plot.py +++ b/cogs/plot.py @@ -14,20 +14,28 @@ from discord.ext import commands logger = logging.getLogger(__name__) -try: - import matplotlib - - matplotlib.use("Agg") - import matplotlib.pyplot as plt - - PLOT_AVAILABLE = True -except ImportError: - PLOT_AVAILABLE = False - logger.warning("matplotlib not available, plot command will be disabled") +_plt_module = None +_plot_available = False + + +def _ensure_plot(): + global _plt_module, _plot_available + + if _plt_module is not None: + return _plot_available + + try: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as _plt_module + _plot_available = True + except ImportError: + _plot_available = False + logger.warning("matplotlib not available, plot command will be disabled") + return _plot_available def parse_expression(expr: str) -> str: - """Convert user expression (x^3) to Python (x**3)""" expr = expr.replace("^", "**") expr = re.sub(r"(\d)([x])", r"\1*\2", expr) expr = re.sub(r"([x])(\d)", r"\1*\2", expr) @@ -39,7 +47,12 @@ class Plot(commands.Cog): self.bot = bot def _generate_plot(self, func_expr: str, output_path: str): - """Generate plot (runs in executor)""" + global _plt_module + + if not _ensure_plot(): + raise RuntimeError("matplotlib not available") + + plt = _plt_module parsed_expr = parse_expression(func_expr) x = [i * 0.1 for i in range(-100, 101)] @@ -83,30 +96,16 @@ class Plot(commands.Cog): plt.savefig(output_path, dpi=100, bbox_inches="tight") plt.close() - @commands.slash_command( - name="funkcja", description="Generuje wykres funkcji matematycznej" - ) - async def plot( - self, - ctx, - funkcja: str = discord.Option( - str, "Funkcja np. x^3, sin(x), x^2 + 2*x - 1", required=True - ), - ): - if not PLOT_AVAILABLE: - await ctx.respond( - "Generowanie wykresów nie jest dostępne (brak matplotlib)", - ephemeral=True, - ) + @commands.slash_command(name="funkcja", description="Generuje wykres funkcji matematycznej") + async def plot(self, ctx, funkcja: str = discord.Option(str, "Funkcja np. x^3, sin(x), x^2 + 2*x - 1", required=True)): + if not _ensure_plot(): + await ctx.respond("Generowanie wykresów nie jest dostępne (brak matplotlib)", ephemeral=True) return await ctx.defer() - temp_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "temp") - os.makedirs(temp_dir, exist_ok=True) - temp_path = os.path.join( - temp_dir, f"plot_{os.getpid()}_{asyncio.get_event_loop().time()}.png" - ) + from cogs.utils.temp import get_temp_dir + temp_path = os.path.join(get_temp_dir(), f"plot_{os.getpid()}_{asyncio.get_event_loop().time()}.png") try: loop = asyncio.get_event_loop() @@ -125,4 +124,4 @@ class Plot(commands.Cog): def setup(bot): - bot.add_cog(Plot(bot)) + bot.add_cog(Plot(bot)) \ No newline at end of file -- cgit v1.2.3