#Problems with getting message attachment

1 messages · Page 1 of 1 (latest)

candid canyon
#

Code:

    @commands.command()
    async def quoteit(self, message):

        source_image = Image.open(message.attachment[0].url)
        transparent_image = Image.open("transparent_image.png").resize(source_image.size)
        mask = Image.open("quote_mask.png").size(source_image.size)

        output_image = Image.composite(source_image, transparent_image, mask)
        message_picture = disnake.File(output_image)
        await message.send(file=message_picture)

Error:

  File "F:\...\cogs\utils.py", line 13, in quoteit
    source_image = Image.open(message.attachments[0].url)
                              ^^^^^^^^^^^^^^^^^^^
AttributeError: 'Context' object has no attribute 'attachments'

Already tried attachment, attachments and still getting this error.

Command looks like:

.quoteit
*image*
teal jetty
#

ctx.message gives Message

brave cedar
#

You're receiving a Context object, it doesn't have attachments directly

#

What it does have is a message reference, which does have attachments

#

Another thing is that you're passing an url to image.open, how's that supposed to work

candid canyon
#

ok

candid canyon
#

without saving it

brave cedar
#

If not, attachments have a .to_file method

candid canyon
candid canyon
#

ctx.send(file=variable)

brave cedar
#

Well then you'd more less do

  • await Attachment.read() to receive bytes
  • pass the bytes to io.BytesIO to get an in-memory file
  • Image.open the file
  • do whatever edits you need
  • Image.save into another io.BytesIO (remember to .seek(0))
  • pass that into disnake.File
  • upload the file
candid canyon
#

oh, bytes

#

okay...

brave cedar
#

A bit involved process but it is what it is...

#

io.BytesIO works as an adapter

#

Since there's no PIL method to create an image directly from bytes

#

Same for saving

candid canyon
#

Ok

candid canyon
#

okay, im almost here

#

but by some reason it's black but not transparent

#

(overlay image is full transparent)

#

(it's PNG)

brave cedar
#

You probably used a method which isn't alpha-aware

candid canyon
#

okay, it;s working

#

(sometimes AI good for trouble-shooting when worst to write code)

brave cedar