我试图制作一个discord机器人,它会给我关于我输入的用户已经获得ACs的问题的信息。为此,我从cfapi获取了json文件,并将其转换为dictionary以访问保存此信息的密钥,我附上了获取的json的格式。问题是,它在我访问密钥的线路上给了我一个错误,另一个我无法理解的错误,我也在附加错误。谁能告诉我哪里出了问题,因为我对这个框架和python都是新手,我也在下面附上我的代码
代码
import discord
import requests
import json
token = '(my_token)'
client = discord.Client()
@client.event
async def on_message(message):
if message.content.startswith("!stalk"):
handle = ""
words = message.content
for word in words[1:]:
handle += word
await message.channel.send(handle + ': (last correctly solved problem name) ')
link = "https://codeforces.com/api/user.status?handle="
link += handle
request_info = requests.get(link)
json_obj = dict(request_info.json())
last_correct_problems = []
for submissions in json_obj['result']:
if submissions['verdict'] == 'OK':
last_correct_problems.append(submissions['problem']['name'])
for problem in last_correct_problems:
await message.channel.send(problem + ', ')
client.run(token)
错误
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\HP\Anaconda3\envs\balalalabot\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:/Users/HP/Desktop/labsheets/new_stuff/discbalalabot/bot.py", line 23, in on_message for submissions in json_obj['result']:
KeyError: 'result'
不和谐时的输出
API链接you can refer to the user.status method on this page
获取的JSON
{"status":"OK",
"result":[{"id":88388369,
"contestId":702,
"creationTimeSeconds":1596059866,
"relativeTimeSeconds":2147483647,
"problem":{"contestId":702,
"index":"A",
"name":"Maximum Increase",
"type":"PROGRAMMING",
"rating":800,
"tags":["dp","greedy","implementation"]},
"author":{"contestId":702,
"members":[{"handle":"Prabhu4"}],
"participantType":"PRACTICE",
"ghost":false,"startTimeSeconds":1469804400},
"programmingLanguage":"GNU C++17",
"verdict":"OK",
"testset":"TESTS",
"passedTestCount":32,
"timeConsumedMillis":46,
"memoryConsumedBytes":3788800},
{"id":88388346,
"contestId":702,
"creationTimeSeconds":1596059822,
"relativeTimeSeconds":2147483647,
"problem":{"contestId":702,
"index":"A",
"name":"Maximum Increase",
"type":"PROGRAMMING",
"rating":800,
"tags":["dp","greedy","implementation"]},
"author":{"contestId":702,
"members":[{"handle":"Prabhu4"}],
"participantType":"PRACTICE",
"ghost":false,
"startTimeSeconds":1469804400},
"programmingLanguage":"GNU C++17",
"verdict":"WRONG_ANSWER",
"testset":"TESTS",
"passedTestCount":0,
"timeConsumedMillis":15,
"memoryConsumedBytes":3788800}]}
首先,我建议您使用aiohttp库而不是请求库,因为aiohttp是异步的,而请求是阻塞的。 它从代码的前几行开始。您希望获取除命令之外的所有单词。message.content不是单词列表,而是消息的字符串。您必须使用message.content.split(“”)将其拆分为单词。 现在,当您获得json文件时,应该会得到正确的结果。 json()返回一个dict,不需要生成dict。 当你实现了这一点,它应该会起作用
相关问题 更多 >
编程相关推荐