我写了一个 Python 代码来从 opensea 的 API 获取一组 NFT 价格并返回它的总美元价值如下:
# Downgraded to python-telegram-bot 13.7 : pip install python-telegram-bot==13.7
# Set your bot token here.
bot_token = ''
# Import necessary libs
import os
import requests
from telegram.ext import Updater, CommandHandler, MessageHandler, filters
# ETH NFT portfolio contained in the dictionary.
eth_nfts_dict = {'pudgypenguins': 1,
'lilpudgys': 1,
'pudgyrods': 1}
# Set up logging
import logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
# Setting up their polling stuff
updater = Updater(token=bot_token, use_context=True)
dispatcher = updater.dispatcher
## Functions
'''Fetch spot prices frm coinbase'''
def coinbase_spot(symbol):
cb_url = f"https://api.coinbase.com/v2/exchange-rates?currency={symbol}"
cb_response = requests.get(cb_url)
return float(cb_response.json()['data']['rates']['USD'])
'''Print ETH NFT prices in portfolio, and total USD value'''
def get_eth_nfts(nfts_dict, name):
eth_counter = 0
for nft, qty in nfts_dict.items():
url = f"https://api.opensea.io/api/v1/collection/{nft}/stats"
headers = {"accept": "application/json"}
response = requests.get(url, headers=headers)
eth_floor_price = response.json()['stats']['floor_price']
eth_counter += eth_floor_price * qty
nfts_dict[nft] = eth_floor_price
# Below code is to format the data to appear visually aligned on TG.
# Wrap ``` to the string (for Markdown formatting)
message = "```\n"
for key, value in nfts_dict.items():
message = message + "{0:<40} {1}".format(key, value) + "\n"
message = message + f"\nTotal value of {name}'s ETH NFTs is {round(eth_counter, 3)} ETH ({'${:,.2f}'.format(eth_counter * coinbase_spot('eth'))})" + "\n```"
return message
# Commands
def eth_nfts(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text=get_eth_nfts(eth_nfts_dict, 'Ben'), parse_mode='Markdown') # parse_mode set to Markdown
# Create and add command handlers
eth_nfts_handler = CommandHandler('Ben_eth', eth_nfts)
dispatcher.add_handler(eth_nfts_handler) # basically it's: updater.dispatcher.add_handler(CommandHandler('<command>', <command function>))
updater.start_polling()
updater.idle() # make sure that program won't fail if 2 programs are attempted to run simultaneously.
下图中的结果显示了当我尝试 ping 我的 Telegram 机器人时发生的情况:
最初的“/ben_eth”命令返回正确的 Total 值。但随后的 '/ben_eth' 似乎返回了错误的总值(初始值的倍数)。导致后续总计值错误的错误是什么?
nft_dict
是一个字典,将 nfts
键映射到它们的数量。但是,当您运行 nfts_dict[nft] = eth_floor_price
时,您将用 nfts
的价格替换字典中的数量。所以你的代码第二次运行时,每个nft
的数量都是错误的。