Is there a way to check if the attachment send is either a image or video in discord.py?

Viewed 931

I am making a bot that converts media.xxxx.net into cdn.xxxx.com links. This works perfectly for videos but as a side effect, it also converts images which is an undesirable effect.

One way would explicitly tell the bot which formats (mp4, MOV etc) to convert and leave the other formats but considering the amount of formats there are for video file, I think it is necessary but I can't come up with any other way.

Here is the code I wrote

if message.content.startswith('https://media') and not message.content.endswith('jpg') and not message.content.endswith('png') and not message.content.endswith('gif') and not message.content.endswith('webp'):
     message.content.replace('media', 'cdn').replace('net', 'com') 
     await message.delete()

Here I was trying to make the bot ignore the most common picture formats but it is just looking like a mess as I add more and more formats.

3 Answers

You can check for the file type of the attachments using the content_type attribute and if they are an image you can tell it to ignore it.

for att in message.attachements:
    if att.content_type.startswith("video"):
        new_url = message.content.replace('media', 'cdn').replace('net', 'com')
        await message.channel.send(new_url)
        await message.delete()

Instead of checking for if the URL does not ends with the image format, check if the URL ends with a video format.

message_text = message.content
if message_text.find('https://media.discordapp.net') != -1 and message_text.find('.mp4') != -1:
     new_url = message_text.replace('https://media.discordapp.net','https://cdn.discordapp.com')
     await message.channel.send(new_url) 
     await message.delete()

To make my code cleaner, I made a list and added all the possible formats in there, it is basically the same LOGIC as my previous way but it is a lot cleaner and more manageable.

formats=['png', 'jpg', 'gif' , 'webp', 'jpeg', 'jpg' , 'jpeg' ,'jfif' ,'pjpeg' , 'pjp', 'svg', 'bmp']
msg = message.content

if message.content.startswith('https://media'): 
     if any(word in msg for word in formats):
      return

So it will check for the word in the link, if it finds any one of the formats (jpg, png), it will return instead of running the next piece of code

Related