0

所以,我希望能够通过 Telepot 将我用 qrcode 类生成的照片上传到 Telegram。这是我最初尝试过的代码!

img = qrcode.make(totp.provisioning_uri(settings.OTPNAME)) # This creates the raw image (of the qr code)
output = BytesIO() # This is a "file" written into memory
img.save(output, format="PNG") # This is saving the raw image (of the qr code) into the "file" in memory
bot.sendPhoto(uid, output) # This is sending the image file (in memory) to telegram!

如果我要接受将照片保存到硬盘然后上传的解决方案,我可以使用此代码上传它!

imgTwo = open("image.png", 'rb') # So this works when combined with bot.sendPhoto(uid, imgTwo) # 'rb' means read + binary
bot.sendPhoto(uid, imgTwo)

我尝试将 BytesIO 图像包装在 BufferedReader 中,甚至给它起一个假名。

#output2 = BufferedReader(output)
#output.name = "fake.png"
#bot.sendPhoto(uid, ("fake.png", output))

过去几天我一直在试图弄清楚为什么我不能从内存中上传照片。我查看了各种解决方案,例如假名解决方案!

Telegram 一直给我的错误是文件不能为空。将其保存到硬盘驱动器表明它不是空的,并且使用我的身份验证应用程序扫描二维码显示二维码没有损坏!谢谢!

telepot.exception.TelegramError: ('Bad Request: file must be non-empty', 400, {'error_code': 400, 'ok': False, 'description': 'Bad Request: file must be non-empty'})
4

1 回答 1

0

在发送之前,您必须将流指针放回零:

img.save(output, format='PNG')
output.seek(0)     # IMPORTANT!!!!!!!!!!!
bot.sendPhoto(uid, ('z.png', output))

每次要重新读取字节流时,请记住将其指向开头。

于 2017-05-17T12:05:58.297 回答