Search code examples
python-3.xdiscorddiscord.pyaiohttp

Getting a file without saving it aiohttp discord.py


So i have a command where it sends whatever the user said after the command to a website api and sends the file the site generates. However i'm changing over to aiohttp as it doesn't block like the standered requests functions

This is how i do it with normal requests and it works fine:

      elif (data[0].lower() == ">signgirl"):
        await bot.send_typing(message.channel)

        tmp = message.content.replace(">signgirl", "")

        m = hashlib.md5()
        m.update(tmp.encode('utf-8'))

        print(tmp, m.hexdigest())
        r = requests.post("http://localhost/sign.php", stream=True, data={'text': tmp})
        if (r.status_code() == 200):
            await bot.send_file(destination=message.channel, filename=str(m.hexdigest()+".png"), fp=r.raw)

However when i try with aiohttp i have no idea how to actually get the raw file data.. So i made this function to get it. but it doesn't let me return an image and i cannot check the http status code without it causing an error.

async def post_data2(url, payload):
async with aiohttp.ClientSession() as session2:
    async with session2.post(url, data=payload) as response2:
        output = {}
        output['data'] = await Image.open(BytesIO(response2.read()))
        output['status'] = 200 #await str(response2.status()) #Why is this object not callable?
        return output

How else could i do this? Is this possible? aiohttp doesn't seem as easy to understand.


Solution

  • Mister Day "V" Own from the discord.py discord server sent a perfect example of getting and sending the data

    async with aiohttp.ClientSession() as session:
        # or use a session you already have
        async with session.get("http://example.com") as resp:
            buffer = io.BytesIO(await resp.read())
            # buffer is a file-like
    
    await client.send_file(channel, fp=buffer, filename="whatever")