Reputation: 5
I am trying to make a discord bot in Nextcord Python that will generate a random recipe using a $randomrecipe command. I tried making it so that it would send a title of a dish (and also the image and ingredients) but I cant get it to work.
@bot.command(name='randomrecipe')
async def randomrecipe(ctx):
r = requests.get('https://api.spoonacular.com/recipes/random?apiKey=apikey')
title_name = r.json() ["title"]
await ctx.send(title_name)
here's the error for that code
Ignoring exception in command randomrecipe:
Traceback (most recent call last):
File "C:\Users\iliaa\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\iliaa\Downloads\json\app.py", line 22, in randomrecipe
title_name = r.json() ["title"]
KeyError: 'title'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\iliaa\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1048, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\iliaa\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\iliaa\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'title'
Upvotes: -1
Views: 493
Reputation: 81
This error means, that the api not returned a title.
The issue lies in following line: title_name = r.json()["title"]
Try to print put r.json() without the ["title"] print(r.json())
You will notice, that title key is not included in the response.
You are looking for title in the root element but after reproducing it, printing out the whole response, i noticed that title is located inside recipes. There are multiplie title keys and because you want the title of the dish (which is the first one) you need to index it by 0 (computers start couting at 0) so you should try to use r.json()["recipes"][0]["title"]
After using it this way, i got follwoing output:
All Day Simple Slow-Cooker FALL OFF the BONE Ribs
Here the full code i've used:
import requests
r = requests.get('https://api.spoonacular.com/recipes/random?apiKey=your_key_here')
print(r.json()["recipes"][0]["title"])
Upvotes: 0