'Downloading attachments with Discord API in python

I am creating a bot to scrape images from a discord channel. The images can come in two ways:

1) A link such as: https://cdn.discordapp.com/attachments/XXXXXXXX

In this case I download the image directly from the URL and there is no problem.

2) In the second case, there is no URL and the images simply come directly as an attachment.

I am using the Python API, is there a simple way of downloading any attachments that are sent in a channel?

The code I am using for part 1 is:

if(string[0:26] == "https://cnd.discordapp.com"):
    r = requests.get(string, stream = True)
    with open("image1.png",'wb') as out_file:
        shutil.copyfileobj(r.raw, out_file)

Is there any way to like extract a URL from an attachment where the URL isn't listed in chat so I can plug it into the first method? If not, what commands do I use to iterate through message attachments/ downloading them?



Solution 1:[1]

you can use

url = ctx.message.attachments[0].url
if url[0:26] == 'https://cdn.discordapp.com':
    await ctx.send(url)

to get any attach attachments in the message, get the cdn.discordapp.com link and send it in chat. I haven't tested it but you should be able to get multiple attachments from a message by changing the list index in ctx.message.attachments[0].url

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 guest257351