koishi-plugin-rina-currency 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/chart.d.ts +8 -0
- package/lib/commands.d.ts +4 -0
- package/lib/config.d.ts +33 -0
- package/lib/formatter.d.ts +9 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.js +732 -0
- package/lib/model.d.ts +28 -0
- package/lib/providers/boc.d.ts +10 -0
- package/lib/providers/common.d.ts +10 -0
- package/lib/providers/icbc.d.ts +23 -0
- package/lib/scheduler.d.ts +17 -0
- package/lib/service.d.ts +26 -0
- package/lib/types.d.ts +26 -0
- package/package.json +41 -0
- package/readme.md +74 -0
package/lib/chart.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { RateType, TrendMetrics } from './types';
|
|
2
|
+
export interface ChartOptions {
|
|
3
|
+
width: number;
|
|
4
|
+
height: number;
|
|
5
|
+
days: number;
|
|
6
|
+
}
|
|
7
|
+
/** Renders a compact, decision-focused trend card. */
|
|
8
|
+
export declare function renderTrendChart(metrics: TrendMetrics, rateType: RateType, options: ChartOptions): Promise<Buffer<ArrayBufferLike>>;
|
package/lib/config.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Schema } from 'koishi';
|
|
2
|
+
import { BankId, RateType } from './types';
|
|
3
|
+
export interface BroadcastTarget {
|
|
4
|
+
enabled: boolean;
|
|
5
|
+
platform: string;
|
|
6
|
+
selfId: string;
|
|
7
|
+
channelId: string;
|
|
8
|
+
hour: number;
|
|
9
|
+
minute: number;
|
|
10
|
+
includeChart: boolean;
|
|
11
|
+
chartDays: number;
|
|
12
|
+
}
|
|
13
|
+
export interface ThresholdAlert {
|
|
14
|
+
enabled: boolean;
|
|
15
|
+
bank: BankId;
|
|
16
|
+
rateType: RateType;
|
|
17
|
+
changePercent: number;
|
|
18
|
+
platform: string;
|
|
19
|
+
selfId: string;
|
|
20
|
+
channelId: string;
|
|
21
|
+
}
|
|
22
|
+
export interface Config {
|
|
23
|
+
defaultBank: BankId;
|
|
24
|
+
defaultRateType: RateType;
|
|
25
|
+
requestTimeout: number;
|
|
26
|
+
collectIntervalMinutes: number;
|
|
27
|
+
collectOnStart: boolean;
|
|
28
|
+
chartWidth: number;
|
|
29
|
+
chartHeight: number;
|
|
30
|
+
broadcasts: BroadcastTarget[];
|
|
31
|
+
thresholdAlerts: ThresholdAlert[];
|
|
32
|
+
}
|
|
33
|
+
export declare const Config: Schema<Config>;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { BankId, ExchangeRateQuote, RateType, TrendMetrics } from './types';
|
|
2
|
+
export declare function formatRate(value: number): string;
|
|
3
|
+
export declare function formatDateTime(value: Date): string;
|
|
4
|
+
export declare function costForYen(amount: number, quote: ExchangeRateQuote, type?: RateType): number;
|
|
5
|
+
export declare function formatMoney(value: number): string;
|
|
6
|
+
export declare function formatDetailed(quote: ExchangeRateQuote): string;
|
|
7
|
+
export declare function formatSnapshot(snapshot: Partial<Record<BankId, ExchangeRateQuote>>, defaultBank: BankId, rateType: RateType): string;
|
|
8
|
+
export declare function formatCost(amount: number, quote: ExchangeRateQuote, type: RateType): string;
|
|
9
|
+
export declare function formatTrendSummary(bank: BankId, type: RateType, metrics: TrendMetrics, days: number): string;
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { Config as ConfigSchema, Config as PluginConfig } from './config';
|
|
3
|
+
export declare const name = "rina-currency";
|
|
4
|
+
export declare const inject: string[];
|
|
5
|
+
export type Config = PluginConfig;
|
|
6
|
+
export declare const Config: import("schemastery")<ConfigSchema>;
|
|
7
|
+
export declare function apply(ctx: Context, config: Config): void;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name2 in all)
|
|
10
|
+
__defProp(target, name2, { get: all[name2], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
Config: () => Config2,
|
|
34
|
+
apply: () => apply,
|
|
35
|
+
inject: () => inject,
|
|
36
|
+
name: () => name
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(src_exports);
|
|
39
|
+
|
|
40
|
+
// src/config.ts
|
|
41
|
+
var import_koishi = require("koishi");
|
|
42
|
+
var BankSchema = import_koishi.Schema.union([
|
|
43
|
+
import_koishi.Schema.const("boc").description("中国银行"),
|
|
44
|
+
import_koishi.Schema.const("icbc").description("中国工商银行")
|
|
45
|
+
]);
|
|
46
|
+
var RateTypeSchema = import_koishi.Schema.union([
|
|
47
|
+
import_koishi.Schema.const("spotSell").description("现汇卖出价(推荐默认)"),
|
|
48
|
+
import_koishi.Schema.const("cashSell").description("现钞卖出价"),
|
|
49
|
+
import_koishi.Schema.const("spotBuy").description("现汇买入价"),
|
|
50
|
+
import_koishi.Schema.const("cashBuy").description("现钞买入价")
|
|
51
|
+
]);
|
|
52
|
+
var BroadcastSchema = import_koishi.Schema.object({
|
|
53
|
+
enabled: import_koishi.Schema.boolean().default(true).description("启用这条播报规则"),
|
|
54
|
+
platform: import_koishi.Schema.string().required().description("平台名称,例如 onebot、qq、telegram"),
|
|
55
|
+
selfId: import_koishi.Schema.string().required().description("用于发送的机器人账号 ID"),
|
|
56
|
+
channelId: import_koishi.Schema.string().required().description("目标频道或群组 ID"),
|
|
57
|
+
hour: import_koishi.Schema.number().min(0).max(23).default(9).description("北京时间小时"),
|
|
58
|
+
minute: import_koishi.Schema.number().min(0).max(59).default(0).description("北京时间分钟"),
|
|
59
|
+
includeChart: import_koishi.Schema.boolean().default(true).description("附上趋势图"),
|
|
60
|
+
chartDays: import_koishi.Schema.number().min(1).max(365).default(7).description("趋势图天数")
|
|
61
|
+
});
|
|
62
|
+
var ThresholdSchema = import_koishi.Schema.object({
|
|
63
|
+
enabled: import_koishi.Schema.boolean().default(true).description("启用这条提醒规则"),
|
|
64
|
+
bank: BankSchema.default("boc"),
|
|
65
|
+
rateType: RateTypeSchema.default("spotSell"),
|
|
66
|
+
changePercent: import_koishi.Schema.number().min(0.01).max(100).required().description("相邻采样点的绝对涨跌幅达到此百分比时提醒,例如 0.5 表示上涨或下跌 0.5%"),
|
|
67
|
+
platform: import_koishi.Schema.string().required().description("平台名称"),
|
|
68
|
+
selfId: import_koishi.Schema.string().required().description("机器人账号 ID"),
|
|
69
|
+
channelId: import_koishi.Schema.string().required().description("目标频道或群组 ID")
|
|
70
|
+
});
|
|
71
|
+
var Config = import_koishi.Schema.object({
|
|
72
|
+
defaultBank: BankSchema.default("boc").description("购汇成本与单银行趋势的默认参考银行"),
|
|
73
|
+
defaultRateType: RateTypeSchema.default("spotSell").description("默认牌价类型"),
|
|
74
|
+
requestTimeout: import_koishi.Schema.number().min(1e3).max(6e4).default(15e3).description("银行接口请求超时(毫秒)"),
|
|
75
|
+
collectIntervalMinutes: import_koishi.Schema.number().min(10).max(1440).default(60).description("牌价采集间隔(分钟)"),
|
|
76
|
+
collectOnStart: import_koishi.Schema.boolean().default(true).description("插件启动后立即采集一次"),
|
|
77
|
+
chartWidth: import_koishi.Schema.number().min(600).max(2e3).default(1200).description("趋势图宽度"),
|
|
78
|
+
chartHeight: import_koishi.Schema.number().min(360).max(1200).default(680).description("趋势图高度"),
|
|
79
|
+
broadcasts: import_koishi.Schema.array(BroadcastSchema).default([]).description("每日定时播报目标"),
|
|
80
|
+
thresholdAlerts: import_koishi.Schema.array(ThresholdSchema).default([]).description("跌破阈值提醒规则")
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// src/commands.ts
|
|
84
|
+
var import_koishi2 = require("koishi");
|
|
85
|
+
|
|
86
|
+
// src/chart.ts
|
|
87
|
+
var import_sharp = __toESM(require("sharp"));
|
|
88
|
+
|
|
89
|
+
// src/types.ts
|
|
90
|
+
var BANK_LABELS = {
|
|
91
|
+
boc: "中国银行",
|
|
92
|
+
icbc: "中国工商银行"
|
|
93
|
+
};
|
|
94
|
+
var RATE_TYPE_LABELS = {
|
|
95
|
+
spotBuy: "现汇买入价",
|
|
96
|
+
cashBuy: "现钞买入价",
|
|
97
|
+
spotSell: "现汇卖出价",
|
|
98
|
+
cashSell: "现钞卖出价"
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// src/formatter.ts
|
|
102
|
+
var chinaDateTime = new Intl.DateTimeFormat("zh-CN", {
|
|
103
|
+
timeZone: "Asia/Shanghai",
|
|
104
|
+
year: "numeric",
|
|
105
|
+
month: "2-digit",
|
|
106
|
+
day: "2-digit",
|
|
107
|
+
hour: "2-digit",
|
|
108
|
+
minute: "2-digit",
|
|
109
|
+
hour12: false
|
|
110
|
+
});
|
|
111
|
+
function formatRate(value) {
|
|
112
|
+
return value.toFixed(4);
|
|
113
|
+
}
|
|
114
|
+
__name(formatRate, "formatRate");
|
|
115
|
+
function formatDateTime(value) {
|
|
116
|
+
return chinaDateTime.format(value).replace(/\//g, "-");
|
|
117
|
+
}
|
|
118
|
+
__name(formatDateTime, "formatDateTime");
|
|
119
|
+
function costForYen(amount, quote, type = "spotSell") {
|
|
120
|
+
return amount * quote[type] / quote.unit;
|
|
121
|
+
}
|
|
122
|
+
__name(costForYen, "costForYen");
|
|
123
|
+
function formatMoney(value) {
|
|
124
|
+
return value.toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
|
125
|
+
}
|
|
126
|
+
__name(formatMoney, "formatMoney");
|
|
127
|
+
function formatDetailed(quote) {
|
|
128
|
+
return [
|
|
129
|
+
`【${BANK_LABELS[quote.bank]} 日元牌价】`,
|
|
130
|
+
`现汇买入:${formatRate(quote.spotBuy)}`,
|
|
131
|
+
`现钞买入:${formatRate(quote.cashBuy)}`,
|
|
132
|
+
`现汇卖出:${formatRate(quote.spotSell)}`,
|
|
133
|
+
`现钞卖出:${formatRate(quote.cashSell)}`,
|
|
134
|
+
`牌价时间:${formatDateTime(quote.publishedAt)}`,
|
|
135
|
+
`单位:100 JPY / CNY`
|
|
136
|
+
].join("\n");
|
|
137
|
+
}
|
|
138
|
+
__name(formatDetailed, "formatDetailed");
|
|
139
|
+
function formatSnapshot(snapshot, defaultBank, rateType) {
|
|
140
|
+
const lines = [
|
|
141
|
+
"【日元汇率】",
|
|
142
|
+
`主参考:${RATE_TYPE_LABELS[rateType]}(100 JPY / CNY)`,
|
|
143
|
+
""
|
|
144
|
+
];
|
|
145
|
+
for (const bank of ["boc", "icbc"]) {
|
|
146
|
+
const quote = snapshot[bank];
|
|
147
|
+
if (quote) lines.push(`${BANK_LABELS[bank]}:${RATE_TYPE_LABELS[rateType]} ${formatRate(quote[rateType])}`);
|
|
148
|
+
}
|
|
149
|
+
const reference = snapshot[defaultBank];
|
|
150
|
+
if (reference) {
|
|
151
|
+
lines.push("", `按${BANK_LABELS[defaultBank]}估算:`);
|
|
152
|
+
lines.push(`10,000 JPY ≈ ${formatMoney(costForYen(1e4, reference, rateType))} CNY`);
|
|
153
|
+
lines.push(`50,000 JPY ≈ ${formatMoney(costForYen(5e4, reference, rateType))} CNY`);
|
|
154
|
+
lines.push(`牌价时间:${formatDateTime(reference.publishedAt)}`);
|
|
155
|
+
}
|
|
156
|
+
const boc = snapshot.boc;
|
|
157
|
+
const icbc = snapshot.icbc;
|
|
158
|
+
if (boc && icbc) {
|
|
159
|
+
const difference = icbc[rateType] - boc[rateType];
|
|
160
|
+
const sign = difference >= 0 ? "+" : "";
|
|
161
|
+
lines.push(`工行较中行:${sign}${formatRate(difference)}(购汇 100,000 JPY 约${difference >= 0 ? "多" : "少"} ${formatMoney(Math.abs(difference) * 1e3)} CNY)`);
|
|
162
|
+
}
|
|
163
|
+
lines.push("数据来源:中国银行、工商银行;实际成交以银行渠道为准。");
|
|
164
|
+
return lines.join("\n");
|
|
165
|
+
}
|
|
166
|
+
__name(formatSnapshot, "formatSnapshot");
|
|
167
|
+
function formatCost(amount, quote, type) {
|
|
168
|
+
return [
|
|
169
|
+
"【购汇成本参考】",
|
|
170
|
+
`按${BANK_LABELS[quote.bank]}${RATE_TYPE_LABELS[type]}计算:`,
|
|
171
|
+
`${amount.toLocaleString("zh-CN")} JPY ≈ ${formatMoney(costForYen(amount, quote, type))} CNY`,
|
|
172
|
+
`牌价:100 JPY = ${formatRate(quote[type])} CNY`,
|
|
173
|
+
`牌价时间:${formatDateTime(quote.publishedAt)}`,
|
|
174
|
+
"实际成交以银行渠道为准。"
|
|
175
|
+
].join("\n");
|
|
176
|
+
}
|
|
177
|
+
__name(formatCost, "formatCost");
|
|
178
|
+
function formatTrendSummary(bank, type, metrics, days) {
|
|
179
|
+
const change = metrics.change == null ? "暂无足够的前一日数据" : `${metrics.change >= 0 ? "+" : ""}${formatRate(metrics.change)}(${metrics.changePercent >= 0 ? "+" : ""}${metrics.changePercent.toFixed(2)}%)`;
|
|
180
|
+
return [
|
|
181
|
+
`【${BANK_LABELS[bank]} 日元${RATE_TYPE_LABELS[type]}趋势】`,
|
|
182
|
+
`当前:${formatRate(metrics.latest[type])}`,
|
|
183
|
+
`较约 24 小时前:${change}`,
|
|
184
|
+
`近 ${days} 天最高:${formatRate(metrics.high)}`,
|
|
185
|
+
`近 ${days} 天最低:${formatRate(metrics.low)}`,
|
|
186
|
+
`10,000 JPY 参考成本:${formatMoney(costForYen(1e4, metrics.latest, type))} CNY`,
|
|
187
|
+
`牌价时间:${formatDateTime(metrics.latest.publishedAt)}`
|
|
188
|
+
].join("\n");
|
|
189
|
+
}
|
|
190
|
+
__name(formatTrendSummary, "formatTrendSummary");
|
|
191
|
+
|
|
192
|
+
// src/chart.ts
|
|
193
|
+
function escapeXml(value) {
|
|
194
|
+
return value.replace(/[&<>'"]/g, (character) => ({
|
|
195
|
+
"&": "&",
|
|
196
|
+
"<": "<",
|
|
197
|
+
">": ">",
|
|
198
|
+
"'": "'",
|
|
199
|
+
'"': """
|
|
200
|
+
})[character]);
|
|
201
|
+
}
|
|
202
|
+
__name(escapeXml, "escapeXml");
|
|
203
|
+
function dateLabel(value) {
|
|
204
|
+
return new Intl.DateTimeFormat("zh-CN", {
|
|
205
|
+
timeZone: "Asia/Shanghai",
|
|
206
|
+
month: "2-digit",
|
|
207
|
+
day: "2-digit"
|
|
208
|
+
}).format(value);
|
|
209
|
+
}
|
|
210
|
+
__name(dateLabel, "dateLabel");
|
|
211
|
+
async function renderTrendChart(metrics, rateType, options) {
|
|
212
|
+
const { width, height } = options;
|
|
213
|
+
const padding = { top: 184, right: 72, bottom: 76, left: 88 };
|
|
214
|
+
const plotWidth = width - padding.left - padding.right;
|
|
215
|
+
const plotHeight = height - padding.top - padding.bottom;
|
|
216
|
+
const values = metrics.points.map((point) => point[rateType]);
|
|
217
|
+
const min = Math.min(...values);
|
|
218
|
+
const max = Math.max(...values);
|
|
219
|
+
const spread = Math.max(max - min, Math.max(max, 1) * 2e-3);
|
|
220
|
+
const lower = min - spread * 0.14;
|
|
221
|
+
const upper = max + spread * 0.14;
|
|
222
|
+
const range = upper - lower;
|
|
223
|
+
const firstTime = metrics.points[0].publishedAt.getTime();
|
|
224
|
+
const lastTime = metrics.latest.publishedAt.getTime();
|
|
225
|
+
const timeRange = Math.max(lastTime - firstTime, 1);
|
|
226
|
+
const xFor = /* @__PURE__ */ __name((time) => padding.left + (time - firstTime) / timeRange * plotWidth, "xFor");
|
|
227
|
+
const yFor = /* @__PURE__ */ __name((value) => padding.top + (upper - value) / range * plotHeight, "yFor");
|
|
228
|
+
const coordinates = metrics.points.map((point) => `${xFor(point.publishedAt.getTime()).toFixed(1)},${yFor(point[rateType]).toFixed(1)}`).join(" ");
|
|
229
|
+
const latestX = xFor(metrics.latest.publishedAt.getTime());
|
|
230
|
+
const latestY = yFor(metrics.latest[rateType]);
|
|
231
|
+
const highPoint = metrics.points.reduce((best, point) => point[rateType] > best[rateType] ? point : best);
|
|
232
|
+
const lowPoint = metrics.points.reduce((best, point) => point[rateType] < best[rateType] ? point : best);
|
|
233
|
+
const highX = xFor(highPoint.publishedAt.getTime());
|
|
234
|
+
const highY = yFor(highPoint[rateType]);
|
|
235
|
+
const lowX = xFor(lowPoint.publishedAt.getTime());
|
|
236
|
+
const lowY = yFor(lowPoint[rateType]);
|
|
237
|
+
const change = metrics.change == null ? "暂无前日数据" : `${metrics.change >= 0 ? "+" : ""}${formatRate(metrics.change)} ${metrics.changePercent >= 0 ? "+" : ""}${metrics.changePercent.toFixed(2)}%`;
|
|
238
|
+
const changeColor = metrics.change == null ? "#94a3b8" : metrics.change > 0 ? "#fb7185" : "#34d399";
|
|
239
|
+
const ticks = Array.from({ length: 4 }, (_, index) => lower + (upper - lower) * index / 3);
|
|
240
|
+
const middlePoint = metrics.points[Math.floor(metrics.points.length / 2)];
|
|
241
|
+
const labels = [metrics.points[0], middlePoint, metrics.latest];
|
|
242
|
+
const grid = ticks.map((value) => {
|
|
243
|
+
const y = yFor(value);
|
|
244
|
+
return `<line x1="${padding.left}" x2="${width - padding.right}" y1="${y}" y2="${y}" stroke="#26334a" stroke-width="1" />
|
|
245
|
+
<text x="${padding.left - 14}" y="${y + 5}" text-anchor="end" class="axis">${formatRate(value)}</text>`;
|
|
246
|
+
}).join("");
|
|
247
|
+
const xLabels = labels.map((point, index) => {
|
|
248
|
+
const anchor = index === 0 ? "start" : index === labels.length - 1 ? "end" : "middle";
|
|
249
|
+
return `<text x="${xFor(point.publishedAt.getTime())}" y="${height - 30}" text-anchor="${anchor}" class="axis">${dateLabel(point.publishedAt)}</text>`;
|
|
250
|
+
}).join("");
|
|
251
|
+
const title = `${BANK_LABELS[metrics.latest.bank]} · 日元${RATE_TYPE_LABELS[rateType]}走势`;
|
|
252
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
|
|
253
|
+
<style>
|
|
254
|
+
text { font-family: 'Microsoft YaHei', 'Noto Sans CJK SC', sans-serif; }
|
|
255
|
+
.title { fill: #f8fafc; font-size: 30px; font-weight: 700; }
|
|
256
|
+
.subtitle { fill: #94a3b8; font-size: 16px; }
|
|
257
|
+
.metric-label { fill: #94a3b8; font-size: 15px; }
|
|
258
|
+
.metric-value { fill: #f8fafc; font-size: 27px; font-weight: 700; }
|
|
259
|
+
.axis { fill: #94a3b8; font-size: 13px; }
|
|
260
|
+
.annotation { fill: #dbeafe; font-size: 13px; font-weight: 600; }
|
|
261
|
+
</style>
|
|
262
|
+
<rect width="100%" height="100%" fill="#0f172a" rx="28" />
|
|
263
|
+
<rect x="24" y="24" width="${width - 48}" height="${height - 48}" fill="#111c33" stroke="#24324a" rx="20" />
|
|
264
|
+
<text x="${padding.left}" y="66" class="title">${escapeXml(title)}</text>
|
|
265
|
+
<text x="${padding.left}" y="94" class="subtitle">100 JPY / CNY · 最近 ${options.days} 天 · ${escapeXml(formatDateTime(metrics.latest.publishedAt))}</text>
|
|
266
|
+
|
|
267
|
+
<text x="${padding.left}" y="136" class="metric-label">当前</text>
|
|
268
|
+
<text x="${padding.left}" y="166" class="metric-value">${formatRate(metrics.latest[rateType])}</text>
|
|
269
|
+
<text x="${padding.left + 230}" y="136" class="metric-label">较约 24 小时前</text>
|
|
270
|
+
<text x="${padding.left + 230}" y="166" fill="${changeColor}" class="metric-value">${escapeXml(change)}</text>
|
|
271
|
+
<text x="${width - padding.right}" y="136" text-anchor="end" class="metric-label">10,000 JPY 参考成本</text>
|
|
272
|
+
<text x="${width - padding.right}" y="166" text-anchor="end" class="metric-value">${formatMoney(costForYen(1e4, metrics.latest, rateType))} CNY</text>
|
|
273
|
+
|
|
274
|
+
${grid}
|
|
275
|
+
<polyline points="${coordinates}" fill="none" stroke="#60a5fa" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" />
|
|
276
|
+
<line x1="${latestX}" x2="${latestX}" y1="${padding.top}" y2="${padding.top + plotHeight}" stroke="#60a5fa" stroke-opacity="0.25" stroke-dasharray="5 6" />
|
|
277
|
+
<circle cx="${latestX}" cy="${latestY}" r="6" fill="#dbeafe" stroke="#60a5fa" stroke-width="4" />
|
|
278
|
+
<circle cx="${highX}" cy="${highY}" r="4" fill="#fbbf24" />
|
|
279
|
+
<circle cx="${lowX}" cy="${lowY}" r="4" fill="#34d399" />
|
|
280
|
+
<text x="${Math.min(highX + 10, width - padding.right - 84)}" y="${Math.max(highY - 12, padding.top + 14)}" class="annotation">高 ${formatRate(highPoint[rateType])}</text>
|
|
281
|
+
<text x="${Math.min(lowX + 10, width - padding.right - 84)}" y="${Math.min(lowY + 22, padding.top + plotHeight - 6)}" class="annotation">低 ${formatRate(lowPoint[rateType])}</text>
|
|
282
|
+
<text x="${Math.min(latestX + 12, width - padding.right - 76)}" y="${Math.max(latestY - 14, padding.top + 14)}" class="annotation">当前 ${formatRate(metrics.latest[rateType])}</text>
|
|
283
|
+
${xLabels}
|
|
284
|
+
<text x="${width - padding.right}" y="${height - 30}" text-anchor="end" class="axis">数据来源:中国银行、工商银行</text>
|
|
285
|
+
</svg>`;
|
|
286
|
+
return (0, import_sharp.default)(Buffer.from(svg)).png().toBuffer();
|
|
287
|
+
}
|
|
288
|
+
__name(renderTrendChart, "renderTrendChart");
|
|
289
|
+
|
|
290
|
+
// src/commands.ts
|
|
291
|
+
function parseBank(input, fallback) {
|
|
292
|
+
const value = input || "";
|
|
293
|
+
if (/工行|工商|icbc/i.test(value)) return "icbc";
|
|
294
|
+
if (/中行|中国银行|boc/i.test(value)) return "boc";
|
|
295
|
+
return fallback;
|
|
296
|
+
}
|
|
297
|
+
__name(parseBank, "parseBank");
|
|
298
|
+
function parseRateType(input, fallback) {
|
|
299
|
+
const value = input || "";
|
|
300
|
+
if (/现钞\s*卖出|现金\s*卖出/i.test(value)) return "cashSell";
|
|
301
|
+
if (/现钞\s*买入|现金\s*买入/i.test(value)) return "cashBuy";
|
|
302
|
+
if (/现汇\s*买入|买入/i.test(value)) return "spotBuy";
|
|
303
|
+
if (/现汇\s*卖出|卖出/i.test(value)) return "spotSell";
|
|
304
|
+
return fallback;
|
|
305
|
+
}
|
|
306
|
+
__name(parseRateType, "parseRateType");
|
|
307
|
+
function parseDays(input) {
|
|
308
|
+
const match = input?.match(/(\d{1,3})\s*天?/);
|
|
309
|
+
const days = match ? Number(match[1]) : 7;
|
|
310
|
+
return Math.min(Math.max(days, 1), 365);
|
|
311
|
+
}
|
|
312
|
+
__name(parseDays, "parseDays");
|
|
313
|
+
function registerCommands(ctx, service, config) {
|
|
314
|
+
ctx.command("汇率 [query:text]", "查询日元银行牌价。默认展示现汇卖出价。").alias("日元").usage("示例:汇率 日元;汇率 中行 日元 详细;汇率 工行 现钞卖出").action(async (_, query) => {
|
|
315
|
+
const snapshot = await service.ensureSnapshot();
|
|
316
|
+
if (!Object.keys(snapshot).length) return "暂时无法获取日元牌价,请稍后重试。";
|
|
317
|
+
const bank = parseBank(query, config.defaultBank);
|
|
318
|
+
const type = parseRateType(query, config.defaultRateType);
|
|
319
|
+
if (/详细|详情/.test(query || "")) {
|
|
320
|
+
const requested = /中行|中国银行|boc|工行|工商|icbc/i.test(query || "");
|
|
321
|
+
const quotes = requested ? [snapshot[bank]] : [snapshot.boc, snapshot.icbc];
|
|
322
|
+
return quotes.filter(Boolean).map((quote) => formatDetailed(quote)).join("\n\n");
|
|
323
|
+
}
|
|
324
|
+
const specifiedBank = /中行|中国银行|boc|工行|工商|icbc/i.test(query || "");
|
|
325
|
+
return formatSnapshot(specifiedBank ? { [bank]: snapshot[bank] } : snapshot, bank, type);
|
|
326
|
+
});
|
|
327
|
+
ctx.command("购汇成本 <amount:number> [query:text]", "按银行日元卖出价估算购汇成本。").alias("换日元").usage("示例:购汇成本 50000;购汇成本 50000 工行 现钞卖出").action(async (_, amount, query) => {
|
|
328
|
+
if (!Number.isFinite(amount) || amount <= 0) return "请输入大于 0 的日元金额。";
|
|
329
|
+
const snapshot = await service.ensureSnapshot();
|
|
330
|
+
const bank = parseBank(query, config.defaultBank);
|
|
331
|
+
const type = parseRateType(query, config.defaultRateType);
|
|
332
|
+
const quote = snapshot[bank];
|
|
333
|
+
if (!quote) return `暂时无法获取${BANK_LABELS[bank]}日元牌价,请稍后重试。`;
|
|
334
|
+
return formatCost(amount, quote, type);
|
|
335
|
+
});
|
|
336
|
+
ctx.command("汇率趋势 [query:text]", "生成日元牌价趋势图。").alias("日元趋势").usage("示例:汇率趋势 日元 7天;汇率趋势 中行 现汇卖出 30天").action(async ({ session }, query) => {
|
|
337
|
+
const bank = parseBank(query, config.defaultBank);
|
|
338
|
+
const type = parseRateType(query, config.defaultRateType);
|
|
339
|
+
const days = parseDays(query);
|
|
340
|
+
let metrics = await service.getTrend(bank, type, days);
|
|
341
|
+
if (!metrics) {
|
|
342
|
+
await service.collect();
|
|
343
|
+
metrics = await service.getTrend(bank, type, days);
|
|
344
|
+
}
|
|
345
|
+
if (!metrics) return `暂无${BANK_LABELS[bank]}的历史牌价,已尝试采集,请稍后重试。`;
|
|
346
|
+
const summary = formatTrendSummary(bank, type, metrics, days);
|
|
347
|
+
if (!session) return summary;
|
|
348
|
+
await session.send(summary);
|
|
349
|
+
try {
|
|
350
|
+
const image = await renderTrendChart(metrics, type, {
|
|
351
|
+
width: config.chartWidth,
|
|
352
|
+
height: config.chartHeight,
|
|
353
|
+
days
|
|
354
|
+
});
|
|
355
|
+
await session.send(import_koishi2.h.image(image, "image/png"));
|
|
356
|
+
} catch (error) {
|
|
357
|
+
ctx.logger("rina-currency").warn(`生成趋势图失败:${String(error)}`);
|
|
358
|
+
await session.send("趋势图生成失败,已返回文字摘要。");
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
__name(registerCommands, "registerCommands");
|
|
363
|
+
|
|
364
|
+
// src/model.ts
|
|
365
|
+
function extendModel(ctx) {
|
|
366
|
+
ctx.model.extend("rina_currency_rate", {
|
|
367
|
+
id: "unsigned",
|
|
368
|
+
bank: "string",
|
|
369
|
+
currency: "string",
|
|
370
|
+
unit: "integer",
|
|
371
|
+
spotBuy: "double",
|
|
372
|
+
cashBuy: "double",
|
|
373
|
+
spotSell: "double",
|
|
374
|
+
cashSell: "double",
|
|
375
|
+
publishedAt: "timestamp",
|
|
376
|
+
collectedAt: "timestamp",
|
|
377
|
+
sourceUrl: "string"
|
|
378
|
+
}, {
|
|
379
|
+
autoInc: true
|
|
380
|
+
});
|
|
381
|
+
ctx.model.extend("rina_currency_alert_state", {
|
|
382
|
+
id: "unsigned",
|
|
383
|
+
key: "string",
|
|
384
|
+
direction: "integer",
|
|
385
|
+
updatedAt: "timestamp"
|
|
386
|
+
}, {
|
|
387
|
+
autoInc: true
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
__name(extendModel, "extendModel");
|
|
391
|
+
|
|
392
|
+
// src/providers/common.ts
|
|
393
|
+
var BOC_SOURCE_URL = "https://www.boc.cn/sourcedb/whpj/index.html";
|
|
394
|
+
var ICBC_SOURCE_URL = "http://papi.icbc.com.cn/exchanges/ns/getLatest";
|
|
395
|
+
async function fetchText(url, timeoutMs, init = {}) {
|
|
396
|
+
const controller = new AbortController();
|
|
397
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
398
|
+
try {
|
|
399
|
+
const response = await fetch(url, { ...init, signal: controller.signal });
|
|
400
|
+
if (!response.ok) {
|
|
401
|
+
throw new Error(`${response.status} ${response.statusText}`);
|
|
402
|
+
}
|
|
403
|
+
return await response.text();
|
|
404
|
+
} finally {
|
|
405
|
+
clearTimeout(timer);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
__name(fetchText, "fetchText");
|
|
409
|
+
function asRate(value, field) {
|
|
410
|
+
const parsed = Number.parseFloat(String(value).trim());
|
|
411
|
+
if (!Number.isFinite(parsed) || parsed <= 0) {
|
|
412
|
+
throw new Error(`无效的${field}:${String(value)}`);
|
|
413
|
+
}
|
|
414
|
+
return parsed;
|
|
415
|
+
}
|
|
416
|
+
__name(asRate, "asRate");
|
|
417
|
+
function chinaTime(date, time) {
|
|
418
|
+
const normalizedDate = date.trim().replace(/\//g, "-").replace(/\s+/, " ");
|
|
419
|
+
const normalizedTime = (time?.trim() || "00:00:00").replace(/\s+/g, "");
|
|
420
|
+
const localDateTime = /\d{1,2}:\d{2}/.test(normalizedDate) ? normalizedDate.replace(" ", "T") : `${normalizedDate}T${normalizedTime}`;
|
|
421
|
+
const value = /* @__PURE__ */ new Date(`${localDateTime}+08:00`);
|
|
422
|
+
if (Number.isNaN(value.getTime())) {
|
|
423
|
+
throw new Error(`无效的发布时间:${date} ${time || ""}`.trim());
|
|
424
|
+
}
|
|
425
|
+
return value;
|
|
426
|
+
}
|
|
427
|
+
__name(chinaTime, "chinaTime");
|
|
428
|
+
|
|
429
|
+
// src/providers/boc.ts
|
|
430
|
+
function decodeCell(value) {
|
|
431
|
+
return value.replace(/<br\s*\/?\s*>/gi, " ").replace(/<[^>]+>/g, "").replace(/ /gi, " ").replace(/&/gi, "&").replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code))).trim();
|
|
432
|
+
}
|
|
433
|
+
__name(decodeCell, "decodeCell");
|
|
434
|
+
function parseBocJpy(html, collectedAt = /* @__PURE__ */ new Date()) {
|
|
435
|
+
const rows = html.match(/<tr\b[^>]*>[\s\S]*?<\/tr>/gi) || [];
|
|
436
|
+
for (const row of rows) {
|
|
437
|
+
const cells = [...row.matchAll(/<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/gi)].map((match) => decodeCell(match[1]));
|
|
438
|
+
if (cells[0] !== "日元" || cells.length < 8) continue;
|
|
439
|
+
return {
|
|
440
|
+
bank: "boc",
|
|
441
|
+
currency: "JPY",
|
|
442
|
+
unit: 100,
|
|
443
|
+
spotBuy: asRate(cells[1], "中行现汇买入价"),
|
|
444
|
+
cashBuy: asRate(cells[2], "中行现钞买入价"),
|
|
445
|
+
spotSell: asRate(cells[3], "中行现汇卖出价"),
|
|
446
|
+
cashSell: asRate(cells[4], "中行现钞卖出价"),
|
|
447
|
+
publishedAt: chinaTime(cells[6], cells[7]),
|
|
448
|
+
collectedAt,
|
|
449
|
+
sourceUrl: BOC_SOURCE_URL
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
throw new Error("未在中行外汇牌价页找到日元(JPY)记录");
|
|
453
|
+
}
|
|
454
|
+
__name(parseBocJpy, "parseBocJpy");
|
|
455
|
+
var BocProvider = class {
|
|
456
|
+
constructor(timeoutMs) {
|
|
457
|
+
this.timeoutMs = timeoutMs;
|
|
458
|
+
}
|
|
459
|
+
static {
|
|
460
|
+
__name(this, "BocProvider");
|
|
461
|
+
}
|
|
462
|
+
id = "boc";
|
|
463
|
+
async fetch() {
|
|
464
|
+
const html = await fetchText(BOC_SOURCE_URL, this.timeoutMs, {
|
|
465
|
+
headers: { "user-agent": "koishi-plugin-rina-currency/0.1" }
|
|
466
|
+
});
|
|
467
|
+
return parseBocJpy(html);
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
// src/providers/icbc.ts
|
|
472
|
+
function parseIcbcJpy(payload, collectedAt = /* @__PURE__ */ new Date()) {
|
|
473
|
+
const row = payload.data?.find((item) => item.currencyENName === "JPY");
|
|
474
|
+
if (payload.code !== 0 || !row) {
|
|
475
|
+
throw new Error(`工行接口未返回日元记录:${payload.message || payload.code}`);
|
|
476
|
+
}
|
|
477
|
+
return {
|
|
478
|
+
bank: "icbc",
|
|
479
|
+
currency: "JPY",
|
|
480
|
+
unit: 100,
|
|
481
|
+
spotBuy: asRate(row.foreignBuy, "工行现汇买入价"),
|
|
482
|
+
cashBuy: asRate(row.cashBuy, "工行现钞买入价"),
|
|
483
|
+
spotSell: asRate(row.foreignSell, "工行现汇卖出价"),
|
|
484
|
+
cashSell: asRate(row.cashSell, "工行现钞卖出价"),
|
|
485
|
+
publishedAt: chinaTime(row.publishDate || "", row.publishTime),
|
|
486
|
+
collectedAt,
|
|
487
|
+
sourceUrl: ICBC_SOURCE_URL
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
__name(parseIcbcJpy, "parseIcbcJpy");
|
|
491
|
+
var IcbcProvider = class {
|
|
492
|
+
constructor(timeoutMs) {
|
|
493
|
+
this.timeoutMs = timeoutMs;
|
|
494
|
+
}
|
|
495
|
+
static {
|
|
496
|
+
__name(this, "IcbcProvider");
|
|
497
|
+
}
|
|
498
|
+
id = "icbc";
|
|
499
|
+
async fetch() {
|
|
500
|
+
const body = await fetchText(ICBC_SOURCE_URL, this.timeoutMs, {
|
|
501
|
+
method: "POST",
|
|
502
|
+
headers: {
|
|
503
|
+
"content-type": "application/json",
|
|
504
|
+
"user-agent": "koishi-plugin-rina-currency/0.1"
|
|
505
|
+
},
|
|
506
|
+
body: "{}"
|
|
507
|
+
});
|
|
508
|
+
return parseIcbcJpy(JSON.parse(body));
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
// src/scheduler.ts
|
|
513
|
+
var import_koishi3 = require("koishi");
|
|
514
|
+
function chinaClock(now = /* @__PURE__ */ new Date()) {
|
|
515
|
+
const parts = new Intl.DateTimeFormat("en-CA", {
|
|
516
|
+
timeZone: "Asia/Shanghai",
|
|
517
|
+
year: "numeric",
|
|
518
|
+
month: "2-digit",
|
|
519
|
+
day: "2-digit",
|
|
520
|
+
hour: "2-digit",
|
|
521
|
+
minute: "2-digit",
|
|
522
|
+
hour12: false
|
|
523
|
+
}).formatToParts(now).reduce((result, part) => {
|
|
524
|
+
result[part.type] = part.value;
|
|
525
|
+
return result;
|
|
526
|
+
}, {});
|
|
527
|
+
return {
|
|
528
|
+
date: `${parts.year}-${parts.month}-${parts.day}`,
|
|
529
|
+
hour: Number(parts.hour),
|
|
530
|
+
minute: Number(parts.minute)
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
__name(chinaClock, "chinaClock");
|
|
534
|
+
var Scheduler = class {
|
|
535
|
+
constructor(ctx, logger, service, config) {
|
|
536
|
+
this.ctx = ctx;
|
|
537
|
+
this.logger = logger;
|
|
538
|
+
this.service = service;
|
|
539
|
+
this.config = config;
|
|
540
|
+
}
|
|
541
|
+
static {
|
|
542
|
+
__name(this, "Scheduler");
|
|
543
|
+
}
|
|
544
|
+
sentBroadcasts = /* @__PURE__ */ new Set();
|
|
545
|
+
start() {
|
|
546
|
+
this.ctx.on("ready", async () => {
|
|
547
|
+
if (this.config.collectOnStart) await this.collectAndAlert();
|
|
548
|
+
this.ctx.setInterval(() => void this.collectAndAlert(), this.config.collectIntervalMinutes * 6e4);
|
|
549
|
+
this.ctx.setInterval(() => void this.runBroadcasts(), 3e4);
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
getBot(target) {
|
|
553
|
+
return this.ctx.bots.find((bot) => bot.platform === target.platform && bot.selfId === target.selfId);
|
|
554
|
+
}
|
|
555
|
+
async send(target, content, image) {
|
|
556
|
+
const bot = this.getBot(target);
|
|
557
|
+
if (!bot) {
|
|
558
|
+
this.logger.warn(`未找到机器人 ${target.platform}:${target.selfId},无法向 ${target.channelId} 发送汇率消息。`);
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
await bot.sendMessage(target.channelId, content);
|
|
562
|
+
if (image) await bot.sendMessage(target.channelId, import_koishi3.h.image(image, "image/png"));
|
|
563
|
+
}
|
|
564
|
+
async collectAndAlert() {
|
|
565
|
+
try {
|
|
566
|
+
const result = await this.service.collect();
|
|
567
|
+
await Promise.all(result.collected.map((item) => this.maybeAlert(item)));
|
|
568
|
+
} catch (error) {
|
|
569
|
+
this.logger.warn(`定时采集日元牌价失败:${String(error)}`);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
async maybeAlert({ quote, previous, isNew }) {
|
|
573
|
+
if (!isNew || !previous) return;
|
|
574
|
+
const alerts = this.config.thresholdAlerts.filter((alert) => alert.enabled && alert.bank === quote.bank);
|
|
575
|
+
for (const alert of alerts) {
|
|
576
|
+
const changePercent = (quote[alert.rateType] - previous[alert.rateType]) / previous[alert.rateType] * 100;
|
|
577
|
+
const direction = Math.abs(changePercent) >= alert.changePercent ? Math.sign(changePercent) : 0;
|
|
578
|
+
const key = [
|
|
579
|
+
alert.platform,
|
|
580
|
+
alert.selfId,
|
|
581
|
+
alert.channelId,
|
|
582
|
+
alert.bank,
|
|
583
|
+
alert.rateType,
|
|
584
|
+
alert.changePercent
|
|
585
|
+
].join(":");
|
|
586
|
+
const states = await this.ctx.database.get("rina_currency_alert_state", { key });
|
|
587
|
+
const state = states[0];
|
|
588
|
+
if (direction && state?.direction !== direction) {
|
|
589
|
+
const elapsedMinutes = Math.max(1, Math.round((quote.publishedAt.getTime() - previous.publishedAt.getTime()) / 6e4));
|
|
590
|
+
await this.send(alert, [
|
|
591
|
+
"【日元汇率波动提醒】",
|
|
592
|
+
`${BANK_LABELS[quote.bank]}${RATE_TYPE_LABELS[alert.rateType]}较上次采样(约 ${elapsedMinutes} 分钟前)${direction > 0 ? "上涨" : "下跌"} ${Math.abs(changePercent).toFixed(2)}%。`,
|
|
593
|
+
`当前:${formatRate(quote[alert.rateType])}(100 JPY / CNY)`,
|
|
594
|
+
`上次采样:${formatRate(previous[alert.rateType])}`,
|
|
595
|
+
"实际成交以银行渠道为准。"
|
|
596
|
+
].join("\n"));
|
|
597
|
+
}
|
|
598
|
+
if (state) {
|
|
599
|
+
await this.ctx.database.set("rina_currency_alert_state", state.id, { direction, updatedAt: /* @__PURE__ */ new Date() });
|
|
600
|
+
} else {
|
|
601
|
+
await this.ctx.database.create("rina_currency_alert_state", { key, direction, updatedAt: /* @__PURE__ */ new Date() });
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
async runBroadcasts() {
|
|
606
|
+
const clock = chinaClock();
|
|
607
|
+
const targets = this.config.broadcasts.filter((target) => target.enabled && target.hour === clock.hour && target.minute === clock.minute);
|
|
608
|
+
for (const [index, target] of targets.entries()) {
|
|
609
|
+
const key = `${clock.date}:${index}:${target.platform}:${target.selfId}:${target.channelId}`;
|
|
610
|
+
if (this.sentBroadcasts.has(key)) continue;
|
|
611
|
+
this.sentBroadcasts.add(key);
|
|
612
|
+
try {
|
|
613
|
+
const snapshot = await this.service.ensureSnapshot();
|
|
614
|
+
if (!Object.keys(snapshot).length) throw new Error("没有可播报的牌价");
|
|
615
|
+
const metrics = await this.service.getTrend(this.config.defaultBank, this.config.defaultRateType, target.chartDays);
|
|
616
|
+
const content = metrics ? `${formatSnapshot(snapshot, this.config.defaultBank, this.config.defaultRateType)}
|
|
617
|
+
|
|
618
|
+
${formatTrendSummary(this.config.defaultBank, this.config.defaultRateType, metrics, target.chartDays)}` : formatSnapshot(snapshot, this.config.defaultBank, this.config.defaultRateType);
|
|
619
|
+
const image = target.includeChart && metrics ? await renderTrendChart(metrics, this.config.defaultRateType, { width: this.config.chartWidth, height: this.config.chartHeight, days: target.chartDays }) : void 0;
|
|
620
|
+
await this.send(target, content, image);
|
|
621
|
+
} catch (error) {
|
|
622
|
+
this.logger.warn(`日元定时播报失败:${String(error)}`);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
// src/service.ts
|
|
629
|
+
function toQuote(record) {
|
|
630
|
+
return { ...record };
|
|
631
|
+
}
|
|
632
|
+
__name(toQuote, "toQuote");
|
|
633
|
+
function sortByPublishedAt(records) {
|
|
634
|
+
return records.sort((left, right) => left.publishedAt.getTime() - right.publishedAt.getTime());
|
|
635
|
+
}
|
|
636
|
+
__name(sortByPublishedAt, "sortByPublishedAt");
|
|
637
|
+
var RateService = class {
|
|
638
|
+
constructor(ctx, logger, providers) {
|
|
639
|
+
this.ctx = ctx;
|
|
640
|
+
this.logger = logger;
|
|
641
|
+
this.providers = providers;
|
|
642
|
+
}
|
|
643
|
+
static {
|
|
644
|
+
__name(this, "RateService");
|
|
645
|
+
}
|
|
646
|
+
async collect() {
|
|
647
|
+
const settled = await Promise.allSettled(this.providers.map(async (provider) => {
|
|
648
|
+
const previous = await this.getLatest(provider.id);
|
|
649
|
+
const quote = await provider.fetch();
|
|
650
|
+
if (previous?.publishedAt.getTime() === quote.publishedAt.getTime()) {
|
|
651
|
+
return { quote: previous, previous, isNew: false };
|
|
652
|
+
}
|
|
653
|
+
await this.ctx.database.create("rina_currency_rate", quote);
|
|
654
|
+
return { quote, previous, isNew: true };
|
|
655
|
+
}));
|
|
656
|
+
const collected = [];
|
|
657
|
+
const errors = [];
|
|
658
|
+
settled.forEach((result, index) => {
|
|
659
|
+
if (result.status === "fulfilled") {
|
|
660
|
+
collected.push(result.value);
|
|
661
|
+
} else {
|
|
662
|
+
const bank = this.providers[index].id;
|
|
663
|
+
errors.push({ bank, error: result.reason });
|
|
664
|
+
this.logger.warn(`采集${bank}日元牌价失败:${String(result.reason)}`);
|
|
665
|
+
}
|
|
666
|
+
});
|
|
667
|
+
return { collected, errors };
|
|
668
|
+
}
|
|
669
|
+
async getLatest(bank) {
|
|
670
|
+
const rows = await this.ctx.database.get("rina_currency_rate", { bank, currency: "JPY" });
|
|
671
|
+
if (!rows.length) return;
|
|
672
|
+
return sortByPublishedAt(rows.map(toQuote)).at(-1);
|
|
673
|
+
}
|
|
674
|
+
async getLatestAll() {
|
|
675
|
+
const entries = await Promise.all(["boc", "icbc"].map(async (bank) => [bank, await this.getLatest(bank)]));
|
|
676
|
+
return Object.fromEntries(entries.filter(([, value]) => value));
|
|
677
|
+
}
|
|
678
|
+
async ensureSnapshot() {
|
|
679
|
+
let snapshot = await this.getLatestAll();
|
|
680
|
+
if (Object.keys(snapshot).length) return snapshot;
|
|
681
|
+
await this.collect();
|
|
682
|
+
snapshot = await this.getLatestAll();
|
|
683
|
+
return snapshot;
|
|
684
|
+
}
|
|
685
|
+
async getTrend(bank, rateType, days) {
|
|
686
|
+
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1e3);
|
|
687
|
+
const rows = await this.ctx.database.get("rina_currency_rate", {
|
|
688
|
+
bank,
|
|
689
|
+
currency: "JPY",
|
|
690
|
+
publishedAt: { $gte: since }
|
|
691
|
+
});
|
|
692
|
+
const points = sortByPublishedAt(rows.map(toQuote));
|
|
693
|
+
if (!points.length) return;
|
|
694
|
+
const latest = points.at(-1);
|
|
695
|
+
const dayBefore = latest.publishedAt.getTime() - 24 * 60 * 60 * 1e3;
|
|
696
|
+
const previous = [...points].reverse().find((point) => point.publishedAt.getTime() <= dayBefore);
|
|
697
|
+
const values = points.map((point) => point[rateType]);
|
|
698
|
+
const change = previous ? latest[rateType] - previous[rateType] : void 0;
|
|
699
|
+
return {
|
|
700
|
+
latest,
|
|
701
|
+
previous,
|
|
702
|
+
change,
|
|
703
|
+
changePercent: change == null ? void 0 : change / previous[rateType] * 100,
|
|
704
|
+
high: Math.max(...values),
|
|
705
|
+
low: Math.min(...values),
|
|
706
|
+
points
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
};
|
|
710
|
+
|
|
711
|
+
// src/index.ts
|
|
712
|
+
var name = "rina-currency";
|
|
713
|
+
var inject = ["database"];
|
|
714
|
+
var Config2 = Config;
|
|
715
|
+
function apply(ctx, config) {
|
|
716
|
+
extendModel(ctx);
|
|
717
|
+
const logger = ctx.logger(name);
|
|
718
|
+
const service = new RateService(ctx, logger, [
|
|
719
|
+
new BocProvider(config.requestTimeout),
|
|
720
|
+
new IcbcProvider(config.requestTimeout)
|
|
721
|
+
]);
|
|
722
|
+
registerCommands(ctx, service, config);
|
|
723
|
+
new Scheduler(ctx, logger, service, config).start();
|
|
724
|
+
}
|
|
725
|
+
__name(apply, "apply");
|
|
726
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
727
|
+
0 && (module.exports = {
|
|
728
|
+
Config,
|
|
729
|
+
apply,
|
|
730
|
+
inject,
|
|
731
|
+
name
|
|
732
|
+
});
|
package/lib/model.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Context } from 'koishi';
|
|
2
|
+
import { BankId } from './types';
|
|
3
|
+
export interface ExchangeRateHistory {
|
|
4
|
+
id: number;
|
|
5
|
+
bank: BankId;
|
|
6
|
+
currency: 'JPY';
|
|
7
|
+
unit: number;
|
|
8
|
+
spotBuy: number;
|
|
9
|
+
cashBuy: number;
|
|
10
|
+
spotSell: number;
|
|
11
|
+
cashSell: number;
|
|
12
|
+
publishedAt: Date;
|
|
13
|
+
collectedAt: Date;
|
|
14
|
+
sourceUrl: string;
|
|
15
|
+
}
|
|
16
|
+
export interface ExchangeRateAlertState {
|
|
17
|
+
id: number;
|
|
18
|
+
key: string;
|
|
19
|
+
direction: number;
|
|
20
|
+
updatedAt: Date;
|
|
21
|
+
}
|
|
22
|
+
declare module 'koishi' {
|
|
23
|
+
interface Tables {
|
|
24
|
+
rina_currency_rate: ExchangeRateHistory;
|
|
25
|
+
rina_currency_alert_state: ExchangeRateAlertState;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export declare function extendModel(ctx: Context): void;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { RateProvider } from './common';
|
|
2
|
+
import { ExchangeRateQuote } from '../types';
|
|
3
|
+
/** Parses the public BOC table without relying on a third-party scraper. */
|
|
4
|
+
export declare function parseBocJpy(html: string, collectedAt?: Date): ExchangeRateQuote;
|
|
5
|
+
export declare class BocProvider implements RateProvider {
|
|
6
|
+
private timeoutMs;
|
|
7
|
+
readonly id: "boc";
|
|
8
|
+
constructor(timeoutMs: number);
|
|
9
|
+
fetch(): Promise<ExchangeRateQuote>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { ExchangeRateQuote } from '../types';
|
|
2
|
+
export declare const BOC_SOURCE_URL = "https://www.boc.cn/sourcedb/whpj/index.html";
|
|
3
|
+
export declare const ICBC_SOURCE_URL = "http://papi.icbc.com.cn/exchanges/ns/getLatest";
|
|
4
|
+
export interface RateProvider {
|
|
5
|
+
readonly id: ExchangeRateQuote['bank'];
|
|
6
|
+
fetch(): Promise<ExchangeRateQuote>;
|
|
7
|
+
}
|
|
8
|
+
export declare function fetchText(url: string, timeoutMs: number, init?: RequestInit): Promise<string>;
|
|
9
|
+
export declare function asRate(value: unknown, field: string): number;
|
|
10
|
+
export declare function chinaTime(date: string, time?: string): Date;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { RateProvider } from './common';
|
|
2
|
+
import { ExchangeRateQuote } from '../types';
|
|
3
|
+
interface IcbcResponse {
|
|
4
|
+
code: number;
|
|
5
|
+
message?: string;
|
|
6
|
+
data?: Array<{
|
|
7
|
+
currencyENName?: string;
|
|
8
|
+
foreignBuy?: string;
|
|
9
|
+
cashBuy?: string;
|
|
10
|
+
foreignSell?: string;
|
|
11
|
+
cashSell?: string;
|
|
12
|
+
publishDate?: string;
|
|
13
|
+
publishTime?: string;
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
16
|
+
export declare function parseIcbcJpy(payload: IcbcResponse, collectedAt?: Date): ExchangeRateQuote;
|
|
17
|
+
export declare class IcbcProvider implements RateProvider {
|
|
18
|
+
private timeoutMs;
|
|
19
|
+
readonly id: "icbc";
|
|
20
|
+
constructor(timeoutMs: number);
|
|
21
|
+
fetch(): Promise<ExchangeRateQuote>;
|
|
22
|
+
}
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Context, Logger } from 'koishi';
|
|
2
|
+
import { Config } from './config';
|
|
3
|
+
import { RateService } from './service';
|
|
4
|
+
export declare class Scheduler {
|
|
5
|
+
private ctx;
|
|
6
|
+
private logger;
|
|
7
|
+
private service;
|
|
8
|
+
private config;
|
|
9
|
+
private sentBroadcasts;
|
|
10
|
+
constructor(ctx: Context, logger: Logger, service: RateService, config: Config);
|
|
11
|
+
start(): void;
|
|
12
|
+
private getBot;
|
|
13
|
+
private send;
|
|
14
|
+
private collectAndAlert;
|
|
15
|
+
private maybeAlert;
|
|
16
|
+
private runBroadcasts;
|
|
17
|
+
}
|
package/lib/service.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Context, Logger } from 'koishi';
|
|
2
|
+
import { RateProvider } from './providers/common';
|
|
3
|
+
import { BankId, ExchangeRateQuote, RateType, TrendMetrics } from './types';
|
|
4
|
+
export interface CollectedRate {
|
|
5
|
+
quote: ExchangeRateQuote;
|
|
6
|
+
previous?: ExchangeRateQuote;
|
|
7
|
+
isNew: boolean;
|
|
8
|
+
}
|
|
9
|
+
export interface CollectionResult {
|
|
10
|
+
collected: CollectedRate[];
|
|
11
|
+
errors: Array<{
|
|
12
|
+
bank: BankId;
|
|
13
|
+
error: unknown;
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
16
|
+
export declare class RateService {
|
|
17
|
+
private ctx;
|
|
18
|
+
private logger;
|
|
19
|
+
private providers;
|
|
20
|
+
constructor(ctx: Context, logger: Logger, providers: RateProvider[]);
|
|
21
|
+
collect(): Promise<CollectionResult>;
|
|
22
|
+
getLatest(bank: BankId): Promise<ExchangeRateQuote | undefined>;
|
|
23
|
+
getLatestAll(): Promise<Partial<Record<BankId, ExchangeRateQuote>>>;
|
|
24
|
+
ensureSnapshot(): Promise<Partial<Record<BankId, ExchangeRateQuote>>>;
|
|
25
|
+
getTrend(bank: BankId, rateType: RateType, days: number): Promise<TrendMetrics | undefined>;
|
|
26
|
+
}
|
package/lib/types.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export declare const RATE_TYPES: readonly ["spotBuy", "cashBuy", "spotSell", "cashSell"];
|
|
2
|
+
export type RateType = (typeof RATE_TYPES)[number];
|
|
3
|
+
export type BankId = 'boc' | 'icbc';
|
|
4
|
+
export interface ExchangeRateQuote {
|
|
5
|
+
bank: BankId;
|
|
6
|
+
currency: 'JPY';
|
|
7
|
+
unit: number;
|
|
8
|
+
spotBuy: number;
|
|
9
|
+
cashBuy: number;
|
|
10
|
+
spotSell: number;
|
|
11
|
+
cashSell: number;
|
|
12
|
+
publishedAt: Date;
|
|
13
|
+
collectedAt: Date;
|
|
14
|
+
sourceUrl: string;
|
|
15
|
+
}
|
|
16
|
+
export interface TrendMetrics {
|
|
17
|
+
latest: ExchangeRateQuote;
|
|
18
|
+
previous?: ExchangeRateQuote;
|
|
19
|
+
change?: number;
|
|
20
|
+
changePercent?: number;
|
|
21
|
+
high: number;
|
|
22
|
+
low: number;
|
|
23
|
+
points: ExchangeRateQuote[];
|
|
24
|
+
}
|
|
25
|
+
export declare const BANK_LABELS: Record<BankId, string>;
|
|
26
|
+
export declare const RATE_TYPE_LABELS: Record<RateType, string>;
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "koishi-plugin-rina-currency",
|
|
3
|
+
"description": "面向购汇决策的日元汇率插件,基于中行和工行数据",
|
|
4
|
+
"version": "0.0.1",
|
|
5
|
+
"main": "lib/index.js",
|
|
6
|
+
"typings": "lib/index.d.ts",
|
|
7
|
+
"files": [
|
|
8
|
+
"lib",
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"scripts": {
|
|
13
|
+
"typecheck": "tsc --noEmit"
|
|
14
|
+
},
|
|
15
|
+
"keywords": [
|
|
16
|
+
"chatbot",
|
|
17
|
+
"koishi",
|
|
18
|
+
"plugin"
|
|
19
|
+
],
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"koishi": "^4.18.7"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"sharp": "^0.34.2"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/node": "^22.15.21",
|
|
28
|
+
"koishi": "^4.18.7",
|
|
29
|
+
"typescript": "^5.8.3"
|
|
30
|
+
},
|
|
31
|
+
"koishi": {
|
|
32
|
+
"description": {
|
|
33
|
+
"zh": "面向购汇决策的日元汇率插件,提供历史趋势、购汇成本和定时播报。"
|
|
34
|
+
},
|
|
35
|
+
"service": {
|
|
36
|
+
"required": [
|
|
37
|
+
"database"
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# koishi-plugin-rina-currency
|
|
2
|
+
|
|
3
|
+
面向购汇决策的日元(JPY)汇率插件。默认关注中国银行与中国工商银行的**现汇卖出价**,定时积累历史牌价,并提供购汇成本、趋势图、每日播报和跌破阈值提醒。
|
|
4
|
+
|
|
5
|
+
## 前置条件
|
|
6
|
+
|
|
7
|
+
插件依赖 Koishi 的 `database` 服务。应用中请启用一个数据库实现;SQLite 示例:
|
|
8
|
+
|
|
9
|
+
```yaml
|
|
10
|
+
plugins:
|
|
11
|
+
database-sqlite:
|
|
12
|
+
path: data/koishi.db
|
|
13
|
+
rina-currency: {}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## 指令
|
|
17
|
+
|
|
18
|
+
```text
|
|
19
|
+
汇率 日元
|
|
20
|
+
汇率 中行 日元
|
|
21
|
+
汇率 工行 现钞卖出
|
|
22
|
+
汇率 日元 详细
|
|
23
|
+
购汇成本 50000
|
|
24
|
+
购汇成本 50000 工行 现钞卖出
|
|
25
|
+
汇率趋势 日元 7天
|
|
26
|
+
汇率趋势 中行 现汇卖出 30天
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`日元`、`换日元` 和 `日元趋势` 可作为对应命令的别名。牌价单位始终为 `100 JPY / CNY`,购汇成本按 `日元金额 × 卖出价 ÷ 100` 计算。
|
|
30
|
+
|
|
31
|
+
## 采集和来源
|
|
32
|
+
|
|
33
|
+
插件启动时可立即采集,之后默认每 60 分钟采集一次。查询优先读取 Koishi 数据库中的历史记录,只有历史库为空时才会补采集一次。
|
|
34
|
+
|
|
35
|
+
- 中国银行:公开外汇牌价页面(HTML 表格)
|
|
36
|
+
- 中国工商银行:公开最新牌价接口(JSON)
|
|
37
|
+
|
|
38
|
+
工行公开端点当前与现代 Node 的 HTTPS TLS 协商不兼容,因此实现使用其原有、无凭据的 HTTP 公开牌价端点;请求不发送任何用户数据。每条历史记录都会保存来源 URL、银行发布时间和抓取时间。
|
|
39
|
+
|
|
40
|
+
牌价仅供参考,实际成交以银行渠道为准。引用中行牌价时应注明来源。
|
|
41
|
+
|
|
42
|
+
## 配置
|
|
43
|
+
|
|
44
|
+
```yaml
|
|
45
|
+
plugins:
|
|
46
|
+
rina-currency:
|
|
47
|
+
defaultBank: boc
|
|
48
|
+
defaultRateType: spotSell
|
|
49
|
+
collectIntervalMinutes: 60
|
|
50
|
+
broadcasts:
|
|
51
|
+
- platform: onebot
|
|
52
|
+
selfId: '123456'
|
|
53
|
+
channelId: '987654'
|
|
54
|
+
hour: 9
|
|
55
|
+
minute: 0
|
|
56
|
+
includeChart: true
|
|
57
|
+
chartDays: 7
|
|
58
|
+
thresholdAlerts:
|
|
59
|
+
- bank: boc
|
|
60
|
+
rateType: spotSell
|
|
61
|
+
changePercent: 0.5
|
|
62
|
+
platform: onebot
|
|
63
|
+
selfId: '123456'
|
|
64
|
+
channelId: '987654'
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
定时播报按北京时间执行。阈值提醒按相邻真实采样点的绝对涨跌幅触发:`changePercent: 0.5` 表示上涨或下跌至少 0.5%。比较周期由 `collectIntervalMinutes` 自然决定;同方向只提醒一次,波动回到阈值内或反向越过阈值后才会重新提醒。
|
|
68
|
+
|
|
69
|
+
## 开发
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
npm install
|
|
73
|
+
npm run typecheck
|
|
74
|
+
```
|