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.
JavaScript
x
13
13
1
import requests
2
import json
3
4
def numapi(no):
5
response = requests.get(f'http://numbersapi.com/{no}?json')
6
#print(response.json())
7
json_data = json.loads(response.text)
8
num = json_data['text']
9
return(num)
10
11
while True:
12
inc = input('enter ')
13
But when i copied the same thing in my discord bot then it was not working. The code and error are as follows :-
code
JavaScript
1
23
23
1
import requests
2
import json
3
4
client = discord.Client()
5
6
def numapi(no):
7
#http://numbersapi.com/#505/year
8
response = requests.get(f'http://numbersapi.com/{no}?json')
9
#print(response.json())
10
json_data = json.loads(response.text)
11
num = json_data['text']
12
return(num)
13
14
@client.event
15
async def on_message(message):
16
if message.content.startswith('$fact'):
17
number = message.content.split('$fact', 1)[1]
18
fact = numapi(number)
19
#await message.channel.send(number)
20
await message.channel.send(fact)
21
22
client.run(os.getenv("TOKEN"))
23
error
JavaScript
1
16
16
1
Ignoring exception in on_message
2
Traceback (most recent call last):
3
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
4
await coro(*args, **kwargs)
5
File "main.py", line 291, in on_message
6
fact = numapi(number)
7
File "main.py", line 89, in numapi
8
json_data = json.loads(response.text)
9
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
10
return _default_decoder.decode(s)
11
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
12
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
13
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
14
raise JSONDecodeError("Expecting value", s, err.value) from None
15
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
16
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')
.