有没有办法从其他键中的键获取值?

时间:2019-08-15 20:01:58

标签: python-3.x discord.py

(如果我做错了,请先发表帖子,抱歉)所以我正在使用discord.py为我和我的朋友们制作一个机器人(不和谐)(因为python是有史以来最简单的代码),我遇到了这个问题。我需要从其他键中的键中获取值。我该怎么做?

因此,我尝试将res更改为res.text和res.json和res.content,但只能找到所需的“数据”,而找不到我的“ id”,“ name”或“ description”。 / p>

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import requests, json
import asyncio

Client = discord.Client()
client = commands.Bot(command_prefix='?')
@client.event
async def on_ready():
    print('started')

@client.command()
async def findfriends(ctx,userid):
        res = requests.get("https://friends.roblox.com/v1/users/"+userid+"/friends")
        var = json.loads(res.text)
        def a(a):
                ID = a['id']
                return ID
        def b(b):
                Name = b['name']
                return Name
        def c(c):
                description = c['description']
                return description
        data = var['data'] #I can get this working
        print(data)
        #cv = data['name'] #but this wont work
        #id = a(var)       #nor this
        #name = b(var)     #nor this
        #desc = c(var)     #nor this
        #await ctx.send("\nID: " + id + "\nName: " + name + "\nDesc: " + desc) # this is just sending the message

client.run(BOT TOKEN HERE) #yes i did indeed add it but just for the question i removed it

正如我在代码中所说,我只能使“数据”正常工作,而不能使id,name或desc生效。对于id名称和desc,它只会引发错误

Ignoring exception in command findfriends:
Traceback (most recent call last):
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 277, in findfriends
    id = a(var)       #nor this
  File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 266, in a
    ID = a['id']
KeyError: 'id'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 728, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'id'

Ignoring exception in command findfriends:
Traceback (most recent call last):
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/Calculator/PycharmProjects/ryhrthrthrhrebnfbngfbfg/a.py", line 274, in findfriends
    data = var['data']['id'] #I can get this working
TypeError: list indices must be integers or slices, not str

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 728, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Calculator\PycharmProjects\ryhrthrthrhrebnfbngfbfg\venv\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str

1 个答案:

答案 0 :(得分:2)

https://friends.roblox.com/v1/users/<userid>/friends端点返回用户拥有的所有朋友的列表,列表的大小可以变化。

使用var = json.loads(res.text),您正在将响应文本加载到一个JSON对象中,该对象包含密钥data,您可以使用data = var['data']访问该密钥。现在,新的data变量包含一个列表对象,这就是cv = data['name']无法工作的原因,因为列表对象不将字符串作为键,而是使用整数来访问它们。

您需要遍历列表以获取有关朋友的所有信息。下面的代码遍历列表,提取列表中每个项目的信息,并在遍历所有项目后发送一条信息消息。

import discord
from discord.ext.commands import Bot
from discord.ext import commands
import requests, json
import asyncio

client = commands.Bot(command_prefix='?')
@client.event
async def on_ready():
    print('started')

@client.command()
async def findfriends(ctx,userid):
    res = requests.get("https://friends.roblox.com/v1/users/"+userid+"/friends")
    var = json.loads(res.text)
    data = var['data']
    print(data)

    friends_msg = 'Friends information:'
    for friend in data:
        id = friend['id']
        name = friend['name']
        desc = friend['description']
        friends_msg = friends_msg + "\nID: " + id + "\nName: " + name + "\nDesc: " + desc

    await ctx.send(friends_msg)

client.run(BOT TOKEN HERE)