繁体   English   中英

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

[英]How would I upload a BytesIO image to Telegram through telepot Bot.sendPhoto(uid, photo)?

因此,我希望能够将通过qrcode类生成的照片通过Telepot上传到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))

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

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

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

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

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

每次您想重新读取字节流时,请记住将其指向起点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM