如何使用电报机器人发送 JSON 格式的消息?

How to send message with information in JSON format using telegram bot?

我正在尝试使用电报机器人将此信息作为消息发送。但是,当我尝试发送消息时出现错误:card = f'{hbold("ExchangeName: ")}{(item.get("exchange_name"))}\n'
AttributeError:'str' 对象没有属性 'get'。我该如何解决?

    "name_of_coin": "Bitcoin",
    "marketPairs": [
        {
            "exchange_name": "Binance",
            "market_url": "https://www.binance.com/en/trade/BTC_USDT",
            "price": 49516.15001013148,
            "last_update": "2021-12-05T12:32:54.000Z",
            "exchange_id": 270
        },
        {
            "exchange_name": "Coinbase Exchange",
            "market_url": "https://pro.coinbase.com/trade/BTC-USD",
            "price": 49610.79,
            "last_update": "2021-12-05T12:32:55.000Z",
            "exchange_id": 89
        },
        {
            "exchange_name": "Bitfinex",
            "market_url": "https://www.bitfinex.com/t/BTC:USD",
            "price": 49586.15351025,
            "last_update": "2021-12-05T12:32:53.000Z",
            "exchange_id": 37
        },
        {
            "exchange_name": "FTX",
            "market_url": "https://ftx.com/trade/BTC/USDT",
            "price": 49508.56563407031,
            "last_update": "2021-12-05T12:32:53.000Z",
            "exchange_id": 524
        }
]

我的代码:

with open(file_path) as file:
        data = json.load(file)

    for item in data:

        card = f'{hbold("ExchangeName: ")}{(item.get("exchange_name"))}\n' \
        f'{hbold("MarketUrl: ")}{(item.get("market_url"))}\n' \
        f'{hbold("Price: ")}{(item.get("price"))}\n' \
        f'{hbold("LastUpdated: ")}{(item.get("last_update"))}\n' \
        f'{hbold("ExchangeId: ")}{(item.get("exchange_id"))}\n' \

        await message.answer(card)

开始吧

with open(file_path) as file:
        data = json.load(file)

我们需要从名为 'marketPairs' 的字典键中获取值,然后我们需要这样写:

for item in data['marketPairs']:

现在我们需要正确使用字符串格式来使之正确。 请不要在字符串末尾关闭引号。看看这个:

  card = f'ExchangeName: {item["exchange_name"]}\n\
  MarketURL: {item["market_url"]} etc.'

我使用 \n\ 没有 qoutes 首先用于输出中的换行符(符号 \n),然后用于代码中的换行符(符号 ) 那么,您可以使用 aiogram 库中的 send_message。因为答案是在用户消息后使用,但 'send_message' 不等待用户的响应。

  await bot.send_message(user_id, card)