@enderhorror/koishi-plugin-steam-friend-status 0.3.3 → 0.3.5

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.
@@ -4,6 +4,12 @@ export interface SteamBroadcastConfig {
4
4
  SteamApiKey: string;
5
5
  useSteamName: boolean;
6
6
  broadcastWithImage: boolean;
7
+ mergeBroadcast?: boolean;
8
+ mergeWindow?: number;
9
+ stabilityPeriod?: number;
10
+ gameBroadcastCooldown?: number;
11
+ minStopPlayMinutes?: number;
12
+ immediateBroadcast?: boolean;
7
13
  }
8
14
  export declare function pollSteamBroadcast(ctx: Context, config: SteamBroadcastConfig, logger: PluginLogger, shouldStop: () => boolean): Promise<void>;
9
15
  export declare function updatePlayerHeadshots(ctx: Context, config: SteamBroadcastConfig, logger: PluginLogger): Promise<void>;
package/lib/index.d.ts CHANGED
@@ -8,6 +8,12 @@ export interface PluginConfig {
8
8
  interval: number;
9
9
  useSteamName: boolean;
10
10
  broadcastWithImage: boolean;
11
+ mergeBroadcast: boolean;
12
+ mergeWindow: number;
13
+ stabilityPeriod: number;
14
+ gameBroadcastCooldown: number;
15
+ minStopPlayMinutes: number;
16
+ immediateBroadcast: boolean;
11
17
  useApifoxProxy: boolean;
12
18
  maxRetries: number;
13
19
  showcardmode: "1" | "2";
package/lib/index.js CHANGED
@@ -484,11 +484,11 @@ async function saveGameSessionsLocked(ctx, data) {
484
484
  releaseLock();
485
485
  }
486
486
  }
487
- async function startGameSession(ctx, userId, gameName) {
487
+ async function startGameSession(ctx, userId, gameName, startTime = Date.now()) {
488
488
  const sessions = await loadGameSessionsLocked(ctx);
489
489
  sessions[userId] = {
490
490
  gameName,
491
- startTime: Date.now()
491
+ startTime
492
492
  };
493
493
  await saveGameSessionsLocked(ctx, sessions);
494
494
  }
@@ -1236,6 +1236,37 @@ async function getGameChangeImg(ctx, playerInfo, changeInfo) {
1236
1236
 
1237
1237
  // package/src/broadcast.ts
1238
1238
  var import_koishi3 = require("koishi");
1239
+ var broadcastCooldowns = /* @__PURE__ */ new WeakMap();
1240
+ function cooldownKey(channelId, userId, id, name2) {
1241
+ return JSON.stringify([channelId, userId, id ? `id:${id}` : `name:${(name2 || "").trim().toLowerCase()}`]);
1242
+ }
1243
+ function eligibleChange(ctx, channelId, change, config) {
1244
+ let cache = broadcastCooldowns.get(ctx);
1245
+ if (!cache) {
1246
+ cache = /* @__PURE__ */ new Map();
1247
+ broadcastCooldowns.set(ctx, cache);
1248
+ }
1249
+ const now = Date.now();
1250
+ const duration = Math.max(0, config.gameBroadcastCooldown ?? 30) * 6e4;
1251
+ for (const [key, expires] of cache) if (expires <= now) cache.delete(key);
1252
+ const oldKey = change.oldGame ? cooldownKey(channelId, change.userId, change.oldGameId, change.oldGame) : "";
1253
+ const newKey = change.newGame ? cooldownKey(channelId, change.userId, change.newGameId, change.newGame) : "";
1254
+ const oldAllowed = !!oldKey && !change.suppressEnd && (!duration || !cache.has(oldKey));
1255
+ const newAllowed = !!newKey && (!duration || !cache.has(newKey));
1256
+ if (change.status === "start") return newAllowed ? { change, keys: [newKey] } : null;
1257
+ if (change.status === "stop") return oldAllowed ? { change, keys: [oldKey] } : null;
1258
+ if (oldAllowed && newAllowed) return { change, keys: [.../* @__PURE__ */ new Set([oldKey, newKey])] };
1259
+ if (newAllowed) return { change: { ...change, status: "start", oldGame: void 0, oldGameId: void 0, playTime: void 0 }, keys: [newKey] };
1260
+ if (oldAllowed) return { change: { ...change, status: "stop", newGame: void 0, newGameId: void 0 }, keys: [oldKey] };
1261
+ return null;
1262
+ }
1263
+ function recordCooldown(ctx, keys, config) {
1264
+ const duration = Math.max(0, config.gameBroadcastCooldown ?? 30) * 6e4;
1265
+ if (!duration) return;
1266
+ const cache = broadcastCooldowns.get(ctx);
1267
+ const expires = Date.now() + duration;
1268
+ for (const key of keys) cache.set(key, expires);
1269
+ }
1239
1270
  async function pollSteamBroadcast(ctx, config, logger, shouldStop) {
1240
1271
  const channels = await ctx.database.get("channel", { usingSteam: true });
1241
1272
  if (channels.length === 0) {
@@ -1270,6 +1301,10 @@ async function pollSteamBroadcast(ctx, config, logger, shouldStop) {
1270
1301
  logger,
1271
1302
  shouldStop
1272
1303
  );
1304
+ if (config.mergeBroadcast !== false && !config.immediateBroadcast) {
1305
+ await processMergedBroadcast(ctx, config, logger, shouldStop, channels, allUserData, steamUserInfo, changes);
1306
+ return;
1307
+ }
1273
1308
  if (Object.keys(changes).length === 0) {
1274
1309
  logger.debug("\u672C\u8F6E\u6CA1\u6709\u68C0\u6D4B\u5230\u6E38\u620F\u72B6\u6001\u53D8\u5316");
1275
1310
  return;
@@ -1287,6 +1322,13 @@ async function pollSteamBroadcast(ctx, config, logger, shouldStop) {
1287
1322
  );
1288
1323
  continue;
1289
1324
  }
1325
+ if (isShortSession(changeInfo, config)) {
1326
+ if (changeInfo.status === "stop") {
1327
+ await acknowledgeGameChange(ctx, changeInfo, logger);
1328
+ continue;
1329
+ }
1330
+ changeInfo.suppressEnd = true;
1331
+ }
1290
1332
  const playerInfo = steamUserInfo.response.players.find(
1291
1333
  (player) => player.steamid === user.steamId
1292
1334
  );
@@ -1299,6 +1341,14 @@ async function pollSteamBroadcast(ctx, config, logger, shouldStop) {
1299
1341
  let allSucceeded = true;
1300
1342
  for (const channel of targetChannels) {
1301
1343
  if (shouldStop()) return;
1344
+ const eligible = eligibleChange(ctx, channel.id, changeInfo, config);
1345
+ if (!eligible) continue;
1346
+ const channelDisplay = {
1347
+ ...displayChange,
1348
+ ...eligible.change,
1349
+ oldGame: eligible.change.oldGame ? displayChange.oldGame : void 0,
1350
+ newGame: eligible.change.newGame ? displayChange.newGame : void 0
1351
+ };
1302
1352
  const directBot = ctx.bots[`${channel.platform}:${channel.assignee}`];
1303
1353
  const bot = directBot || Object.values(ctx.bots).find(
1304
1354
  (item) => item.platform === channel.platform && (item.selfId === channel.assignee || item.user?.id === channel.assignee)
@@ -1317,7 +1367,7 @@ async function pollSteamBroadcast(ctx, config, logger, shouldStop) {
1317
1367
  );
1318
1368
  const textMessage = buildBroadcastText(
1319
1369
  channelNickname || changeInfo.userName,
1320
- displayChange
1370
+ channelDisplay
1321
1371
  );
1322
1372
  try {
1323
1373
  await sendBroadcast(
@@ -1326,10 +1376,11 @@ async function pollSteamBroadcast(ctx, config, logger, shouldStop) {
1326
1376
  channel.id,
1327
1377
  textMessage,
1328
1378
  playerInfo,
1329
- displayChange,
1379
+ channelDisplay,
1330
1380
  config.broadcastWithImage,
1331
1381
  logger
1332
1382
  );
1383
+ recordCooldown(ctx, eligible.keys, config);
1333
1384
  logger.debug(
1334
1385
  `\u5DF2\u5411\u7FA4\u7EC4 ${channel.id} \u64AD\u62A5\u7528\u6237 ${changeInfo.userId}: ${textMessage}`
1335
1386
  );
@@ -1343,6 +1394,113 @@ async function pollSteamBroadcast(ctx, config, logger, shouldStop) {
1343
1394
  }
1344
1395
  }
1345
1396
  }
1397
+ var mergeStates = /* @__PURE__ */ new WeakMap();
1398
+ function getMergeState(ctx) {
1399
+ let state = mergeStates.get(ctx);
1400
+ if (!state) {
1401
+ state = { candidates: /* @__PURE__ */ new Map(), queue: /* @__PURE__ */ new Map() };
1402
+ mergeStates.set(ctx, state);
1403
+ }
1404
+ return state;
1405
+ }
1406
+ function changeSignature(change) {
1407
+ return JSON.stringify([change.oldGame || "", change.newGame || "", change.newGameId || ""]);
1408
+ }
1409
+ async function processMergedBroadcast(ctx, config, logger, shouldStop, channels, users, steamUserInfo, changes) {
1410
+ const state = getMergeState(ctx);
1411
+ const now = Date.now();
1412
+ const stableMs = Math.max(0, config.stabilityPeriod ?? 30) * 1e3;
1413
+ const mergeMs = Math.max(0, config.mergeWindow ?? 180) * 1e3;
1414
+ const observed = new Set(steamUserInfo.response.players.map((p) => p.steamid));
1415
+ const userMap = new Map(users.map((u) => [u.userId, u]));
1416
+ for (const id of /* @__PURE__ */ new Set([...state.candidates.keys(), ...state.queue.keys()])) {
1417
+ const user = userMap.get(id);
1418
+ if (!user || !observed.has(user.steamId) || !changes[id]) {
1419
+ state.candidates.delete(id);
1420
+ if (!user || observed.has(user.steamId) && !changes[id]) state.queue.delete(id);
1421
+ }
1422
+ }
1423
+ for (const change of Object.values(changes)) {
1424
+ const signature = changeSignature(change);
1425
+ const previous = state.candidates.get(change.userId);
1426
+ if (!previous || previous.signature !== signature) {
1427
+ state.candidates.set(change.userId, { signature, since: now, firstChange: { ...change } });
1428
+ state.queue.delete(change.userId);
1429
+ if (stableMs > 0) continue;
1430
+ } else if (now - previous.since < stableMs) continue;
1431
+ const firstChange = state.candidates.get(change.userId).firstChange;
1432
+ if (isShortSession(firstChange, config)) {
1433
+ if (firstChange.status === "stop") {
1434
+ if (await acknowledgeGameChange(ctx, firstChange, logger)) {
1435
+ state.queue.delete(change.userId);
1436
+ state.candidates.delete(change.userId);
1437
+ }
1438
+ continue;
1439
+ }
1440
+ change.suppressEnd = true;
1441
+ }
1442
+ const queued = state.queue.get(change.userId);
1443
+ if (queued?.signature === signature) continue;
1444
+ const user = userMap.get(change.userId);
1445
+ if (!user) continue;
1446
+ change.observedAt = state.candidates.get(change.userId).since;
1447
+ const pendingChannels = new Set(channels.filter((c) => user.effectGroups.includes(c.id)).map((c) => c.id));
1448
+ if (pendingChannels.size) state.queue.set(change.userId, { signature, change, queuedAt: now, pendingChannels });
1449
+ }
1450
+ for (const channel of channels) {
1451
+ if (shouldStop()) return;
1452
+ const entries = [...state.queue.values()].filter((entry) => {
1453
+ const candidate = state.candidates.get(entry.change.userId);
1454
+ return entry.pendingChannels.has(channel.id) && observed.has(userMap.get(entry.change.userId)?.steamId || "") && candidate?.signature === entry.signature && now - candidate.since >= stableMs;
1455
+ });
1456
+ if (!entries.length || now - Math.min(...entries.map((e) => e.queuedAt)) < mergeMs) continue;
1457
+ const eligibleEntries = entries.map((entry) => ({ entry, eligible: eligibleChange(ctx, channel.id, entry.change, config) }));
1458
+ for (const item of eligibleEntries) if (!item.eligible) item.entry.pendingChannels.delete(channel.id);
1459
+ const toSend = eligibleEntries.filter((item) => !!item.eligible);
1460
+ if (!toSend.length) continue;
1461
+ const bot = ctx.bots[`${channel.platform}:${channel.assignee}`] || Object.values(ctx.bots).find(
1462
+ (item) => item.platform === channel.platform && (item.selfId === channel.assignee || item.user?.id === channel.assignee)
1463
+ );
1464
+ if (!bot) {
1465
+ logger.warn(`\u672A\u627E\u5230\u7FA4\u7EC4 ${channel.id} \u5BF9\u5E94\u7684\u673A\u5668\u4EBA\uFF0C\u4FDD\u7559\u5F85\u53D1\u9001\u64AD\u62A5`);
1466
+ continue;
1467
+ }
1468
+ try {
1469
+ const lines = [];
1470
+ for (const item of toSend) {
1471
+ const change = item.eligible.change;
1472
+ const display = {
1473
+ ...change,
1474
+ oldGame: change.oldGame ? await getLocalizedGameName(ctx, change.oldGameId, change.oldGame) : void 0,
1475
+ newGame: change.newGame ? await getLocalizedGameName(ctx, change.newGameId, change.newGame) : void 0
1476
+ };
1477
+ const nickname = await getUserNickname(ctx, change.userId, channel.id);
1478
+ lines.push(`\u2022 ${buildBroadcastText(nickname || change.userName, display)}`);
1479
+ }
1480
+ if (shouldStop()) return;
1481
+ await bot.sendMessage(channel.id, `\u{1F3AE} Steam \u597D\u53CB\u52A8\u6001
1482
+ ${lines.join("\n")}`);
1483
+ for (const item of toSend) {
1484
+ recordCooldown(ctx, item.eligible.keys, config);
1485
+ item.entry.pendingChannels.delete(channel.id);
1486
+ }
1487
+ } catch (error) {
1488
+ logger.warn(`\u7FA4\u7EC4 ${channel.id} \u5408\u5E76\u64AD\u62A5\u5931\u8D25\uFF0C\u5C06\u5728\u4E0B\u6B21\u8F6E\u8BE2\u91CD\u8BD5:`, error);
1489
+ }
1490
+ }
1491
+ for (const [id, entry] of state.queue) {
1492
+ const user = userMap.get(id);
1493
+ for (const channelId of entry.pendingChannels) {
1494
+ if (!channels.some((c) => c.id === channelId) || !user?.effectGroups.includes(channelId)) entry.pendingChannels.delete(channelId);
1495
+ }
1496
+ if (!entry.pendingChannels.size) {
1497
+ if (await acknowledgeGameChange(ctx, entry.change, logger)) {
1498
+ state.queue.delete(id);
1499
+ state.candidates.delete(id);
1500
+ }
1501
+ }
1502
+ }
1503
+ }
1346
1504
  async function updatePlayerHeadshots(ctx, config, logger) {
1347
1505
  const allUserData = await ctx.database.select("SteamUser").execute();
1348
1506
  const steamUserInfo = await getSteamUserInfoByDatabase(
@@ -1390,7 +1548,10 @@ async function detectGameChanges(ctx, allUserData, steamUserInfo, useSteamName,
1390
1548
  }
1391
1549
  continue;
1392
1550
  }
1393
- const playTime = await getCurrentPlayTime(ctx, userData.userId);
1551
+ const session = await getGameSession(ctx, userData.userId);
1552
+ const playDurationMs = session && Number.isFinite(session.startTime) ? Math.max(0, Date.now() - session.startTime) : void 0;
1553
+ const minutes = playDurationMs === void 0 ? 0 : Math.floor(playDurationMs / 6e4);
1554
+ const playTime = minutes > 0 ? formatPlayTime(minutes) : void 0;
1394
1555
  const userName = useSteamName ? player.personaname : userData.userName;
1395
1556
  if (newGame && !oldGame) {
1396
1557
  changes[userData.userId] = {
@@ -1409,7 +1570,8 @@ async function detectGameChanges(ctx, allUserData, steamUserInfo, useSteamName,
1409
1570
  oldGameId,
1410
1571
  newGame,
1411
1572
  newGameId,
1412
- playTime
1573
+ playTime,
1574
+ playDurationMs
1413
1575
  };
1414
1576
  } else if (!newGame && oldGame) {
1415
1577
  changes[userData.userId] = {
@@ -1418,20 +1580,19 @@ async function detectGameChanges(ctx, allUserData, steamUserInfo, useSteamName,
1418
1580
  status: "stop",
1419
1581
  oldGame,
1420
1582
  oldGameId,
1421
- playTime
1583
+ playTime,
1584
+ playDurationMs
1422
1585
  };
1423
1586
  }
1424
1587
  }
1425
1588
  return changes;
1426
1589
  }
1427
- async function getCurrentPlayTime(ctx, userId) {
1428
- const session = await getGameSession(ctx, userId);
1429
- if (!session) return void 0;
1430
- const minutes = Math.floor((Date.now() - session.startTime) / 6e4);
1431
- return minutes > 0 ? formatPlayTime(minutes) : void 0;
1590
+ function isShortSession(change, config) {
1591
+ const threshold = Math.max(0, config.minStopPlayMinutes ?? 10) * 6e4;
1592
+ return (change.status === "stop" || change.status === "change") && change.playDurationMs !== void 0 && change.playDurationMs < threshold;
1432
1593
  }
1433
1594
  function buildBroadcastText(displayName, changeInfo) {
1434
- if (changeInfo.status === "start") {
1595
+ if (changeInfo.status === "start" || changeInfo.status === "change" && changeInfo.suppressEnd) {
1435
1596
  return `${displayName} \u5F00\u59CB\u73A9 ${changeInfo.newGame} \u4E86`;
1436
1597
  }
1437
1598
  if (changeInfo.status === "stop") {
@@ -1454,10 +1615,10 @@ async function sendBroadcast(ctx, bot, channelId, textMessage, playerInfo, chang
1454
1615
  async function acknowledgeGameChange(ctx, changeInfo, logger) {
1455
1616
  try {
1456
1617
  if (changeInfo.status === "start") {
1457
- await startGameSession(ctx, changeInfo.userId, changeInfo.newGame || "");
1618
+ await startGameSession(ctx, changeInfo.userId, changeInfo.newGame || "", changeInfo.observedAt);
1458
1619
  } else if (changeInfo.status === "change") {
1459
1620
  await endGameSession(ctx, changeInfo.userId);
1460
- await startGameSession(ctx, changeInfo.userId, changeInfo.newGame || "");
1621
+ await startGameSession(ctx, changeInfo.userId, changeInfo.newGame || "", changeInfo.observedAt);
1461
1622
  } else {
1462
1623
  await endGameSession(ctx, changeInfo.userId);
1463
1624
  }
@@ -1466,11 +1627,13 @@ async function acknowledgeGameChange(ctx, changeInfo, logger) {
1466
1627
  { userId: changeInfo.userId },
1467
1628
  { lastPlayedGame: changeInfo.newGame || "", lastPlayedGameId: changeInfo.newGameId || "" }
1468
1629
  );
1630
+ return true;
1469
1631
  } catch (error) {
1470
1632
  logger.error(
1471
1633
  `\u64AD\u62A5\u5DF2\u53D1\u9001\uFF0C\u4F46\u66F4\u65B0\u7528\u6237 ${changeInfo.userId} \u7684\u6E38\u620F\u72B6\u6001\u5931\u8D25:`,
1472
1634
  error
1473
1635
  );
1636
+ return false;
1474
1637
  }
1475
1638
  }
1476
1639
  async function downloadPlayerAvatar(ctx, player) {
@@ -1551,10 +1714,18 @@ var Config = import_koishi4.Schema.intersect([
1551
1714
  SteamApiKey: import_koishi4.Schema.string().description(
1552
1715
  "Steam API Key\uFF0C\u83B7\u53D6\u65B9\u5F0F\uFF1Ahttps://partner.steamgames.com/doc/webapi_overview/auth"
1553
1716
  ).role("secret").required(),
1554
- interval: import_koishi4.Schema.number().default(60).min(10).description("\u67E5\u8BE2\u95F4\u9694,\u5355\u4F4D\uFF1A\u79D2"),
1717
+ interval: import_koishi4.Schema.number().default(60).min(10).description("\u67E5\u8BE2\u95F4\u9694\uFF0C\u5355\u4F4D\uFF1A\u79D2\uFF1B\u72B6\u6001\u7A33\u5B9A\u671F\u9700\u7ECF\u540E\u7EED\u8F6E\u8BE2\u786E\u8BA4\uFF0C\u5EFA\u8BAE\u4E0D\u5927\u4E8E\u7A33\u5B9A\u671F"),
1555
1718
  useSteamName: import_koishi4.Schema.boolean().default(true).description("\u4F7F\u7528Steam\u6635\u79F0,\u5173\u95ED\u65F6\u4F7F\u7528\u7684QQ\u6635\u79F0"),
1556
1719
  broadcastWithImage: import_koishi4.Schema.boolean().default(true).description("\u64AD\u62A5\u65F6\u9644\u5E26\u56FE\u7247")
1557
1720
  }).description("\u57FA\u7840\u8BBE\u7F6E"),
1721
+ import_koishi4.Schema.object({
1722
+ mergeBroadcast: import_koishi4.Schema.boolean().default(true).description("\u5408\u5E76\u7A97\u53E3\u5185\u7684\u6E38\u620F\u72B6\u6001\u64AD\u62A5"),
1723
+ mergeWindow: import_koishi4.Schema.number().default(180).min(1).step(1).description("\u5408\u5E76\u64AD\u62A5\u7A97\u53E3\uFF0C\u5355\u4F4D\uFF1A\u79D2"),
1724
+ stabilityPeriod: import_koishi4.Schema.number().default(30).min(0).step(1).description("\u72B6\u6001\u7A33\u5B9A\u671F\uFF0C\u5355\u4F4D\uFF1A\u79D2\uFF1B\u9700\u901A\u8FC7\u540E\u7EED\u8F6E\u8BE2\u786E\u8BA4"),
1725
+ gameBroadcastCooldown: import_koishi4.Schema.number().default(30).min(0).step(1).description("\u540C\u4E00\u7FA4\u4E2D\u540C\u4E00\u7528\u6237\u540C\u4E00\u6E38\u620F\u7684\u64AD\u62A5\u51B7\u5374\u65F6\u95F4\uFF08\u5206\u949F\uFF09\uFF0C0 \u4E3A\u5173\u95ED\uFF1B\u5F00\u59CB\u548C\u7ED3\u675F\u5171\u7528\u51B7\u5374"),
1726
+ minStopPlayMinutes: import_koishi4.Schema.number().default(10).min(0).step(1).description("\u7ED3\u675F\u64AD\u62A5\u6700\u77ED\u6E38\u620F\u65F6\u957F\uFF08\u5206\u949F\uFF09\uFF0C\u8BBE\u4E3A 0 \u5173\u95ED\u8FC7\u6EE4\uFF1B\u65F6\u957F\u672A\u77E5\u65F6\u4ECD\u64AD\u62A5"),
1727
+ immediateBroadcast: import_koishi4.Schema.boolean().default(false).description("\u5373\u65F6\u64AD\u62A5\uFF0C\u8DF3\u8FC7\u5408\u5E76\u7A97\u53E3\u548C\u72B6\u6001\u7A33\u5B9A\u671F")
1728
+ }).description("\u64AD\u62A5\u8BBE\u7F6E"),
1558
1729
  import_koishi4.Schema.object({
1559
1730
  useApifoxProxy: import_koishi4.Schema.boolean().default(true).description(
1560
1731
  "Steam API \u76F4\u8FDE\u5931\u8D25\u65F6\u4F7F\u7528 APIFOX \u516C\u5171\u4EE3\u7406\u515C\u5E95\uFF08\u8BF7\u6C42 URL \u4F1A\u53D1\u9001\u7ED9\u4EE3\u7406\uFF09"
package/lib/types.d.ts CHANGED
@@ -24,6 +24,9 @@ export interface GameChangeInfo {
24
24
  oldGame?: string;
25
25
  newGame?: string;
26
26
  playTime?: string;
27
+ playDurationMs?: number;
28
+ suppressEnd?: boolean;
29
+ observedAt?: number;
27
30
  oldGameId?: string;
28
31
  newGameId?: string;
29
32
  }
package/lib/userdata.d.ts CHANGED
@@ -6,7 +6,7 @@ interface GameSession {
6
6
  /**
7
7
  * 记录用户开始玩游戏
8
8
  */
9
- export declare function startGameSession(ctx: Context, userId: string, gameName: string): Promise<void>;
9
+ export declare function startGameSession(ctx: Context, userId: string, gameName: string, startTime?: number): Promise<void>;
10
10
  /**
11
11
  * 结束游戏会话并返回游玩时长(分钟)
12
12
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@enderhorror/koishi-plugin-steam-friend-status",
3
3
  "description": "查询并播报 Steam 好友状态,支持游戏活动播报名称本地化",
4
- "version": "0.3.3",
4
+ "version": "0.3.5",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/readme.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  自动查询并播报 Steam 好友游戏状态的 Koishi 插件。本版本基于 [koishi-plugin-steam-friend-status-fork@0.3.1](https://www.npmjs.com/package/koishi-plugin-steam-friend-status-fork/v/0.3.1) 修改。
4
4
 
5
+ ## 更新日志
6
+
7
+ ### 0.3.5
8
+
9
+ - 增加同一群中同一用户同一游戏的播报冷却,默认 30 分钟,开始和结束事件共用;可配置为 0 关闭。
10
+ - 冷却期间仍更新游戏状态;切换游戏分别检查新旧游戏,发送失败不会启动冷却。
11
+
12
+ ### 0.3.4
13
+
14
+ - 默认开启群组游戏动态合并播报,合并窗口默认为 180 秒;不同群组独立发送,失败群组在后续轮询重试。
15
+ - 新增状态稳定期,默认 30 秒;需后续轮询确认,降低短时间状态波动产生的播报。
16
+ - 新增结束播报时长阈值,默认少于 10 分钟不播报结束;切换游戏时若前一游戏未达到阈值,仅播报新游戏开始。时长未知时仍播报,阈值设为 0 可关闭过滤。
17
+ - 新增即时播报选项及相关配置;合并播报以文字汇总,不附单人图片。
18
+ - 新安装默认轮询间隔为 60 秒;已有配置保持不变。实际检测与播报时间受轮询间隔影响,待发送队列存于内存。
19
+
5
20
  ## 本版本的主要改动
6
21
 
7
22
  - **长游戏名称布局**:加宽好友列表和活动播报卡片,长游戏名自动换行,减少截断;个人资料游戏名支持长单词换行。
@@ -46,9 +61,23 @@ npm install @enderhorror/koishi-plugin-steam-friend-status
46
61
  | 配置项 | 默认值 | 说明 |
47
62
  | ------------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------- |
48
63
  | SteamApiKey | 无 | 用户查询信息的apikey,可以从 -> [这里](https://partner.steamgames.com/doc/webapi_overview/auth) 获取 |
49
- | interval | 300 | 单位(秒),自动查询信息的时间间隔 |
64
+ | interval | 60 | 单位(秒),自动查询信息的时间间隔,最小 10 秒 |
50
65
  | useSteamName | true | 播报时使用玩家昵称,false为QQ昵称,true为steam昵称 <span style="color:red">red/satori适配器暂时无法获取到用户昵称,建议打开</span> |
51
66
  | broadcastWithImage | true | 播报时附带好友列表图片,关闭可以减少因长图片导致的刷屏 |
67
+ | mergeBroadcast | true | 开启合并播报 |
68
+ | mergeWindow | 180 | 合并播报窗口,单位:秒,最小 1 秒 |
69
+ | stabilityPeriod | 30 | 状态稳定期,单位:秒,最小 0 秒 |
70
+ | gameBroadcastCooldown | 30 | 同一群同一用户同一游戏的开始与结束共用冷却(分钟);0 关闭,冷却在内存中,重启清空 |
71
+ | minStopPlayMinutes | 10 | 少于该时长(分钟)不播报结束;0 表示关闭过滤,时长未知仍播报 |
72
+ | immediateBroadcast | false | 开启后即时播报,跳过合并窗口和状态稳定期 |
73
+
74
+ 状态变化通过轮询发现和确认;稳定期不是精确定时,实际确认可能延迟至下一次轮询。默认查询间隔为 60 秒,若希望更及时地确认默认 30 秒稳定期,可将 `interval` 调整至 30 秒或更短(最小 10 秒);更频繁的轮询会增加 Steam API 请求量。已有 `interval` 配置不会自动改变。
75
+
76
+ 同一游戏的开始和结束播报共用冷却:成功发送任意一种后,冷却内不再播报该用户该游戏,但仍更新状态。切换游戏时分别检查新旧游戏;冷却按群隔离,发送失败不计入冷却,插件重启后清空。
77
+
78
+ 游戏切换时,如果上一个游戏未满阈值,只播报新游戏开始;结束状态仍会更新。时长以插件首次检测到开始和结束的时间估算,而非 Steam 官方精确游戏时长;轮询间隔可能影响估算,旧会话可能受升级前播报延迟影响。
79
+
80
+ > 合并播报以文字汇总发送,不附单人图片。候选状态和待发送队列保存在内存中,插件重启会清空队列;未成功确认的状态将在后续轮询重新检测。发送失败的群组会在下一次轮询时重试;不同群组独立发送。
52
81
 
53
82
  ## 其他说明
54
83
 
package/src/broadcast.ts CHANGED
@@ -16,10 +16,46 @@ export interface SteamBroadcastConfig {
16
16
  SteamApiKey: string;
17
17
  useSteamName: boolean;
18
18
  broadcastWithImage: boolean;
19
+ mergeBroadcast?: boolean;
20
+ immediateBroadcast?: boolean;
21
+ mergeWindow?: number;
22
+ stabilityPeriod?: number;
23
+ minStopPlayMinutes?: number;
24
+ gameBroadcastCooldown?: number;
19
25
  }
20
26
 
21
27
  type SteamPlayer = SteamUserInfo["response"]["players"][number];
22
28
 
29
+ // 冷却仅针对已成功发送的动态,群组和用户之间相互隔离。
30
+ const broadcastCooldowns = new WeakMap<Context, Map<string, number>>();
31
+ function cooldownKey(channelId: string, userId: string, id: string | undefined, name: string | undefined): string {
32
+ return JSON.stringify([channelId, userId, id ? `id:${id}` : `name:${(name || "").trim().toLowerCase()}`]);
33
+ }
34
+ function eligibleChange(ctx: Context, channelId: string, change: GameChangeInfo, config: SteamBroadcastConfig): { change: GameChangeInfo; keys: string[] } | null {
35
+ let cache = broadcastCooldowns.get(ctx);
36
+ if (!cache) { cache = new Map(); broadcastCooldowns.set(ctx, cache); }
37
+ const now = Date.now();
38
+ const duration = Math.max(0, config.gameBroadcastCooldown ?? 30) * 60_000;
39
+ for (const [key, expires] of cache) if (expires <= now) cache.delete(key);
40
+ const oldKey = change.oldGame ? cooldownKey(channelId, change.userId, change.oldGameId, change.oldGame) : "";
41
+ const newKey = change.newGame ? cooldownKey(channelId, change.userId, change.newGameId, change.newGame) : "";
42
+ const oldAllowed = !!oldKey && !change.suppressEnd && (!duration || !cache.has(oldKey));
43
+ const newAllowed = !!newKey && (!duration || !cache.has(newKey));
44
+ if (change.status === "start") return newAllowed ? { change, keys: [newKey] } : null;
45
+ if (change.status === "stop") return oldAllowed ? { change, keys: [oldKey] } : null;
46
+ if (oldAllowed && newAllowed) return { change, keys: [...new Set([oldKey, newKey])] };
47
+ if (newAllowed) return { change: { ...change, status: "start", oldGame: undefined, oldGameId: undefined, playTime: undefined }, keys: [newKey] };
48
+ if (oldAllowed) return { change: { ...change, status: "stop", newGame: undefined, newGameId: undefined }, keys: [oldKey] };
49
+ return null;
50
+ }
51
+ function recordCooldown(ctx: Context, keys: string[], config: SteamBroadcastConfig): void {
52
+ const duration = Math.max(0, config.gameBroadcastCooldown ?? 30) * 60_000;
53
+ if (!duration) return;
54
+ const cache = broadcastCooldowns.get(ctx)!;
55
+ const expires = Date.now() + duration;
56
+ for (const key of keys) cache.set(key, expires);
57
+ }
58
+
23
59
  // 轮询 Steam 状态,并按用户绑定过的群组进行播报
24
60
  export async function pollSteamBroadcast(
25
61
  ctx: Context,
@@ -67,6 +103,10 @@ export async function pollSteamBroadcast(
67
103
  logger,
68
104
  shouldStop,
69
105
  );
106
+ if (config.mergeBroadcast !== false && !config.immediateBroadcast) {
107
+ await processMergedBroadcast(ctx, config, logger, shouldStop, channels, allUserData, steamUserInfo, changes);
108
+ return;
109
+ }
70
110
  if (Object.keys(changes).length === 0) {
71
111
  logger.debug("本轮没有检测到游戏状态变化");
72
112
  return;
@@ -88,6 +128,13 @@ export async function pollSteamBroadcast(
88
128
  continue;
89
129
  }
90
130
 
131
+ if (isShortSession(changeInfo, config)) {
132
+ if (changeInfo.status === "stop") {
133
+ await acknowledgeGameChange(ctx, changeInfo, logger);
134
+ continue;
135
+ }
136
+ changeInfo.suppressEnd = true;
137
+ }
91
138
  const playerInfo = steamUserInfo.response.players.find(
92
139
  (player) => player.steamid === user.steamId,
93
140
  );
@@ -103,6 +150,12 @@ export async function pollSteamBroadcast(
103
150
  for (const channel of targetChannels) {
104
151
  if (shouldStop()) return;
105
152
 
153
+ const eligible = eligibleChange(ctx, channel.id, changeInfo, config);
154
+ if (!eligible) continue;
155
+ const channelDisplay: GameChangeInfo = { ...displayChange, ...eligible.change,
156
+ oldGame: eligible.change.oldGame ? displayChange.oldGame : undefined,
157
+ newGame: eligible.change.newGame ? displayChange.newGame : undefined,
158
+ };
106
159
  const directBot = ctx.bots[`${channel.platform}:${channel.assignee}`];
107
160
  const bot =
108
161
  directBot ||
@@ -128,7 +181,7 @@ export async function pollSteamBroadcast(
128
181
  );
129
182
  const textMessage = buildBroadcastText(
130
183
  channelNickname || changeInfo.userName,
131
- displayChange,
184
+ channelDisplay,
132
185
  );
133
186
 
134
187
  try {
@@ -138,10 +191,11 @@ export async function pollSteamBroadcast(
138
191
  channel.id,
139
192
  textMessage,
140
193
  playerInfo,
141
- displayChange,
194
+ channelDisplay,
142
195
  config.broadcastWithImage,
143
196
  logger,
144
197
  );
198
+ recordCooldown(ctx, eligible.keys, config);
145
199
  logger.debug(
146
200
  `已向群组 ${channel.id} 播报用户 ${changeInfo.userId}: ${textMessage}`,
147
201
  );
@@ -157,6 +211,118 @@ export async function pollSteamBroadcast(
157
211
  }
158
212
  }
159
213
 
214
+ // 运行期队列:候选状态需两次成功轮询确认,群组发送成功后不重复投递。
215
+ type Candidate = { signature: string; since: number; firstChange: GameChangeInfo };
216
+ type QueuedChange = { signature: string; change: GameChangeInfo; queuedAt: number; pendingChannels: Set<string> };
217
+ type MergeState = { candidates: Map<string, Candidate>; queue: Map<string, QueuedChange> };
218
+ const mergeStates = new WeakMap<Context, MergeState>();
219
+ function getMergeState(ctx: Context): MergeState {
220
+ let state = mergeStates.get(ctx);
221
+ if (!state) { state = { candidates: new Map(), queue: new Map() }; mergeStates.set(ctx, state); }
222
+ return state;
223
+ }
224
+ function changeSignature(change: GameChangeInfo): string {
225
+ return JSON.stringify([change.oldGame || "", change.newGame || "", change.newGameId || ""]);
226
+ }
227
+ async function processMergedBroadcast(
228
+ ctx: Context, config: SteamBroadcastConfig, logger: PluginLogger, shouldStop: () => boolean,
229
+ channels: any[], users: SteamUser[], steamUserInfo: SteamUserInfo, changes: Record<string, GameChangeInfo>,
230
+ ): Promise<void> {
231
+ const state = getMergeState(ctx);
232
+ const now = Date.now();
233
+ const stableMs = Math.max(0, config.stabilityPeriod ?? 30) * 1000;
234
+ const mergeMs = Math.max(0, config.mergeWindow ?? 180) * 1000;
235
+ const observed = new Set(steamUserInfo.response.players.map((p) => p.steamid));
236
+ const userMap = new Map(users.map((u) => [u.userId, u]));
237
+ // 消失、解绑或恢复原状时取消过期状态;未返回玩家时不认定稳定。
238
+ for (const id of new Set([...state.candidates.keys(), ...state.queue.keys()])) {
239
+ const user = userMap.get(id);
240
+ if (!user || !observed.has(user.steamId) || !changes[id]) {
241
+ state.candidates.delete(id);
242
+ if (!user || (observed.has(user.steamId) && !changes[id])) state.queue.delete(id);
243
+ }
244
+ }
245
+ for (const change of Object.values(changes)) {
246
+ const signature = changeSignature(change);
247
+ const previous = state.candidates.get(change.userId);
248
+ if (!previous || previous.signature !== signature) {
249
+ state.candidates.set(change.userId, { signature, since: now, firstChange: { ...change } });
250
+ state.queue.delete(change.userId);
251
+ if (stableMs > 0) continue;
252
+ } else if (now - previous.since < stableMs) continue;
253
+ const firstChange = state.candidates.get(change.userId)!.firstChange;
254
+ if (isShortSession(firstChange, config)) {
255
+ if (firstChange.status === "stop") {
256
+ if (await acknowledgeGameChange(ctx, firstChange, logger)) {
257
+ state.queue.delete(change.userId);
258
+ state.candidates.delete(change.userId);
259
+ }
260
+ continue;
261
+ }
262
+ change.suppressEnd = true;
263
+ }
264
+ const queued = state.queue.get(change.userId);
265
+ if (queued?.signature === signature) continue;
266
+ const user = userMap.get(change.userId);
267
+ if (!user) continue;
268
+ change.observedAt = state.candidates.get(change.userId)!.since;
269
+ const pendingChannels = new Set(channels.filter((c) => user.effectGroups.includes(c.id)).map((c) => c.id as string));
270
+ if (pendingChannels.size) state.queue.set(change.userId, { signature, change, queuedAt: now, pendingChannels });
271
+ }
272
+ // 每个群从其首条稳定动态入队开始计时,到期后一次汇总。
273
+ for (const channel of channels) {
274
+ if (shouldStop()) return;
275
+ const entries = [...state.queue.values()].filter((entry) => {
276
+ const candidate = state.candidates.get(entry.change.userId);
277
+ return entry.pendingChannels.has(channel.id)
278
+ && observed.has(userMap.get(entry.change.userId)?.steamId || "")
279
+ && candidate?.signature === entry.signature
280
+ && now - candidate.since >= stableMs;
281
+ });
282
+ if (!entries.length || now - Math.min(...entries.map((e) => e.queuedAt)) < mergeMs) continue;
283
+ const eligibleEntries = entries.map((entry) => ({ entry, eligible: eligibleChange(ctx, channel.id, entry.change, config) }));
284
+ for (const item of eligibleEntries) if (!item.eligible) item.entry.pendingChannels.delete(channel.id);
285
+ const toSend = eligibleEntries.filter((item) => !!item.eligible);
286
+ if (!toSend.length) continue;
287
+ const bot = ctx.bots[`${channel.platform}:${channel.assignee}`] || Object.values(ctx.bots).find(
288
+ (item) => item.platform === channel.platform && (item.selfId === channel.assignee || item.user?.id === channel.assignee),
289
+ );
290
+ if (!bot) { logger.warn(`未找到群组 ${channel.id} 对应的机器人,保留待发送播报`); continue; }
291
+ try {
292
+ const lines: string[] = [];
293
+ for (const item of toSend) {
294
+ const change = item.eligible!.change;
295
+ const display: GameChangeInfo = {
296
+ ...change,
297
+ oldGame: change.oldGame ? await getLocalizedGameName(ctx, change.oldGameId, change.oldGame) : undefined,
298
+ newGame: change.newGame ? await getLocalizedGameName(ctx, change.newGameId, change.newGame) : undefined,
299
+ };
300
+ const nickname = await getUserNickname(ctx, change.userId, channel.id);
301
+ lines.push(`• ${buildBroadcastText(nickname || change.userName, display)}`);
302
+ }
303
+ if (shouldStop()) return;
304
+ await bot.sendMessage(channel.id, `🎮 Steam 好友动态\n${lines.join("\n")}`);
305
+ for (const item of toSend) {
306
+ recordCooldown(ctx, item.eligible!.keys, config);
307
+ item.entry.pendingChannels.delete(channel.id);
308
+ }
309
+ } catch (error) { logger.warn(`群组 ${channel.id} 合并播报失败,将在下次轮询重试:`, error); }
310
+ }
311
+ for (const [id, entry] of state.queue) {
312
+ const user = userMap.get(id);
313
+ // 群组已关闭或解绑时不再继续投递。
314
+ for (const channelId of entry.pendingChannels) {
315
+ if (!channels.some((c) => c.id === channelId) || !user?.effectGroups.includes(channelId)) entry.pendingChannels.delete(channelId);
316
+ }
317
+ if (!entry.pendingChannels.size) {
318
+ if (await acknowledgeGameChange(ctx, entry.change, logger)) {
319
+ state.queue.delete(id);
320
+ state.candidates.delete(id);
321
+ }
322
+ }
323
+ }
324
+ }
325
+
160
326
  // 更新所有已绑定用户的头像
161
327
  export async function updatePlayerHeadshots(
162
328
  ctx: Context,
@@ -224,7 +390,10 @@ async function detectGameChanges(
224
390
  continue;
225
391
  }
226
392
 
227
- const playTime = await getCurrentPlayTime(ctx, userData.userId);
393
+ const session = await getGameSession(ctx, userData.userId);
394
+ const playDurationMs = session && Number.isFinite(session.startTime) ? Math.max(0, Date.now() - session.startTime) : undefined;
395
+ const minutes = playDurationMs === undefined ? 0 : Math.floor(playDurationMs / 60000);
396
+ const playTime = minutes > 0 ? formatPlayTime(minutes) : undefined;
228
397
  const userName = useSteamName ? player.personaname : userData.userName;
229
398
 
230
399
  if (newGame && !oldGame) {
@@ -245,6 +414,7 @@ async function detectGameChanges(
245
414
  newGame,
246
415
  newGameId,
247
416
  playTime,
417
+ playDurationMs,
248
418
  };
249
419
  } else if (!newGame && oldGame) {
250
420
  changes[userData.userId] = {
@@ -254,6 +424,7 @@ async function detectGameChanges(
254
424
  oldGame,
255
425
  oldGameId,
256
426
  playTime,
427
+ playDurationMs,
257
428
  };
258
429
  }
259
430
  }
@@ -261,22 +432,17 @@ async function detectGameChanges(
261
432
  return changes;
262
433
  }
263
434
 
264
- async function getCurrentPlayTime(
265
- ctx: Context,
266
- userId: string,
267
- ): Promise<string | undefined> {
268
- const session = await getGameSession(ctx, userId);
269
- if (!session) return undefined;
270
-
271
- const minutes = Math.floor((Date.now() - session.startTime) / 60000);
272
- return minutes > 0 ? formatPlayTime(minutes) : undefined;
435
+ function isShortSession(change: GameChangeInfo, config: SteamBroadcastConfig): boolean {
436
+ const threshold = Math.max(0, config.minStopPlayMinutes ?? 10) * 60_000;
437
+ return (change.status === "stop" || change.status === "change")
438
+ && change.playDurationMs !== undefined && change.playDurationMs < threshold;
273
439
  }
274
440
 
275
441
  function buildBroadcastText(
276
442
  displayName: string,
277
443
  changeInfo: GameChangeInfo,
278
444
  ): string {
279
- if (changeInfo.status === "start") {
445
+ if (changeInfo.status === "start" || (changeInfo.status === "change" && changeInfo.suppressEnd)) {
280
446
  return `${displayName} 开始玩 ${changeInfo.newGame} 了`;
281
447
  }
282
448
 
@@ -320,13 +486,13 @@ async function acknowledgeGameChange(
320
486
  ctx: Context,
321
487
  changeInfo: GameChangeInfo,
322
488
  logger: PluginLogger,
323
- ): Promise<void> {
489
+ ): Promise<boolean> {
324
490
  try {
325
491
  if (changeInfo.status === "start") {
326
- await startGameSession(ctx, changeInfo.userId, changeInfo.newGame || "");
492
+ await startGameSession(ctx, changeInfo.userId, changeInfo.newGame || "", changeInfo.observedAt);
327
493
  } else if (changeInfo.status === "change") {
328
494
  await endGameSession(ctx, changeInfo.userId);
329
- await startGameSession(ctx, changeInfo.userId, changeInfo.newGame || "");
495
+ await startGameSession(ctx, changeInfo.userId, changeInfo.newGame || "", changeInfo.observedAt);
330
496
  } else {
331
497
  await endGameSession(ctx, changeInfo.userId);
332
498
  }
@@ -336,11 +502,13 @@ async function acknowledgeGameChange(
336
502
  { userId: changeInfo.userId },
337
503
  { lastPlayedGame: changeInfo.newGame || "", lastPlayedGameId: changeInfo.newGameId || "" },
338
504
  );
505
+ return true;
339
506
  } catch (error) {
340
507
  logger.error(
341
508
  `播报已发送,但更新用户 ${changeInfo.userId} 的游戏状态失败:`,
342
509
  error,
343
510
  );
511
+ return false;
344
512
  }
345
513
  }
346
514
 
package/src/index.ts CHANGED
@@ -70,7 +70,7 @@ export const Config = Schema.intersect([
70
70
  interval: Schema.number()
71
71
  .default(60)
72
72
  .min(10)
73
- .description("查询间隔,单位:秒"),
73
+ .description("查询间隔,单位:秒;状态稳定期需经后续轮询确认,建议不大于稳定期"),
74
74
  useSteamName: Schema.boolean()
75
75
  .default(true)
76
76
  .description("使用Steam昵称,关闭时使用的QQ昵称"),
@@ -79,6 +79,35 @@ export const Config = Schema.intersect([
79
79
  .description("播报时附带图片"),
80
80
  }).description("基础设置"),
81
81
 
82
+ Schema.object({
83
+ mergeBroadcast: Schema.boolean()
84
+ .default(true)
85
+ .description("合并窗口内的游戏状态播报"),
86
+ mergeWindow: Schema.number()
87
+ .default(180)
88
+ .min(1)
89
+ .step(1)
90
+ .description("合并播报窗口,单位:秒"),
91
+ stabilityPeriod: Schema.number()
92
+ .default(30)
93
+ .min(0)
94
+ .step(1)
95
+ .description("状态稳定期,单位:秒;需通过后续轮询确认"),
96
+ gameBroadcastCooldown: Schema.number()
97
+ .default(30)
98
+ .min(0)
99
+ .step(1)
100
+ .description("同一群中同一用户同一游戏的播报冷却时间(分钟),0 为关闭;开始和结束共用冷却"),
101
+ minStopPlayMinutes: Schema.number()
102
+ .default(10)
103
+ .min(0)
104
+ .step(1)
105
+ .description("结束播报最短游戏时长(分钟),设为 0 关闭过滤;时长未知时仍播报"),
106
+ immediateBroadcast: Schema.boolean()
107
+ .default(false)
108
+ .description("即时播报,跳过合并窗口和状态稳定期"),
109
+ }).description("播报设置"),
110
+
82
111
  Schema.object({
83
112
  useApifoxProxy: Schema.boolean()
84
113
  .default(true)
@@ -154,6 +183,12 @@ export interface PluginConfig {
154
183
  interval: number;
155
184
  useSteamName: boolean;
156
185
  broadcastWithImage: boolean;
186
+ mergeBroadcast: boolean;
187
+ mergeWindow: number;
188
+ stabilityPeriod: number;
189
+ immediateBroadcast: boolean;
190
+ minStopPlayMinutes: number;
191
+ gameBroadcastCooldown: number;
157
192
  useApifoxProxy: boolean;
158
193
  maxRetries: number;
159
194
  showcardmode: "1" | "2";
package/src/types.ts CHANGED
@@ -31,6 +31,9 @@ export interface GameChangeInfo {
31
31
  oldGame?: string;
32
32
  newGame?: string;
33
33
  playTime?: string;
34
+ playDurationMs?: number;
35
+ suppressEnd?: boolean;
36
+ observedAt?: number;
34
37
  oldGameId?: string;
35
38
  newGameId?: string;
36
39
  }
package/src/userdata.ts CHANGED
@@ -98,11 +98,11 @@ async function saveGameSessionsLocked(ctx: Context, data: GameSessionsData): Pro
98
98
  /**
99
99
  * 记录用户开始玩游戏
100
100
  */
101
- export async function startGameSession(ctx: Context, userId: string, gameName: string): Promise<void> {
101
+ export async function startGameSession(ctx: Context, userId: string, gameName: string, startTime: number = Date.now()): Promise<void> {
102
102
  const sessions = await loadGameSessionsLocked(ctx);
103
103
  sessions[userId] = {
104
104
  gameName,
105
- startTime: Date.now(),
105
+ startTime,
106
106
  };
107
107
  await saveGameSessionsLocked(ctx, sessions);
108
108
  }