如何通过Telepot Bot.sendPhoto(uid,照片)将BytesIO图像上传到Telegram?

时间:2017-05-16 21:58:08

标签: python python-3.x telegram-bot python-telegram-bot

所以,我希望能够通过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))

过去几天我一直想弄清楚为什么我无法从内存中上传照片。我已经查看了各种解决方案,例如the fake name解决方案!

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

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

1 个答案:

答案 0 :(得分:0)

在发送之前必须将流指针置回零:

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

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