Created
February 8, 2025 08:38
-
-
Save yung8118/911bbcb436c583fae86a6f5a8642d1f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### 📝 正确代码内容 | |
```javascript | |
// 油价查询小组件 for Scriptable | |
// API来自天行数据,需自行替换有效API密钥 | |
// 配置项 | |
const API_KEY = '0d86b1d5c8d616c329e953a1907d7fd5'; // 替换为你的天行API密钥 | |
const PROVINCE = '北京'; // 查询省份 | |
const UPDATE_INTERVAL = 2; // 自动刷新间隔(小时) | |
async function getOilPrice() { | |
const url = `https://apis.tianapi.com/oilprice/index?key=${API_KEY}&prov=${encodeURIComponent(PROVINCE)}`; | |
const request = new Request(url); | |
try { | |
const response = await request.loadJSON(); | |
if (response.code === 200) return response.result; | |
throw new Error(response.msg || '请求失败'); | |
} catch (error) { | |
console.error('API错误: ' + error); | |
return null; | |
} | |
} | |
function createWidgetUI(data) { | |
const widget = new ListWidget(); | |
widget.backgroundColor = new Color('#1c1c1e'); | |
// 标题 | |
const title = widget.addText(`⛽️ ${PROVINCE}油价`); | |
title.textColor = Color.orange(); | |
title.font = Font.boldSystemFont(16); | |
widget.addSpacer(8); | |
// 油价数据 | |
if (data?.list) { | |
data.list.forEach(item => { | |
const row = widget.addStack(); | |
row.layoutHorizontally(); | |
const type = row.addText(item.type); | |
type.textColor = Color.white(); | |
type.font = Font.mediumSystemFont(14); | |
row.addSpacer(); | |
const price = row.addText(item.price); | |
price.textColor = Color.green(); | |
price.font = Font.boldSystemFont(14); | |
widget.addSpacer(6); | |
}); | |
} else { | |
widget.addText('⚠️ 数据加载失败').textColor = Color.red(); | |
} | |
// 更新时间 | |
widget.addSpacer(); | |
const time = widget.addText(`更新: ${new Date().toLocaleTimeString()}`); | |
time.textColor = Color.gray(); | |
time.font = Font.smallSystemFont(10); | |
return widget; | |
} | |
async function run() { | |
let data; | |
if (config.runsInWidget) { | |
data = await getOilPrice(); | |
} else { // 预览模式测试数据 | |
data = { | |
list: [ | |
{ type: "92号汽油", price: "7.50元/升" }, | |
{ type: "95号汽油", price: "8.00元/升" }, | |
{ type: "98号汽油", price: "9.50元/升" }, | |
{ type: "0号柴油", price: "7.20元/升" } | |
] | |
}; | |
} | |
const widget = createWidgetUI(data); | |
if (config.runsInWidget) { | |
widget.refreshAfterDate = new Date(Date.now() + UPDATE_INTERVAL*3600*1000); | |
} | |
Script.setWidget(widget); | |
Script.complete(); | |
} | |
await run(); | |
``` | |
--- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment