I was working on my discord bot and found a api(named numapi) which i want to use, i made a prototype in my pc which was ↓↓↓↓ and it worked fine.
import requests import json def numapi(no): response = requests.get(f'http://numbersapi.com/{no}?json') #print(response.json()) json_data = json.loads(response.text) num = json_data['text'] return(num) while True: inc = input('enter ')
But when i copied the same thing in my discord bot then it was not working. The code and error are as follows :-
code
import requests import json client = discord.Client() def numapi(no): #http://numbersapi.com/#505/year response = requests.get(f'http://numbersapi.com/{no}?json') #print(response.json()) json_data = json.loads(response.text) num = json_data['text'] return(num) @client.event async def on_message(message): if message.content.startswith('$fact'): number = message.content.split('$fact', 1)[1] fact = numapi(number) #await message.channel.send(number) await message.channel.send(fact) client.run(os.getenv("TOKEN"))
error
Ignoring exception in on_message Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 291, in on_message fact = numapi(number) File "main.py", line 89, in numapi json_data = json.loads(response.text) File "/usr/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
pls help me slove this
Advertisement
Answer
json.loads()
assumes that the data is decoded. Probably you’re receiving a bytes string. Try response.text.decode('utf-8')
.