#πŸ”’ Verifying image urls

20 messages Β· Page 1 of 1 (latest)

marsh cloud
#

I'm trying to create a command that allows users to send an image url, but I would like to verify that the link actually leads to a valid image before having it stored in the database.

Also I'm using nextcord for this

waxen walrusBOT
#

@marsh cloud

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

wheat leaf
#

hi

marsh cloud
#

greetings

marsh cloud
wheat leaf
#

ok

cyan shell
wheat leaf
#

@marsh cloud

#

you can use a databank to save the images

#

a json file

marsh cloud
#

I'm pretty new at coding -- what exactly can a json file store?

wheat leaf
#
import discord
from discord.ext import commands
import requests
import json


# Loading data from JSON file
try:
    with open('allowed_images.json', 'r') as file:
        allowed_images = json.load(file)
except FileNotFoundError:
    allowed_images = []

# Function to save data to JSON file
def save_allowed_images():
    with open('allowed_images.json', 'w') as file:
        json.dump(allowed_images, file, indent=4)

@bot.command()
async def addimage(ctx, image_url: str):
    # List of allowed prefixes for the URL
    allowed_prefixes = ["https://", "http://"]

    # Checking if the link starts with an allowed prefix
    if not any(image_url.startswith(prefix) for prefix in allowed_prefixes):
        await ctx.send("The image URL must start with 'https://' or 'http://'.")
        return

    # Checking if the URL is already in the list
    if image_url in allowed_images:
        await ctx.send("The image URL is already allowed and was not saved again.")
    else:
        # The URL is valid, saving it to the database
        allowed_images.append(image_url)
        save_allowed_images()
        await ctx.send("The image URL has been successfully saved!")

i made notes above the codes #

#

please take this as an exercise and correct some information by yourself!

marsh cloud
#

interesting, ty

#

I'll see what I can make with it

wheat leaf
waxen walrusBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.