跳到文章

Crypto Price - Scriptable Widget

Crypto Price

用 Coinbase 的 API 写了一个小组件, 方便随时瞄一眼 BTC, ETH, SOL 的价格

不用交易所 widget 主要是他们的控件 widget 名字已经有品牌露出, 仍在不大的空间里塞进自己的 icon/logo

选择 Scriptable 是它可以方便设置为点击打开的 app 例如各种应用, 小程序或者捷径, 这个的 widget 不需要额外安装加密货币交易所 app, 还可以显示今天是不是周五

使用很简单

  1. 添加到 Scriptable 和 Home,
  2. 编辑 widget, 选择对应的 js
  3. 在 Parameter 填入三个你想跟踪的币种, 以英文逗号间隔, BTC,ETH,SOL

完整代码 需要代理:

// Date
function friday() {
  let day = new Date().getDay();
  log(new Date())
  if (day === 5) {
    return true;
  } else {
    return false;
  }
}

// Widget
function coinWidget() {
  let widget = new ListWidget();
  widget.backgroundColor = Color.black();
  // Format
  let row = widget.addStack();
  row.layoutHorizontally();
  let column = widget.addStack();
  column.layoutVertically();

  row.addSpacer();

  // text1
  let text1 = column.addText(params[0] + ": " + coin1);
  text1.font = Font.semiboldRoundedSystemFont(17);
  text1.textColor = Color.white();
  text1.minimumScaleFactor = 1;

  column.addSpacer();

  // text2
  let text2 = column.addText(params[1] + ": " + coin2);
  text2.font = Font.semiboldRoundedSystemFont(17);
  text2.textColor = Color.white();
  text2.minimumScaleFactor = 1;

  column.addSpacer();

  // text3
  let text3 = column.addText(params[2] + ": " + coin3);
  text3.font = Font.semiboldRoundedSystemFont(17);
  text3.textColor = Color.white();
  text3.minimumScaleFactor = 1;

  column.addSpacer();

  // Friday
  if (friday()) {
    let answer = row.addText("yuh.l!");
    answer.font = Font.regularRoundedSystemFont(23);
    answer.textColor = Color.orange();
  } else {
    let answer = row.addText("huh.");
    answer.font = Font.regularRoundedSystemFont(23);
    answer.textColor = Color.white();
  }

  return widget;
}

// Set Coin
let params = null;
// Parameters
if (args.widgetParameter == null) {
  params = ["BTC", "ETH", "SOL"]; // Default
} else {
  params = args.widgetParameter.split(",");
  console.log(params);
}

// Request data
const url1 = "https://api.coinbase.com/v2/prices/" + params[0] + "-usd/spot";
const req1 = new Request(url1);
const res1 = await req1.loadJSON();
const coin1 = res1.data.amount;

const url2 = "https://api.coinbase.com/v2/prices/" + params[1] + "-usd/spot";
const req2 = new Request(url2);
const res2 = await req2.loadJSON();
const coin2 = res2.data.amount;

const url3 = "https://api.coinbase.com/v2/prices/" + params[2] + "-usd/spot";
const req3 = new Request(url3);
const res3 = await req3.loadJSON();
const coin3 = res3.data.amount;

let widget = coinWidget(coin1, coin2, coin3, params[0], params[1], params[2]);

widget.presentMedium();

Script.complete();