【发布时间】:2021-06-11 18:02:07
【问题描述】:
我正在开发我的 discord 机器人,并找到了一个我想使用的 api(命名为 numapi),我在我的电脑上做了一个原型,它是 ↓↓↓↓ 并且效果很好。
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 ')
但是当我在我的不和谐机器人中复制相同的东西时,它就不起作用了。代码和错误如下:-
代码
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"))
错误
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)
请帮我解决这个问题
【问题讨论】:
-
检查
number是什么。另外你为什么评论response.json()而使用json.loads()? -
json.loads()假定数据已编码。可能您正在接收字节字符串。试试response.text.decode('utf-8')。 -
还有一件事。
number = message.content.split('$fact', 1)[1]这假设$fact之后没有空格。所以试试fact = numapi(int(number.strip())) -
@buran 我检查了一切,一切都很好。我评论说,因为我只是看到那个 json 中有什么东西,我用
json.loads()导入那个 json -
requests.Response.json()是一种方便的方法,您只需json_data = response.json()。当您print(repr(number))时,您会得到什么?
标签: python json api discord discord.py