简体   繁体   English

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

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

So, I want to be able to upload a photo I have generated with the qrcode class to Telegram through telepot. 因此,我希望能够将通过qrcode类生成的照片通过Telepot上传到Telegram。 This is the code I have originally tried! 这是我最初尝试的代码!

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!

If I was going to accept the solution of saving the photo to the hard drive and then uploading it, I could upload it using this code! 如果我要接受将照片保存到硬盘然后上传的解决方案,则可以使用以下代码上传!

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

I have tried wrapping the BytesIO image in a BufferedReader and even giving it a fake name. 我曾尝试将BytesIO映像包装在BufferedReader中,甚至给它一个假名。

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

I have spent the past few days trying to figure out why I cannot upload the photo from memory. 在过去的几天里,我试图弄清楚为什么我不能从内存中上传照片。 I have looked through various solutions such as the fake name solution! 我浏览了各种解决方案,例如假名解决方案!

The error Telegram keeps giving me is the file must not be empty. 错误电报一直给我,因为该文件不能为空。 Saving it to the hard drive shows that it isn't empty and scanning the qrcode with my authentication app shows the qr code is not corrupted! 将其保存到硬盘驱动器表明它不为空,并且使用我的身份验证应用程序扫描二维码显示二维码未损坏! Thanks! 谢谢!

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

You have to put the stream pointer back to zero before sending: 发送之前,必须将流指针放回零:

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

Every time you want to re-read the byte stream, remember to point it back to the beginning. 每次您想重新读取字节流时,请记住将其指向起点。

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

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