Search code examples
pythondiscordcommandbots

Way to Get Information from Website With Discord Bot


i'm working on coding a discord bot using python and i'm trying to figure out a way to access a website via a bot command.

in theory, i'll have a command link the bot to the site, grab information, and then put that specific information in the chat.

this is what i'm trying to use: https://api.quotable.io/random, and have it be like !quote and then the bot will grab the 'content' and the 'author' bits of it.

is there a way to do this? i can't find anything written in the documentation online.

apologies if this is confusing, i'm not 100% sure what i'm doing.


Solution

  • You can do this by using the requests library. The code below imports the library, creates the query for the api and then makes the requests and then finally prints the response.

    import requests
    
    query = "https://api.quotable.io/random" 
    response = requests.get(query) 
    print(response)
    

    To output specific parts of the response, you will need to use JSON formatting. The code below only outputs the content of the message from the api request that you have made.

    import requests
    
    query = "https://api.quotable.io/random" 
    response = requests.get(query)
    print(response["content"]) 
    

    To implement this is discord instead of printing the response you can use message.send which is already built in. An example is below. This code makes the same request and instead outputs the content from the api request.

    import discord
    import requests
    
    @commands.command()
    async def search(ctx): 
        query = "https://api.quotable.io/random"
        response = requests.get(query)
        output = "The quote is " + response["content"]
        await ctx.send(output)