You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何选取JSON中的最小属性值?Discord机器人获取Solanart地板价问题

解决方案

你现有代码存在两个核心问题:

  1. 数据请求逻辑写在全局作用域,只会在机器人启动时拉取一次JSON,后续用户调用!floor时返回的都是旧数据,不符合实时获取最新价格的需求
  2. 缺少提取最小price值的逻辑

修改步骤

  • 把数据请求逻辑迁移到!floor指令的触发分支内,每次用户调用都重新拉取最新的在售NFT数据
  • 遍历返回的JSON数组,提取所有price字段的值,转换为数值类型后取最小值
  • 新增异常捕获逻辑,避免接口请求失败导致机器人报错

修改后的完整代码

import discord
import os
import json
import urllib.request

my_secret = os.environ['TOKEN']
# 新版discord.py需要手动开启消息内容权限,版本低于2.0可删除这两行intents配置
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)


@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

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

  if message.content.startswith('!floor'):
    try:
        # 每次调用指令都拉取最新的在售数据
        with urllib.request.urlopen("https://qzlsklfacc.medianetwork.cloud/nft_for_sale?collection=cryptocavemen") as url:
            data = json.loads(url.read().decode())
        # 提取所有price转为浮点型后取最小值,保留2位小数输出
        min_price = min(float(item['price']) for item in data)
        await message.channel.send(f"The Floor Price is: {min_price:.2f} SOL")
    except Exception as e:
        await message.channel.send("暂时无法获取地板价,请稍后再试")
        # 控制台打印错误信息方便排查
        print(f"请求出错:{e}")

client.run(my_secret)

内容的提问来源于stack exchange,提问作者Ataberk Genç

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:54:03