Search code examples
discordchatbotnextcord

How can I get the first image of a thread using nextcord api?


I want to be able to get the first/last image of a thread in discord using nextcord.

I think I have to go through the channel/thread history but then how do I get the image out of the message? is an URL that I have to request.get?

   if message.flags.has_thread:
      async for m in message.thread.history(limit=100, oldest_first=True):

Solution

  • You can do like this as per your code:

    if message.flags.has_thread:
        async for m in message.thread.history(limit=100, oldest_first=True):
            if m.attachments:
                return m.attachments[0].url
    
    
    first_image_url = await first_image_from_thread(channel_id, thread_id)
    if first_image_url:
        response = requests.get(first_image_url)
        with open('first_image.jpg', 'wb') as f:
            f.write(response.content)
        print("Downloaded first image from thread...")
    else:
        print("No image found in thread...")
    

    In this, first_image_from_thread will be your function where you will pass parameter of channel_id & thread_id.

    You can also iterate through the attachments and check if it's image with it's file type like attachment.file_type.endswith(".jpeg"). If it's image you seeing then use "url" property to get image url and use "requests" module to download the image.