-1

I am using discord.py and while trying to use a bible api that will call a random verse and return the verse from the function. The api will return something like this:

{
    'reference': 'Romans 1:11',
    'verses': [{'book_id': 'ROM',
                'book_name': 'Romans',
                'chapter': 1,
                'verse': 11,
                'text': 'For I long to see you, that I may impart to you some spiritual gift, to the end that you may be established;\n'}],
    'text': 'For I long to see you, that I may impart to you some spiritual gift, to the end that you may be established;\n', 
    'translation_id': 'web',
    'translation_name': 'World English Bible',
    'translation_note': 'Public Domain'
}

The api is this: https://bible-api.com/BOOK+CHAPTER:VERSE It is showing {'error':'not found'} when the verse or book is unacceptable, that's why I made a loop to check if it's allowed or not, if not then it will loop until it isn't 'not found'. and the code goes like this:

      find_book = True
      while True:
        response = requests.get(
          f'https://bible-api.com/{random.choice(bible_books)}+"-"{random.randint(1,150)}:{random.randint(1,176)}'
        )
        json_data = json.loads(response.text)
        print(str(json_data))
        if not json_data['error'] == 'not found':
          print(str(json_data[0]['reference']))
          find_book = False

but instead it prints out

    2022-10-07 04:11:23 ERROR    discord.client Ignoring exception in on_message
    Traceback (most recent call last):
      File "/home/runner/Beronics-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
        await coro(*args, **kwargs)
      File "main.py", line 127, in on_message
        get_random_bible_verse()
      File "main.py", line 48, in get_random_bible_verse
        if not json_data['error'] == 'not found':
    KeyError: 'error'

and not printing anything. I am not yet an expert at this but I will need help to do so.

To bring more information, the problem is that it doesn't prints the verses, it being a key inside a list of dicts of keys, I allow the keyError as it does the job but the other just ignores it as it is just an exception, so I don't know what to do.

  • Please include the relevant parts of the code as well as the full traceback error. – ewokx Oct 07 '22 at 04:11
  • Done, can you help please? – Beronicous Oct 07 '22 at 04:14
  • There isn't any key named ```error``` in your ```json_data```. You should check if there is a key ```error``` in your json_data before accessing it. – ewokx Oct 07 '22 at 04:18
  • You should use `response.json()` to get json out of your response and since your api is not sending any error key in your json response you cannot access it. If you want to check for not found you can use `response.status_code == '404'` this will check if resource is not found. – Deepak Tripathi Oct 07 '22 at 04:38
  • Does this answer your question? [I'm getting Key error in python](https://stackoverflow.com/questions/10116518/im-getting-key-error-in-python) – TheFungusAmongUs Oct 07 '22 at 14:39
  • No, there is an actual key named error, and I put a print function just incase. It prints out `{'error':'not found'}' and it actually works, it does the loop until it is not that, but the real problem is that printing the verse because it is not able to get the key from a list of dict which contains the verse or book name. – Beronicous Oct 08 '22 at 00:58

1 Answers1

0

Looks like the comments explained the key error, but fwiw whenever you have a key that may or may not exists, consider using .get as this will return None if the key does not exist. You can also add another default as a parameter for unique cases where None will not be a desired default.

if not json_data.get('error') == 'not found':
 ...

# or
if json_data.get('error') != 'not found':
 ...
0xDEADBEEF
  • 26
  • 2
  • The problem is not the ``keyError``, because it works until I stop using it. The problem is that it ignores the print of the verses and it fails. – Beronicous Oct 08 '22 at 01:09