【问题标题】:How to output this JSON, which is in the format below in Discord?如何在 Discord 中输出以下格式的 JSON?
【发布时间】:2022-01-24 01:45:28
【问题描述】:

代码由用户在 Discord "$CryptoUpdate bitcoin" 上输入 我希望程序在没有语音标记和大括号的情况下输出以下内容:

{"id":"bitcoin",
"symbol":"btc",
"name":"Bitcoin","image":"https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
"current_price":36953,
"market_cap":698702581464,
"market_cap_rank":1,"fully_diluted_valuation":776008266281,"total_volume":16490236396,
"high_24h":37609,
"low_24h":36620,
"price_change_24h":58.65,
"price_change_percentage_24h":0.15896,
"market_cap_change_24h":362040201,
"market_cap_change_percentage_24h":0.05184,
"circulating_supply":18907987.0,
"total_supply":21000000.0,
"max_supply":21000000.0,
"ath":51032,
"ath_change_percentage":-27.54985,
"ath_date":"2021-11-10T14:24:11.849Z",
"atl":43.9,
"atl_change_percentage":84116.23351,
"atl_date":"2013-07-05T00:00:00.000Z",
"roi":"null",
"last_updated":"2021-12-22T17:31:34.189Z"}

Click here for JSON response output on Discord

代码:

import discord
import requests
from replit import db

def getCryptoUpdate(crypto):
  URL ='https://api.coingecko.com/api/v3/coins/markets?vs_currency=gbp'
  r = requests.get(url=URL)
  data = r.json()

  for i in range(len(data)):
    db[data[i]['id']] = data[i]

  if crypto in db.keys():
    return db[crypto]
  else:
    return None

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith("$CryptoUpdate "):
    cryptoToBeChecked = message.content.split('$CryptoUpdate ',1)[1].lower()
    await message.channel.send(getCryptoUpdate(cryptoToBeChecked))

【问题讨论】:

    标签: python discord


    【解决方案1】:

    我建议使用format_message 之类的函数,并将解析后的 JSON 作为 python dict 传递。从那时起,您可以调整您发送的消息的外观,以及显示响应中的哪些属性。

    例如

    def format_message(crypto):
        return f'Name:  {crypto.name}. Current price: {crypto.current_price}'
    

    在我看来,如果您真的需要全部显示数据,那么删除大括号和引号在可读性方面的影响可以忽略不计。

    【讨论】:

    • 谢谢!是的,大括号和引号并没有多大意义,我只是认为有一种简单的方法可以删除它们。但是谢谢,伙计!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 2020-06-15
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多