【问题标题】:appending input to the end of api call in python在python中将输入附加到api调用的末尾
【发布时间】:2019-01-25 14:44:30
【问题描述】:
def i(bot,update,args):
    coin=args
    infoCall =requests.get("https://api.coingecko.com/api/v3/coins/").json()
    coinId = infoCall ['categories']
    update.message.reply_text(coinId)

我想将在 coin=args 中声明的 args 添加到 api 请求的末尾,以便它检索我的用户请求的信息,但这是我得到的错误

coinId = infoCall ['categories']
KeyError: 'categories'

我的猜测是因为它没有正确格式化请求,所以 api 给出的是 404 而不是请求的信息

def i(bot,update,args):
    coin=args
    infoCall =requests.get("https://api.coingecko.com/api/v3/coins/").json()
    infoCall = json.loads(infoCall)+str(coins) 
    coinId = infoCall['categories']
    update.message.reply_text(str (coinId))

添加后,这是我得到的新错误

    Traceback (most recent call last):
  File "C:\Users\Matthew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telegram\ext\dispatcher.py", line 279, in process_update
    handler.handle_update(update, self)
  File "C:\Users\Matthew\AppData\Local\Programs\Python\Python37-32\lib\site-packages\telegram\ext\commandhandler.py", line 173, in handle_update
    return self.callback(dispatcher.bot, update, **optional_args)
  File "C:/Users/Matthew/Desktop/coding_crap/CryptoBotBetav2.py", line 78, in i
    infoCall = json.loads(infoCall)+str(coins)
  File "C:\Users\Matthew\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 341, in loads
    raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not list

【问题讨论】:

  • 好吧,我错了,你infoCall正在检索列表中的信息,列表里面有dict,你现在要追加什么?你想给每个dict附加一个coinIds吗?
  • 如果我可以将我的用户输入添加到该 api 请求的末尾,它将撤回我想要对 api 进行的调用,从而打开我需要发送给他们的 json 信息。 抱歉,我对编程真的很陌生,我认为最好的学习方法是先跳起来,动手学习,因为所有视频对我都有很大帮助
  • 请告诉我你的预期输出。
  • 但是是的,我的想法是让我的电报机器人接受 /info 用户输入,然后获取找到该信息的 api 调用。
  • 用户在电报聊天中键入:/bitcoin - 然后将 /*bitcoin* 添加到 API 调用的末尾以调用 api.coingecko.com/api/v3/coins/bitcoin - 在 json 中搜索 ['categories' ] 并将该信息发送回用户

标签: python json bots telegram


【解决方案1】:

基本上,您没有将 args 参数附加到 api 点,这就是您收到错误的原因。在发出请求之前,您需要将 'bitcoin' 附加到 api 点,而不是在输出上。 一个典型的例子如下。我已经删除了 update 和其他未使用的变量。您可以根据需要放置它们。

import requests
def i(args):
    coin=args
    infoCall =requests.get("https://api.coingecko.com/api/v3/coins/"+ args).json()
    coinId = infoCall ['categories']
    print(coinId)
    # update.message.reply_text(coinId)
i('bitcoin')

输出:

['加密货币']

【讨论】:

  • TypeError: i() got multiple values for argument 'args' is the error I get with your solution
  • 请复制粘贴我的 sn-p 并在独立文件中执行
  • 您需要将我的解决方案修改为您需要的内容。我已经解决了你的KeyError 问题
  • 谢谢!问题解决了,有点....现在消息太长了,我只想选择一定数量
  • 很高兴我能帮上忙。如果我的回答对您有帮助,请点击对勾接受我的回答。
猜你喜欢
  • 1970-01-01
  • 2021-04-03
  • 2017-03-26
  • 2017-10-13
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 2011-09-06
相关资源
最近更新 更多