获取文件而不保存 aiohttp discord.py
Getting a file without saving it aiohttp discord.py
所以我有一个命令,它将用户在命令后所说的任何内容发送到网站 api 并发送网站生成的文件。但是我正在切换到 aiohttp,因为它不像标准请求函数那样阻塞
这是我处理正常请求的方式,效果很好:
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)
然而,当我尝试使用 aiohttp 时,我不知道如何实际获取原始文件数据。
所以我做了这个功能来得到它。但它不让我 return 图片,我无法检查 http 状态代码,否则它会导致错误。
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
我还能怎么做?这可能吗? aiohttp好像不太好理解
戴先生 "V" 自己从 discord.py discord 服务器发送了一个获取和发送数据的完美示例
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")
所以我有一个命令,它将用户在命令后所说的任何内容发送到网站 api 并发送网站生成的文件。但是我正在切换到 aiohttp,因为它不像标准请求函数那样阻塞
这是我处理正常请求的方式,效果很好:
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)
然而,当我尝试使用 aiohttp 时,我不知道如何实际获取原始文件数据。 所以我做了这个功能来得到它。但它不让我 return 图片,我无法检查 http 状态代码,否则它会导致错误。
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
我还能怎么做?这可能吗? aiohttp好像不太好理解
戴先生 "V" 自己从 discord.py discord 服务器发送了一个获取和发送数据的完美示例
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")