はじめに
(補足)Scriptableは、JavaScriptというプログラム言語でiPhoneのウィジェットを作れる無料アプリです。きっかけは、Xで見かけた自作ウィジェットの投稿でした。結論を先に言うと、コードは1行も自分で書かずに、ウィジェットが6個できました。
作ったウィジェット6個
1. 週間カレンダー(毎日使用中)
今日から7日分の予定を、日付ごとに並べて表示します。予定はiPhone本体のカレンダーから直接読むので、Googleカレンダーに予定を入れればそのまま反映されます。これが一番欲しかったもので、今は毎朝これで1週間を確認しています。
[スクリーンショットをここに入れる]
2. 金価格(3か月チャートつき)
金の価格(ドル建て)と前日比、過去3か月の値動きチャート、円換算のグラム単価までを1枚に表示します。価格データはYahoo Financeから無料で取得していて、APIキーも登録も不要です。
[スクリーンショットをここに入れる]
3. 現在地の天気
今いる場所の天気を表示します。旅行や出張のときも、その土地の天気がそのまま出ます。
4. 仕事の状況
仕事で使っている「発送待ちの件数」と「評価待ちの件数」を表示します。裏側ではAIが毎朝データを更新していて、ウィジェットはそれを読みにいく仕組みです。個人の予定だけでなく、仕事の数字もホーム画面に出せる例として作りました。
5. 今日の予定とToDo
今日の残りの予定と、期限が来ているリマインダーをまとめて表示します。期限を過ぎたものは赤字になるので、やり忘れに気づけます。
6. ゴミ出し
曜日ごとのゴミ出しルールを表示します。収集日は地域ごとに違うので、コードの先頭にあるルール表を自分の地域に合わせて書き換える形式にしています。
作り方の全体像(3ステップ)
- AIに「こんなウィジェットが欲しい」と言葉で頼む
- 返ってきたコードをScriptableアプリに貼り付ける
- ホーム画面にウィジェットとして置く
Scriptableの設置は、アプリを開いて右上の「+」で新しいスクリプトを作り、コードを貼って名前を付けるだけです。あとはホーム画面を長押ししてScriptableのウィジェットを追加し、作ったスクリプトを選べば表示されます。
……と、ここまでは順調だったのですが、僕はこの「あとは置くだけ」のところでやらかしました。
(実行して許可したら、無事に表示されました)
頼み方のコツ
詰まったところ3つ
Googleカレンダーの予定が出てこない
更新はリアルタイムではない
AIの残量表示は、別のやり方でできた
コピペで使えるコード
実際に使っているコードを2つ公開します。Scriptableに貼るだけで動きます。貼ったらまず一度「▶」で実行——ここだけ忘れないでください(僕の失敗談の通りです)。
週間カレンダーのコード
// ============================================================
// 週間カレンダー ウィジェット(Scriptable用)v3
// 「今週の予定」専用(小サイズ前提のスッキリ版)。
// 「今日やること」は別ウィジェット(scriptable_today_todo.js)に分離。
//
// ・予定はiPhone本体のカレンダーから直接読むので、
// リンク共有や再承認なしで常に最新の状態が表示されます
// ・小サイズでは1日1行(最初の予定+件数)に凝縮して表示し、
// 中・大サイズでは従来どおり1日最大3件まで表示します
//
// 使い方(更新も同じ手順)
// 1. Scriptableを開き、既存の「週間カレンダー」スクリプトの
// 中身を全部この内容に置き換える
// 2. スクリプトを一度実行(▶)する
// → カレンダーへのアクセス許可ダイアログが出たら「許可」
// 3. ホーム画面のウィジェットを「小」サイズで置く
//
// 注意
// ・予定が出ない場合:iPhoneの「設定 → カレンダー → アカウント」に
// Googleアカウントが追加されているか確認してください
// (Appleカレンダーに予定が見えている状態が前提です)
// ・更新タイミングはiOSが決めるため、完全なリアルタイムではありません
// ・複数日にまたがる予定は、開始日の行に表示されます
// ============================================================
const DAYS_TO_SHOW = 7;
const WEEKDAYS = ["日", "月", "火", "水", "木", "金", "土"];
function pad(n) { return String(n).padStart(2, "0"); }
function dayKey(d) {
return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate());
}
function timeLabel(ev) {
if (ev.isAllDay) return "終日";
return pad(ev.startDate.getHours()) + ":" + pad(ev.startDate.getMinutes());
}
async function buildWidget(family) {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const end = new Date(start);
end.setDate(end.getDate() + DAYS_TO_SHOW);
const calendars = await Calendar.forEvents();
const events = await CalendarEvent.between(start, end, calendars);
const byDay = {};
for (const ev of events) {
const k = dayKey(ev.startDate);
if (!byDay[k]) byDay[k] = [];
byDay[k].push(ev);
}
for (const k of Object.keys(byDay)) {
byDay[k].sort((a, b) => a.startDate - b.startDate);
}
const small = family === "small";
const w = new ListWidget();
w.backgroundColor = new Color("#ffffff");
w.setPadding(small ? 8 : 10, small ? 10 : 12, small ? 8 : 10, small ? 10 : 12);
const title = w.addText("今週の予定");
title.font = Font.boldSystemFont(small ? 11 : 12);
title.textColor = new Color("#111111");
w.addSpacer(small ? 4 : 6);
for (let i = 0; i < DAYS_TO_SHOW; i++) {
const d = new Date(start);
d.setDate(d.getDate() + i);
const isToday = i === 0;
const dayEvents = byDay[dayKey(d)] || [];
const row = w.addStack();
row.layoutHorizontally();
const dateText = row.addText((d.getMonth() + 1) + "/" + d.getDate() + "(" + WEEKDAYS[d.getDay()] + ")");
dateText.font = isToday ? Font.boldSystemFont(small ? 10 : 11) : Font.systemFont(small ? 10 : 11);
dateText.textColor = isToday ? new Color("#d70015") : new Color("#333333");
row.addSpacer(6);
if (small) {
// 小サイズ: 最初の予定を1行だけ+残り件数
if (dayEvents.length === 0) {
const none = row.addText("予定なし");
none.font = Font.systemFont(10);
none.textColor = new Color("#999999");
} else {
const first = dayEvents[0];
let label = timeLabel(first) + " " + first.title;
if (dayEvents.length > 1) label += " +" + (dayEvents.length - 1);
const line = row.addText(label);
line.font = Font.systemFont(10);
line.textColor = new Color("#111111");
line.lineLimit = 1;
}
} else {
if (dayEvents.length === 0) {
const none = row.addText("予定なし");
none.font = Font.systemFont(11);
none.textColor = new Color("#999999");
} else {
const col = row.addStack();
col.layoutVertically();
for (const ev of dayEvents.slice(0, 3)) {
const line = col.addText(timeLabel(ev) + " " + ev.title);
line.font = Font.systemFont(11);
line.textColor = new Color("#111111");
line.lineLimit = 1;
}
if (dayEvents.length > 3) {
const more = col.addText("ほか" + (dayEvents.length - 3) + "件");
more.font = Font.systemFont(10);
more.textColor = new Color("#999999");
}
}
}
if (i < DAYS_TO_SHOW - 1) w.addSpacer(small ? 3 : 4);
}
w.url = "calshow:";
w.refreshAfterDate = new Date(Date.now() + 30 * 60 * 1000);
return w;
}
const family = config.widgetFamily || "small";
const widget = await buildWidget(family);
if (config.runsInWidget) {
Script.setWidget(widget);
} else if (family === "medium") {
widget.presentMedium();
} else if (family === "large") {
widget.presentLarge();
} else {
widget.presentSmall();
}
Script.complete();
金価格ウィジェットのコード
価格・前日比・3か月チャート・円換算まで出す、少し本格的なものです。コードは長いので、要点だけ先に書きます。
- 価格とチャートはYahoo Finance(金先物)から取得。APIキー不要
- 取得に失敗したときの予備ルートと、前回値の保存つき
- 円/g換算はドル円レートから自動計算
// ============================================================
// 金価格(GOLD)ウィジェット for Scriptable
// ------------------------------------------------------------
// ・価格と過去3ヶ月の日足チャートを Yahoo Finance(金先物 GC=F)
// から取得(キー不要)。前日比もここから計算する
// ・取得できないときは gold-api.com のスポット価格+端末内に
// 記録した前日終値で代替表示する
// ・円/g換算は open.er-api.com のドル円(日次)で計算
// ・更新間隔はiOS側の制御(目安15〜60分)
// ・価格は参考値(先物価格ベース)
//
// 使い方: Scriptableで新規スクリプトを作り、この内容を貼り付けて
// 名前を「金価格」にして1回実行 → ホーム画面のウィジェットから選択
// ============================================================
const YAHOO_URL = "https://query1.finance.yahoo.com/v8/finance/chart/GC=F?range=3mo&interval=1d";
const GOLDAPI_URL = "https://api.gold-api.com/price/XAU";
const FX_URL = "https://open.er-api.com/v6/latest/USD";
const TROY_OZ_G = 31.1034768;
const fm = FileManager.local();
const cachePath = fm.joinPath(fm.documentsDirectory(), "gold-cache.json");
function loadCache() {
try { if (fm.fileExists(cachePath)) return JSON.parse(fm.readString(cachePath));} catch (e) {}
return {};
}
function saveCache(c) { try { fm.writeString(cachePath, JSON.stringify(c));} catch (e) {}}
function dayStr(d) {
const p = (n) => String(n).padStart(2, "0");
return d.getFullYear() + "-" + p(d.getMonth() + 1) + "-" + p(d.getDate());
}
function fmt(n, digits) {
const parts = n.toFixed(digits).split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
async function fetchJSON(url) {
const req = new Request(url);
req.timeoutInterval = 15;
req.headers = { "User-Agent": "Mozilla/5.0"};
return await req.loadJSON();
}
const now = new Date();
const today = dayStr(now);
const cache = loadCache();
let price = null, prevClose = null, closes = [], jpy = null, stale = false;
// --- Yahoo(価格・前日終値・チャート) ---
try {
const d = await fetchJSON(YAHOO_URL);
const r = d.chart.result[0];
price = r.meta.regularMarketPrice;
const raw = r.indicators.quote[0].close || [];
closes = raw.filter((c) => c!= null);
if (closes.length >= 2) prevClose = closes[closes.length - 2];
} catch (e) {}
// --- 代替:gold-apiスポット ---
if (price == null) {
try {
const g = await fetchJSON(GOLDAPI_URL);
if (g && g.price) price = g.price;
} catch (e) {}
}
if (price == null && cache.lastPrice) { price = cache.lastPrice; stale = true;}
// --- ドル円 ---
try {
const f = await fetchJSON(FX_URL);
if (f && f.rates && f.rates.JPY) jpy = f.rates.JPY;
} catch (e) {}
if (jpy == null && cache.lastJpy) jpy = cache.lastJpy;
// --- キャッシュ(代替経路用の前日終値づくり) ---
if (price!= null) {
if (cache.todayDate!== today) {
if (cache.lastPrice) cache.prevClose = cache.lastPrice;
cache.todayDate = today;
}
cache.lastPrice = price;
if (jpy) cache.lastJpy = jpy;
saveCache(cache);
}
if (prevClose == null && cache.prevClose && cache.todayDate === today) prevClose = cache.prevClose;
// ---------- チャート描画 ----------
function drawChart(values, upColor) {
const W = 640, H = 124, PAD = 8;
const dc = new DrawContext();
dc.size = new Size(W, H);
dc.opaque = false;
dc.respectScreenScale = true;
if (values.length < 2) return null;
const min = Math.min.apply(null, values);
const max = Math.max.apply(null, values);
const span = (max - min) || 1;
const x = (i) => PAD + (W - 2 * PAD) * i / (values.length - 1);
const y = (v) => H - PAD - (H - 2 * PAD) * (v - min) / span;
// 塗り(下側)
const fill = new Path();
fill.move(new Point(x(0), H - PAD));
values.forEach((v, i) => fill.addLine(new Point(x(i), y(v))));
fill.addLine(new Point(x(values.length - 1), H - PAD));
fill.closeSubpath();
dc.addPath(fill);
dc.setFillColor(new Color(upColor.hex, 0.15));
dc.fillPath();
// 線
const line = new Path();
values.forEach((v, i) => {
if (i === 0) line.move(new Point(x(i), y(v)));
else line.addLine(new Point(x(i), y(v)));
});
dc.addPath(line);
dc.setStrokeColor(upColor);
dc.setLineWidth(3);
dc.strokePath();
// 最終点
const lx = x(values.length - 1), ly = y(values[values.length - 1]);
dc.setFillColor(upColor);
dc.fillEllipse(new Rect(lx - 6, ly - 6, 12, 12));
return dc.getImage();
}
// ---------- 表示 ----------
const w = new ListWidget();
w.setPadding(10, 14, 10, 14);
const head = w.addStack();
head.centerAlignContent();
const title = head.addText("GOLD 金価格(3ヶ月)");
title.font = Font.boldSystemFont(12);
title.textColor = new Color("#8a6d1f");
head.addSpacer();
const upd = head.addText(stale? "前回取得分": "更新 " + now.toLocaleTimeString("ja-JP", { hour: "2-digit", minute: "2-digit"}));
upd.font = Font.systemFont(10);
upd.textColor = Color.gray();
w.addSpacer(2);
if (price == null) {
const t = w.addText("価格を取得できませんでした");
t.font = Font.systemFont(14);
t.textColor = Color.red();
} else {
const row = w.addStack();
row.centerAlignContent();
const p = row.addText("$" + fmt(price, 2));
p.font = Font.boldSystemFont(24);
row.addSpacer(12);
if (prevClose) {
const pct = (price / prevClose - 1) * 100;
const up = pct > 0.05, down = pct < -0.05;
const arrow = up? "▲": (down? "▼": "―");
const label = up? "上げ相場": (down? "下げ相場": "横ばい");
const color = up? new Color("#1a7f37"): (down? new Color("#cf222e"): Color.gray());
const line = row.addText(arrow + " " + label + " " + (pct >= 0? "+": "") + pct.toFixed(2) + "%");
line.font = Font.boldSystemFont(15);
line.textColor = color;
} else {
const note = row.addText("前日比は記録中");
note.font = Font.systemFont(12);
note.textColor = Color.gray();
}
// チャート+フッター(高値・安値・円換算を1行に)
if (closes.length >= 2) {
const periodUp = closes[closes.length - 1] >= closes[0];
const col = periodUp? new Color("#1a7f37"): new Color("#cf222e");
const img = drawChart(closes, col);
if (img) {
w.addSpacer(2);
const iw = w.addImage(img);
iw.imageSize = new Size(320, 62);
iw.centerAlignImage();
}
const min = Math.min.apply(null, closes), max = Math.max.apply(null, closes);
let foot = "高値 $" + fmt(max, 0) + " / 安値 $" + fmt(min, 0);
if (jpy) {
const perG = price * jpy / TROY_OZ_G;
foot += " ・ ¥" + fmt(perG, 0) + "/g";
}
const range = w.addText(foot);
range.font = Font.systemFont(10);
range.textColor = Color.gray();
} else if (jpy) {
const perG = price * jpy / TROY_OZ_G;
const yen = w.addText("円換算 約 ¥" + fmt(perG, 0) + " /g(ドル円 " + fmt(jpy, 1) + ")");
yen.font = Font.systemFont(11);
yen.textColor = Color.gray();
}
}
w.refreshAfterDate = new Date(now.getTime() + 30 * 60 * 1000);
if (config.runsInWidget) {
Script.setWidget(w);
} else {
w.presentMedium();
}
Script.complete();
まとめ
次は、LINEの未読をAIに読ませて毎朝のまとめに入れた話を書く予定です。
