From 6f38686513e2e7bd0fd2463cb91465ee68be7ee6 Mon Sep 17 00:00:00 2001 From: klemek Date: Thu, 30 Apr 2020 09:12:05 +0200 Subject: [PATCH] better use of BytesIO --- discord_bot/__main__.py | 16 +++++++--------- meme_otron/meme_otron.py | 8 ++++---- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/discord_bot/__main__.py b/discord_bot/__main__.py index 572aa6a..d602e45 100644 --- a/discord_bot/__main__.py +++ b/discord_bot/__main__.py @@ -3,7 +3,7 @@ import traceback import logging import discord import re -import tempfile +from io import BytesIO import sys from datetime import datetime from dotenv import load_dotenv @@ -134,8 +134,11 @@ async def on_message(message: discord.Message): else: await message.channel.send(response) else: - with tempfile.NamedTemporaryFile(delete=False) as output: - img.save(output, format="JPEG") + with BytesIO() as output_file: + img.save(output_file, format="JPEG") + output_file.flush() + output_file.seek(0) + response = None meme_id = utils.sanitize_input(args[0]) if len(args) == 1 and meme_id not in ["image", "text"]: @@ -153,13 +156,8 @@ async def on_message(message: discord.Message): response = f"A meme by {message.author.mention}:" if message_id not in SENT: SENT[message_id] = [] - response = await message.channel.send(response, - file=discord.File(filename="meme.jpg", fp=output.name)) + response = await message.channel.send(response, file=discord.File(output_file, "meme.jpg")) SENT[message_id] += [response] - try: - os.remove(output.name) - except PermissionError: - pass if not is_direct: await delete(message) diff --git a/meme_otron/meme_otron.py b/meme_otron/meme_otron.py index 41f893c..5070956 100644 --- a/meme_otron/meme_otron.py +++ b/meme_otron/meme_otron.py @@ -59,10 +59,10 @@ def compute(*args: str, input_data: Optional[bytes] = None, output_image = img_factory.apply_texts(output_image, watermarks, debug=debug) if max_file_size is not None: - img_file = BytesIO() - output_image.save(img_file, 'jpg') - if img_file.tell() > max_file_size: - return None, ['Output image too big'] + with BytesIO() as img_file: + output_image.save(img_file, 'JPEG') + if img_file.tell() > max_file_size: + return None, ['Output image too big'] return output_image, errors