skip to Main Content

I have a bot that creates a qr code and I want it to send qr code to the user without saving it to the hard drive

I create qr code like this:

import qrcode
qr_code_img = qrcode.make('some data')   # in handler used # qrcode.make(message.text')
print(type(qr_code_img))                 # <class 'qrcode.image.pil.PilImage'>
print(type(qr_code_img.get_image()))     # <class 'PIL.Image.Image'>

I think I need to get <class '_io.BytesIO'>

with information about qr code

class aiogram.types.input_file.InputFile(path_or_bytesio: Union[str, IOBase, Path, _WebPipe], filename=None, conf=None)

docs: https://docs.aiogram.dev/en/latest/telegram/types/input_file.html

file = InputFile(path_or_bytesio = ?)    #need to convert qr code to something
await bot.send_photo(chat_id = message.from_user.id, photo = file)

thanks a lot

qr_code_img = qrcode.make(message.text)
await bot.send_photo(chat_id = message.from_user.id, photo = qr_code_img)

if I just send a qrcode i’ll get error

TypeError: Can not serialize value type: <class 'qrcode.image.pil.PilImage'>
 headers: {}
 value: <qrcode.image.pil.PilImage object at 0x000001C741E4CE10> ````

2

Answers


  1. Your question isn’t great, but I think you just want to save to a BytesIO object.

    Something like:

    from io import BytesIO
    
    import qrcode
    import aiogram
    
    def make_qrcode(text):
        buf = BytesIO()
        qrcode.make(text).save(buf, format='PNG')
        buf.seek(0)
        return aiogram.types.InputFile(buf, "qrcode.png")
    
    bot.send_photo(chat_id=message.from_user.id, photo=make_qrcode("example text"))
    

    Would hopefully do what you want.

    Login or Signup to reply.
  2. For aiogram 3.0 works a bit different

    import qrcode
    import qrcode.image.svg
    from io import BytesIO
    from aiogram.types import BufferedInputFile
    
    
    def make_qr(url: str) -> BufferedInputFile:
        # Better use BytesIO as context manager
        with BytesIO() as buffer:
            image = qrcode.make(url)
            # Don't use format kwarg - it is not useful anymore. 
            # If you need specified format better choose it in make()
            image.save(buffer)
            # Following command sets cursor to 0 position in the buffer
            buffer.seek(0)
            # To transform _io.Bytes to bytesarray you need to use read()
            file_to_send = BufferedInputFile(buffer.read(), "qrcode.svg")
        # Sure, you can return BufferedInputFile with not using variable
        return file_to_send
    

    InputFile is not required for direct use anymore. Now you need to use child classes like BufferedInputFile

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search