简体   繁体   中英

Is there any way of getting values from keys inside other keys?

(first post sorry if i do this wrong) So I am making a bot (on discord) for me and my friends using discord.py (since python is the easiest code ever) and I've came across this. I need to get values from keys INSIDE OTHER keys. How do I do this?

So I've tried to change res to res.text and res.json and res.content and I could only find the "data" but not "id","name" or "description" which I need.

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

As I said in the code, I can only get "data" working and not id,name or desc. For id name and desc it just throws an error

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'

and

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

The https://friends.roblox.com/v1/users/<userid>/friends endpoint returns a list of all the friends that the user has, which can be of varying size.

With var = json.loads(res.text) you are loading the response text into a json object, which contains the key data , which you access using data = var['data'] . The new data variable now contains a list object, which is why cv = data['name'] fails to work as list objects do not take strings as keys, they are accessed using integers.

You need to iterate over the list to get all information on the friends. The below code goes through the list, pulls information for each item in the list and sends a message of the information once it has gone through all items.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM