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/qr.py | 46 +++++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 17 deletions(-) (limited to 'cogs/qr.py') diff --git a/cogs/qr.py b/cogs/qr.py index 058dac8..c1fd499 100644 --- a/cogs/qr.py +++ b/cogs/qr.py @@ -15,14 +15,26 @@ from discord.ext import commands logger = logging.getLogger(__name__) -try: - from PIL import Image - from pyzbar.pyzbar import decode as decode_qr - - DECODE_AVAILABLE = True -except ImportError: - DECODE_AVAILABLE = False - logger.warning("pyzbar or PIL not available, decode command will be disabled") +_pil_image = None +_decode_func = None +_decode_available = False + + +def _ensure_qr(): + global _pil_image, _decode_func, _decode_available + + if _pil_image is not None: + return _decode_available + + try: + from PIL import Image + from pyzbar.pyzbar import decode as _decode_func + _pil_image = Image + _decode_available = True + except ImportError: + _decode_available = False + logger.warning("pyzbar or PIL not available, decode command will be disabled") + return _decode_available class QR(commands.Cog): @@ -50,10 +62,9 @@ class QR(commands.Cog): ): await ctx.defer() - temp_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "temp") - os.makedirs(temp_dir, exist_ok=True) + from cogs.utils.temp import get_temp_dir temp_path = os.path.join( - temp_dir, f"qr_{os.getpid()}_{asyncio.get_event_loop().time()}.png" + get_temp_dir(), f"qr_{os.getpid()}_{asyncio.get_event_loop().time()}.png" ) try: @@ -75,7 +86,7 @@ class QR(commands.Cog): """Generate QR code (runs in executor)""" qr = qrcode.QRCode( version=1, - error_correction=qrcode.constants.ERROR_CORRECT_L, + error_correction=qrcode.constants.ERROR_CORRECT_L, # type: ignore[attr-defined] box_size=10, border=4, ) @@ -92,7 +103,7 @@ class QR(commands.Cog): discord.Attachment, "Obrazek z kodem QR", required=True ), ): - if not DECODE_AVAILABLE: + if not _ensure_qr(): await ctx.respond( "Dekodowanie nie jest dostępne (brak biblioteki pyzbar)", ephemeral=True ) @@ -126,11 +137,12 @@ class QR(commands.Cog): def _decode_qr(self, image_path): """Decode QR code from image (runs in executor)""" - try: - from PIL import Image + if not _ensure_qr(): + return None - img = Image.open(image_path) - decoded_list = decode_qr(img) + try: + img = _pil_image.open(image_path) + decoded_list = _decode_func(img) if decoded_list: return decoded_list[0].data.decode("utf-8") except Exception as e: -- cgit v1.2.3