Python如何从Solanart接口JSON中获取token地址最高id及对应价格
实现方案
核心处理逻辑
你需要先对接口返回的原始数据去重,只保留每个NFT地址对应的最新售卖记录,再计算地板价,具体逻辑如下:
- 以
token_add字段为唯一标识对所有记录分组 - 每个分组内仅保留
id最大的记录(id越大代表记录越新) - 从筛选后的最新记录中取最低价格,即为真实地板价
- 建议将接口请求逻辑挪到
!floor指令触发时执行,避免启动时拉取的静态数据长期未更新导致价格错误
完整修改代码
import discord import os import json import urllib.request from urllib.error import URLError my_secret = os.environ['TOKEN'] client = discord.Client() # 封装拉取并处理数据的函数 def get_latest_floor(): try: # 每次请求拉取最新数据 with urllib.request.urlopen("https://qzlsklfacc.medianetwork.cloud/nft_for_sale?collection=cryptocavemen", timeout=10) as url: data = json.loads(url.read().decode()) # 按token_add分组,保留每个地址最新的最高id记录 token_latest_map = {} for item in data: token_add = item['token_add'] # 不存在该token记录,或者当前记录id更大,就更新 if token_add not in token_latest_map or item['id'] > token_latest_map[token_add]['id']: token_latest_map[token_add] = item # 从最新记录中取最低价格 latest_prices = [item['price'] for item in token_latest_map.values()] floor_price = min(latest_prices) return f"The Floor Price is: {floor_price}" except URLError: return "数据请求失败,请稍后再试" except Exception as e: return f"数据处理出错:{str(e)}" @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'): res = get_latest_floor() await message.channel.send(res) client.run(my_secret)
关键修改说明
- 新增
get_latest_floor函数封装所有数据拉取、去重、计算逻辑,每次调用!floor都会重新拉取最新数据 - 使用字典
token_latest_map存储每个token地址的最新记录,自动过滤同一token的旧记录 - 新增基础异常捕获,避免接口故障导致bot直接崩溃
内容的提问来源于stack exchange,提问作者Ataberk Genç
相关产品推荐
相关产品推荐

