23

所以我有一个我正在玩的不和谐机器人来学习 Python。我有一个命令可以下载图像并编辑/合并它们,然后将编辑后的图像发送到聊天室。我以前曾经requests这样做过,但是其中一位 discord.py 的库开发人员告诉我,我应该使用aiohttp而不是requests. 我找不到如何下载图像aiohttp,我尝试了很多东西,但没有一个有效。

if message.content.startswith("!async"):
    import aiohttp
    import random
    import time
    import shutil
    start = time.time()
    notr = 0
    imagemake = Image.new("RGBA",(2048,2160))
    imgsave = "H:\Documents\PyCharmProjects\ChatBot\Images"
    imagesend = os.path.join(imgsave,"merged.png")
    imgmergedsend =os.path.join(imgsave,"merged2.png")
    with aiohttp.ClientSession() as session:
        async with session.get("http://schoolido.lu/api/cards/788/") as resp:
            data = await resp.json()
            cardsave = session.get(data["card_image"])
            with open((os.path.join(imgsave, "card.png")),"wb") as out_file:
                shutil.copyfileobj(cardsave, out_file)

是我现在拥有的,但这仍然行不通。

那么,有没有办法下载图片呢?

4

2 回答 2

36

写入文件时锁定循环。您需要使用 aiofiles。

import aiohttp        
import aiofiles

async with aiohttp.ClientSession() as session:
    url = "http://host/file.img"
    async with session.get(url) as resp:
        if resp.status == 200:
            f = await aiofiles.open('/some/file.img', mode='wb')
            await f.write(await resp.read())
            await f.close()
于 2018-08-08T11:45:57.880 回答
9

所以我想通了,不久前:

if message.content.startswith("!async2"):
    import aiohttp
    with aiohttp.ClientSession() as session:
        async with session.get("http://schoolido.lu/api/cards/788/") as resp:
            data = await resp.json()
            card = data["card_image"]
            async with session.get(card) as resp2:
                test = await resp2.read()
                with open("cardtest2.png", "wb") as f:
                    f.write(test)

我收到的是回复,而不是图片回复

于 2016-02-16T14:40:39.023 回答